(function() { (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", "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.", "1401": "The first argument should be the destination object", "1402": "The 'visible' property of %s is deprecated, use 'enabled' instead please.", "1403": "Sorry, cc.audioEngine.willPlayMusic is removed.", "1404": "cc.spriteFrameCache is removed, please use cc.loader to load and cache sprite frames of atlas format.", "1405": "The '%s' will be removed in v2.0, please use '%s' instead.", "1406": "'%s.%s' is removed", "1407": "cc.pool is being removed from v2.0, you are getting cc.js.Pool 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.", "1512": "cc.Scheduler: updateFunc parameter is deprecated in scheduleUpdate function, and will be removed in v2.0", "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", "1600": "getZOrder is deprecated. Please use getLocalZOrder instead.", "1601": "setZOrder is deprecated. Please use setLocalZOrder instead.", "1602": "RotationX != RotationY. Don't know which one to return", "1603": "ScaleX != ScaleY. Don't know which one to return", "1605": "child already added. It can't be added again", "1606": "child must be non-null", "1607": "removeFromParentAndCleanup is deprecated. Use removeFromParent instead", "1608": "boundingBox is deprecated. Use getBoundingBox instead", "1609": "argument tag is an invalid tag", "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", "1614": "resumeSchedulerAndActions is deprecated, please use resume instead.", "1615": "pauseSchedulerAndActions is deprecated, please use pause instead.", "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", "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.", "2000": "Don't call this method if the event is for touch.", "2200": "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", "2604": "setDisplayFrame is deprecated, please use setSpriteFrame instead.", "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", "2710": "Sprite.initWithTexture(): Argument must be non-nil", "2712": "Invalid spriteFrameName", "3002": "textureForKey is deprecated. Please use getTextureForKey instead.", "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", "3118": "contentSize parameter is deprecated and ignored for cc.Texture2D initWithData function.", "3119": "Lazy init texture with image element failed due to image loading failure: %s", "3300": "Rect width exceeds maximum margin: %s", "3400": "Rect height exceeds maximum margin: %s", "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.", "3629": "attribute must be type object", "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 construct a dummy instance of the "%s" class using `new` behind the scenes. This is for getting default values declared in TypeScript. Please ensure the class will be able to construct during script\'s initialization. %s.', "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.Integer\n default: 0 // <--\n})\nvalue;\n// After:\n@property({\n type: cc.Integer\n})\nvalue = 0; // <--', "3654": 'Please specifiy a default value for "%s" property at its declaration:\n \n// Before:\n@property(...)\nvalue; \n// After:\n@property(...)\nvalue = 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}', "3656": "The default value of %s.%s must be an empty string. (changed since 1.8)", "3657": "The value assigned to %s should be Texture2D object, not url string. Since 1.8, \nyou can declare a texture object directly in properties by using: \n \n{\n default: null,\n type: cc.Texture2D // use 'type:' instead of 'url:'\n}", "3658": "browser does not support getters", "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", "3908": "animation not added or already removed", "3912": "already-playing", "4000": "Sorry, the cc.Font has been modified from Raw Asset to Asset. Please load the font asset before using.", "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.", "4100": "Property padding is deprecated, please use paddingLeft, paddingRight, paddingTop and paddingBottom instead", "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.", "4903": "Can not get class '%s'", "4914": "Resources url '%s' does not exist.", "4915": "Pack indices and data do not match in size", "4916": "Failed to download package for %s", "4920": "Sorry, you shouldn't use id as item identity any more, please use url or uuid instead, the current id is being set as url: (%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", "4931": "Download Uuid: can not find type of raw asset[ %s ]: %s", "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", "5000": "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'", "5400": "'%s' is deprecated, use '%s' instead please.", "5401": "'%s' is deprecated, use '%s' instead please.", "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't work with 'get/set' !", "5501": "'notify' must work with 'default' !", "5502": "Invalid url of %s.%s", "5503": "The 'url' attribute of '%s.%s' is undefined when loading script.", "5504": "The 'url' type of '%s.%s' must be child class of cc.RawAsset.", "5505": "The 'url' type of '%s.%s' must not be child class of cc.Asset, otherwise you should use 'type: %s' instead.", "5506": "Can not specify 'type' attribute for '%s.%s', because its 'url' is already defined.", "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 'Float' or '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.", "5600": "Argument must be non-nil", "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.", "6000": "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", "6031": "cc.ParticleSystem: unknown image format with Data", "6032": "cc.ParticleSystem.initWithDictionary() : error loading the texture", "6200": "Canvas doesn't support mesh slot!", "6300": "only cc.DrawNode is accepted as stencil", "6301": "Stencil buffer is not enabled.", "6302": "Nesting more than %d stencils is not supported. Everything will be drawn without stencil for this node and its children.", "6400": "asset.url is not usable in core process", "6401": "asset.urls 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", "6701": "Should not add Canvas to a node which already contains a renderer component (%s).", "6702": "Should not add Canvas to a node which size is already used by its other component.", "6703": "Can't initialise DrawingPrimitiveWebGL. context need is WebGLRenderingContext", "6704": "Polygon's point must greater than 2", "6705": "Argument must be non-nil", "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", "7000": "Failed to init asset's raw path.", "7001": "Should not load '%s' from script dynamically, unless it is placed in the 'resources' folder.", "7002": "Sorry can not load '%s' because it is not placed in the 'resources' folder.", "7003": "Failed to init builtin asset's raw path.", "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", "7214": "propertiesForGID is deprecated. Please use getPropertiesForGID instead.", "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", "7505": "Invalid type of atlasFile, atlas should be registered as raw asset.", "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", "8000": "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.", "9000": "Stencil manager does not support level bigger than %d in this device.", "9001": "Stencil manager is already empty, cannot pop any mask", "0100": "%s not yet implemented." }; }), {} ], 2: [ (function(require, module, exports) { require("../core/platform/CCClass"); var misc = require("../core/utils/misc"); cc.Action = cc.Class({ name: "cc.Action", ctor: function() { this.originalTarget = null; this.target = null; this.tag = cc.Action.TAG_INVALID; }, clone: function() { var action = new cc.Action(); action.originalTarget = null; action.target = null; action.tag = this.tag; return action; }, isDone: function() { return true; }, startWithTarget: function(target) { this.originalTarget = target; this.target = target; }, stop: function() { this.target = null; }, step: function(dt) { cc.logID(1006); }, update: function(dt) { cc.logID(1007); }, getTarget: function() { return this.target; }, setTarget: function(target) { this.target = target; }, getOriginalTarget: function() { return this.originalTarget; }, setOriginalTarget: function(originalTarget) { this.originalTarget = originalTarget; }, getTag: function() { return this.tag; }, setTag: function(tag) { this.tag = tag; }, retain: function() {}, release: function() {} }); cc.Action.TAG_INVALID = -1; cc.FiniteTimeAction = cc.Class({ name: "cc.FiniteTimeAction", extends: cc.Action, ctor: function() { this._duration = 0; }, getDuration: function() { return this._duration * (this._timesForRepeat || 1); }, setDuration: function(duration) { this._duration = duration; }, reverse: function() { cc.logID(1008); return null; }, clone: function() { return new cc.FiniteTimeAction(); } }); cc.Speed = cc.Class({ name: "cc.Speed", extends: cc.Action, ctor: function(action, speed) { this._speed = 0; this._innerAction = null; action && this.initWithAction(action, speed); }, getSpeed: function() { return this._speed; }, setSpeed: function(speed) { this._speed = speed; }, initWithAction: function(action, speed) { if (!action) { cc.errorID(1021); return false; } this._innerAction = action; this._speed = speed; return true; }, clone: function() { var action = new cc.Speed(); action.initWithAction(this._innerAction.clone(), this._speed); return action; }, startWithTarget: function(target) { cc.Action.prototype.startWithTarget.call(this, target); this._innerAction.startWithTarget(target); }, stop: function() { this._innerAction.stop(); cc.Action.prototype.stop.call(this); }, step: function(dt) { this._innerAction.step(dt * this._speed); }, isDone: function() { return this._innerAction.isDone(); }, reverse: function() { return new cc.Speed(this._innerAction.reverse(), this._speed); }, setInnerAction: function(action) { this._innerAction !== action && (this._innerAction = action); }, getInnerAction: function() { 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(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() { 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() { return this._boundarySet; }, setBoudarySet: function(value) { this._boundarySet = value; }, initWithTarget: function(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(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() { return !this._followedNode.activeInHierarchy; }, stop: function() { this.target = null; cc.Action.prototype.stop.call(this); } }); cc.follow = function(followedNode, rect) { return new cc.Follow(followedNode, rect); }; }), { "../core/platform/CCClass": 161, "../core/utils/misc": 243 } ], 3: [ (function(require, module, exports) { 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(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(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() { var action = new cc.CardinalSplineTo(); action.initWithDuration(this._duration, cloneControlPoints(this._points), this._tension); return action; }, startWithTarget: function(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(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() { var reversePoints = reverseControlPoints(this._points); return cc.cardinalSplineTo(this._duration, reversePoints, this._tension); }, updatePosition: function(newPos) { this.target.setPosition(newPos); this._previousPosition = newPos; }, getPoints: function() { return this._points; }, setPoints: function(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(duration, points, tension) { this._startPosition = cc.v2(0, 0); void 0 !== tension && this.initWithDuration(duration, points, tension); }, startWithTarget: function(target) { cc.CardinalSplineTo.prototype.startWithTarget.call(this, target); this._startPosition.x = target.x; this._startPosition.y = target.y; }, reverse: function() { 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(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() { 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(dt, points) { points && this.initWithDuration(dt, points); }, initWithDuration: function(dt, points) { return cc.CardinalSplineTo.prototype.initWithDuration.call(this, dt, points, .5); }, clone: function() { 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(dt, points) { points && this.initWithDuration(dt, points); }, initWithDuration: function(dt, points) { return cc.CardinalSplineTo.prototype.initWithDuration.call(this, dt, points, .5); }, clone: function() { 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) { cc.easeIn = function(rate) { return { _rate: rate, easing: function(dt) { return Math.pow(dt, this._rate); }, reverse: function() { return cc.easeIn(1 / this._rate); } }; }; cc.easeOut = function(rate) { return { _rate: rate, easing: function(dt) { return Math.pow(dt, 1 / this._rate); }, reverse: function() { return cc.easeOut(1 / this._rate); } }; }; cc.easeInOut = function(rate) { return { _rate: rate, easing: function(dt) { dt *= 2; return dt < 1 ? .5 * Math.pow(dt, this._rate) : 1 - .5 * Math.pow(2 - dt, this._rate); }, reverse: function() { return cc.easeInOut(this._rate); } }; }; var _easeExponentialInObj = { easing: function(dt) { return 0 === dt ? 0 : Math.pow(2, 10 * (dt - 1)); }, reverse: function() { return _easeExponentialOutObj; } }; cc.easeExponentialIn = function() { return _easeExponentialInObj; }; var _easeExponentialOutObj = { easing: function(dt) { return 1 === dt ? 1 : 1 - Math.pow(2, -10 * dt); }, reverse: function() { return _easeExponentialInObj; } }; cc.easeExponentialOut = function() { return _easeExponentialOutObj; }; var _easeExponentialInOutObj = { easing: function(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() { return _easeExponentialInOutObj; } }; cc.easeExponentialInOut = function() { return _easeExponentialInOutObj; }; var _easeSineInObj = { easing: function(dt) { return 0 === dt || 1 === dt ? dt : -1 * Math.cos(dt * Math.PI / 2) + 1; }, reverse: function() { return _easeSineOutObj; } }; cc.easeSineIn = function() { return _easeSineInObj; }; var _easeSineOutObj = { easing: function(dt) { return 0 === dt || 1 === dt ? dt : Math.sin(dt * Math.PI / 2); }, reverse: function() { return _easeSineInObj; } }; cc.easeSineOut = function() { return _easeSineOutObj; }; var _easeSineInOutObj = { easing: function(dt) { return 0 === dt || 1 === dt ? dt : -.5 * (Math.cos(Math.PI * dt) - 1); }, reverse: function() { return _easeSineInOutObj; } }; cc.easeSineInOut = function() { return _easeSineInOutObj; }; var _easeElasticInObj = { easing: function(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() { return _easeElasticOutObj; } }; cc.easeElasticIn = function(period) { if (period && .3 !== period) return { _period: period, easing: function(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() { return cc.easeElasticOut(this._period); } }; return _easeElasticInObj; }; var _easeElasticOutObj = { easing: function(dt) { return 0 === dt || 1 === dt ? dt : Math.pow(2, -10 * dt) * Math.sin((dt - .075) * Math.PI * 2 / .3) + 1; }, reverse: function() { return _easeElasticInObj; } }; cc.easeElasticOut = function(period) { if (period && .3 !== period) return { _period: period, easing: function(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() { return cc.easeElasticIn(this._period); } }; return _easeElasticOutObj; }; cc.easeElasticInOut = function(period) { period = period || .3; return { _period: period, easing: function(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() { 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(dt) { return 1 - _bounceTime(1 - dt); }, reverse: function() { return _easeBounceOutObj; } }; cc.easeBounceIn = function() { return _easeBounceInObj; }; var _easeBounceOutObj = { easing: function(dt) { return _bounceTime(dt); }, reverse: function() { return _easeBounceInObj; } }; cc.easeBounceOut = function() { return _easeBounceOutObj; }; var _easeBounceInOutObj = { easing: function(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() { return _easeBounceInOutObj; } }; cc.easeBounceInOut = function() { return _easeBounceInOutObj; }; var _easeBackInObj = { easing: function(time1) { var overshoot = 1.70158; return 0 === time1 || 1 === time1 ? time1 : time1 * time1 * ((overshoot + 1) * time1 - overshoot); }, reverse: function() { return _easeBackOutObj; } }; cc.easeBackIn = function() { return _easeBackInObj; }; var _easeBackOutObj = { easing: function(time1) { var overshoot = 1.70158; time1 -= 1; return time1 * time1 * ((overshoot + 1) * time1 + overshoot) + 1; }, reverse: function() { return _easeBackInObj; } }; cc.easeBackOut = function() { return _easeBackOutObj; }; var _easeBackInOutObj = { easing: function(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() { return _easeBackInOutObj; } }; cc.easeBackInOut = function() { return _easeBackInOutObj; }; cc.easeBezierAction = function(a, b, c, d) { return { easing: function(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() { return cc.easeBezierAction(d, c, b, a); } }; }; var _easeQuadraticActionIn = { easing: function(time) { return Math.pow(time, 2); }, reverse: function() { return _easeQuadraticActionIn; } }; cc.easeQuadraticActionIn = function() { return _easeQuadraticActionIn; }; var _easeQuadraticActionOut = { easing: function(time) { return -time * (time - 2); }, reverse: function() { return _easeQuadraticActionOut; } }; cc.easeQuadraticActionOut = function() { return _easeQuadraticActionOut; }; var _easeQuadraticActionInOut = { easing: function(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() { return _easeQuadraticActionInOut; } }; cc.easeQuadraticActionInOut = function() { return _easeQuadraticActionInOut; }; var _easeQuarticActionIn = { easing: function(time) { return time * time * time * time; }, reverse: function() { return _easeQuarticActionIn; } }; cc.easeQuarticActionIn = function() { return _easeQuarticActionIn; }; var _easeQuarticActionOut = { easing: function(time) { time -= 1; return -(time * time * time * time - 1); }, reverse: function() { return _easeQuarticActionOut; } }; cc.easeQuarticActionOut = function() { return _easeQuarticActionOut; }; var _easeQuarticActionInOut = { easing: function(time) { time *= 2; if (time < 1) return .5 * time * time * time * time; time -= 2; return -.5 * (time * time * time * time - 2); }, reverse: function() { return _easeQuarticActionInOut; } }; cc.easeQuarticActionInOut = function() { return _easeQuarticActionInOut; }; var _easeQuinticActionIn = { easing: function(time) { return time * time * time * time * time; }, reverse: function() { return _easeQuinticActionIn; } }; cc.easeQuinticActionIn = function() { return _easeQuinticActionIn; }; var _easeQuinticActionOut = { easing: function(time) { time -= 1; return time * time * time * time * time + 1; }, reverse: function() { return _easeQuinticActionOut; } }; cc.easeQuinticActionOut = function() { return _easeQuinticActionOut; }; var _easeQuinticActionInOut = { easing: function(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() { return _easeQuinticActionInOut; } }; cc.easeQuinticActionInOut = function() { return _easeQuinticActionInOut; }; var _easeCircleActionIn = { easing: function(time) { return -1 * (Math.sqrt(1 - time * time) - 1); }, reverse: function() { return _easeCircleActionIn; } }; cc.easeCircleActionIn = function() { return _easeCircleActionIn; }; var _easeCircleActionOut = { easing: function(time) { time -= 1; return Math.sqrt(1 - time * time); }, reverse: function() { return _easeCircleActionOut; } }; cc.easeCircleActionOut = function() { return _easeCircleActionOut; }; var _easeCircleActionInOut = { easing: function(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() { return _easeCircleActionInOut; } }; cc.easeCircleActionInOut = function() { return _easeCircleActionInOut; }; var _easeCubicActionIn = { easing: function(time) { return time * time * time; }, reverse: function() { return _easeCubicActionIn; } }; cc.easeCubicActionIn = function() { return _easeCubicActionIn; }; var _easeCubicActionOut = { easing: function(time) { time -= 1; return time * time * time + 1; }, reverse: function() { return _easeCubicActionOut; } }; cc.easeCubicActionOut = function() { return _easeCubicActionOut; }; var _easeCubicActionInOut = { easing: function(time) { time *= 2; if (time < 1) return .5 * time * time * time; time -= 2; return .5 * (time * time * time + 2); }, reverse: function() { return _easeCubicActionInOut; } }; cc.easeCubicActionInOut = function() { return _easeCubicActionInOut; }; }), {} ], 5: [ (function(require, module, exports) { cc.ActionInstant = cc.Class({ name: "cc.ActionInstant", extends: cc.FiniteTimeAction, isDone: function() { return true; }, step: function(dt) { this.update(1); }, update: function(dt) {}, reverse: function() { return this.clone(); }, clone: function() { return new cc.ActionInstant(); } }); cc.Show = cc.Class({ name: "cc.Show", extends: cc.ActionInstant, update: function(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() { return new cc.Hide(); }, clone: function() { return new cc.Show(); } }); cc.show = function() { return new cc.Show(); }; cc.Hide = cc.Class({ name: "cc.Hide", extends: cc.ActionInstant, update: function(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() { return new cc.Show(); }, clone: function() { return new cc.Hide(); } }); cc.hide = function() { return new cc.Hide(); }; cc.ToggleVisibility = cc.Class({ name: "cc.ToggleVisibility", extends: cc.ActionInstant, update: function(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() { return new cc.ToggleVisibility(); }, clone: function() { return new cc.ToggleVisibility(); } }); cc.toggleVisibility = function() { return new cc.ToggleVisibility(); }; cc.RemoveSelf = cc.Class({ name: "cc.RemoveSelf", extends: cc.ActionInstant, ctor: function(isNeedCleanUp) { this._isNeedCleanUp = true; void 0 !== isNeedCleanUp && this.init(isNeedCleanUp); }, update: function(dt) { this.target.removeFromParent(this._isNeedCleanUp); }, init: function(isNeedCleanUp) { this._isNeedCleanUp = isNeedCleanUp; return true; }, reverse: function() { return new cc.RemoveSelf(this._isNeedCleanUp); }, clone: function() { return new cc.RemoveSelf(this._isNeedCleanUp); } }); cc.removeSelf = function(isNeedCleanUp) { return new cc.RemoveSelf(isNeedCleanUp); }; cc.FlipX = cc.Class({ name: "cc.FlipX", extends: cc.ActionInstant, ctor: function(flip) { this._flippedX = false; void 0 !== flip && this.initWithFlipX(flip); }, initWithFlipX: function(flip) { this._flippedX = flip; return true; }, update: function(dt) { this.target.scaleX = Math.abs(this.target.scaleX) * (this._flippedX ? -1 : 1); }, reverse: function() { return new cc.FlipX(!this._flippedX); }, clone: function() { 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(flip) { this._flippedY = false; void 0 !== flip && this.initWithFlipY(flip); }, initWithFlipY: function(flip) { this._flippedY = flip; return true; }, update: function(dt) { this.target.scaleY = Math.abs(this.target.scaleY) * (this._flippedY ? -1 : 1); }, reverse: function() { return new cc.FlipY(!this._flippedY); }, clone: function() { 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(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(x, y) { this._x = x; this._y = y; return true; }, update: function(dt) { this.target.setPosition(this._x, this._y); }, clone: function() { 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(selector, selectorTarget, data) { this._selectorTarget = null; this._function = null; this._data = null; this.initWithFunction(selector, selectorTarget, data); }, initWithFunction: function(selector, selectorTarget, data) { selector && (this._function = selector); selectorTarget && (this._selectorTarget = selectorTarget); void 0 !== data && (this._data = data); return true; }, execute: function() { this._function && this._function.call(this._selectorTarget, this.target, this._data); }, update: function(dt) { this.execute(); }, getTargetCallback: function() { return this._selectorTarget; }, setTargetCallback: function(sel) { if (sel !== this._selectorTarget) { this._selectorTarget && (this._selectorTarget = null); this._selectorTarget = sel; } }, clone: function() { 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) { cc.ActionInterval = cc.Class({ name: "cc.ActionInterval", extends: cc.FiniteTimeAction, ctor: function(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() { return this._elapsed; }, initWithDuration: function(d) { this._duration = 0 === d ? cc.macro.FLT_EPSILON : d; this._elapsed = 0; this._firstTick = true; return true; }, isDone: function() { return this._elapsed >= this._duration; }, _cloneDecoration: function(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(action) { if (this._easeList) { action._easeList = []; for (var i = 0; i < this._easeList.length; i++) action._easeList.push(this._easeList[i].reverse()); } }, clone: function() { var action = new cc.ActionInterval(this._duration); this._cloneDecoration(action); return action; }, easing: function(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(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(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(target) { cc.Action.prototype.startWithTarget.call(this, target); this._elapsed = 0; this._firstTick = true; }, reverse: function() { cc.logID(1010); return null; }, setAmplitudeRate: function(amp) { cc.logID(1011); }, getAmplitudeRate: function() { cc.logID(1012); return 0; }, speed: function(speed) { if (speed <= 0) { cc.logID(1013); return this; } this._speedMethod = true; this._speed *= speed; return this; }, getSpeed: function() { return this._speed; }, setSpeed: function(speed) { this._speed = speed; return this; }, repeat: function(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() { 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(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(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() { var action = new cc.Sequence(); this._cloneDecoration(action); action.initWithTwoActions(this._actions[0].clone(), this._actions[1].clone()); return action; }, startWithTarget: function(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() { -1 !== this._last && this._actions[this._last].stop(); cc.Action.prototype.stop.call(this); }, update: function(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() { 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(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(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() { var action = new cc.Repeat(); this._cloneDecoration(action); action.initWithAction(this._innerAction.clone(), this._times); return action; }, startWithTarget: function(target) { this._total = 0; this._nextDt = this._innerAction._duration / this._duration; cc.ActionInterval.prototype.startWithTarget.call(this, target); this._innerAction.startWithTarget(target); }, stop: function() { this._innerAction.stop(); cc.Action.prototype.stop.call(this); }, update: function(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() { return this._total === this._times; }, reverse: function() { var action = new cc.Repeat(this._innerAction.reverse(), this._times); this._cloneDecoration(action); this._reverseEaseList(action); return action; }, setInnerAction: function(action) { this._innerAction !== action && (this._innerAction = action); }, getInnerAction: function() { return this._innerAction; } }); cc.repeat = function(action, times) { return new cc.Repeat(action, times); }; cc.RepeatForever = cc.Class({ name: "cc.RepeatForever", extends: cc.ActionInterval, ctor: function(action) { this._innerAction = null; action && this.initWithAction(action); }, initWithAction: function(action) { if (!action) { cc.errorID(1026); return false; } this._innerAction = action; return true; }, clone: function() { var action = new cc.RepeatForever(); this._cloneDecoration(action); action.initWithAction(this._innerAction.clone()); return action; }, startWithTarget: function(target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); this._innerAction.startWithTarget(target); }, step: function(dt) { var locInnerAction = this._innerAction; locInnerAction.step(dt); if (locInnerAction.isDone()) { locInnerAction.startWithTarget(this.target); locInnerAction.step(locInnerAction.getElapsed() - locInnerAction._duration); } }, isDone: function() { return false; }, reverse: function() { var action = new cc.RepeatForever(this._innerAction.reverse()); this._cloneDecoration(action); this._reverseEaseList(action); return action; }, setInnerAction: function(action) { this._innerAction !== action && (this._innerAction = action); }, getInnerAction: function() { return this._innerAction; } }); cc.repeatForever = function(action) { return new cc.RepeatForever(action); }; cc.Spawn = cc.Class({ name: "cc.Spawn", extends: cc.ActionInterval, ctor: function(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(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() { var action = new cc.Spawn(); this._cloneDecoration(action); action.initWithTwoActions(this._one.clone(), this._two.clone()); return action; }, startWithTarget: function(target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); this._one.startWithTarget(target); this._two.startWithTarget(target); }, stop: function() { this._one.stop(); this._two.stop(); cc.Action.prototype.stop.call(this); }, update: function(dt) { dt = this._computeEaseTime(dt); this._one && this._one.update(dt); this._two && this._two.update(dt); }, reverse: function() { 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, ctor: function(duration, deltaAngleX, deltaAngleY) { this._dstAngleX = 0; this._startAngleX = 0; this._diffAngleX = 0; this._dstAngleY = 0; this._startAngleY = 0; this._diffAngleY = 0; void 0 !== deltaAngleX && this.initWithDuration(duration, deltaAngleX, deltaAngleY); }, initWithDuration: function(duration, deltaAngleX, deltaAngleY) { if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) { this._dstAngleX = deltaAngleX || 0; this._dstAngleY = void 0 !== deltaAngleY ? deltaAngleY : this._dstAngleX; return true; } return false; }, clone: function() { var action = new cc.RotateTo(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._dstAngleX, this._dstAngleY); return action; }, startWithTarget: function(target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); var locStartAngleX = target.rotationX % 360; var locDiffAngleX = this._dstAngleX - locStartAngleX; locDiffAngleX > 180 && (locDiffAngleX -= 360); locDiffAngleX < -180 && (locDiffAngleX += 360); this._startAngleX = locStartAngleX; this._diffAngleX = locDiffAngleX; this._startAngleY = target.rotationY % 360; var locDiffAngleY = this._dstAngleY - this._startAngleY; locDiffAngleY > 180 && (locDiffAngleY -= 360); locDiffAngleY < -180 && (locDiffAngleY += 360); this._diffAngleY = locDiffAngleY; }, reverse: function() { cc.logID(1016); }, update: function(dt) { dt = this._computeEaseTime(dt); if (this.target) { this.target.rotationX = this._startAngleX + this._diffAngleX * dt; this.target.rotationY = this._startAngleY + this._diffAngleY * dt; } } }); cc.rotateTo = function(duration, deltaAngleX, deltaAngleY) { return new cc.RotateTo(duration, deltaAngleX, deltaAngleY); }; cc.RotateBy = cc.Class({ name: "cc.RotateBy", extends: cc.ActionInterval, ctor: function(duration, deltaAngleX, deltaAngleY) { this._angleX = 0; this._startAngleX = 0; this._angleY = 0; this._startAngleY = 0; void 0 !== deltaAngleX && this.initWithDuration(duration, deltaAngleX, deltaAngleY); }, initWithDuration: function(duration, deltaAngleX, deltaAngleY) { if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) { this._angleX = deltaAngleX || 0; this._angleY = void 0 !== deltaAngleY ? deltaAngleY : this._angleX; return true; } return false; }, clone: function() { var action = new cc.RotateBy(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._angleX, this._angleY); return action; }, startWithTarget: function(target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); this._startAngleX = target.rotationX; this._startAngleY = target.rotationY; }, update: function(dt) { dt = this._computeEaseTime(dt); if (this.target) { this.target.rotationX = this._startAngleX + this._angleX * dt; this.target.rotationY = this._startAngleY + this._angleY * dt; } }, reverse: function() { var action = new cc.RotateBy(this._duration, -this._angleX, -this._angleY); this._cloneDecoration(action); this._reverseEaseList(action); return action; } }); cc.rotateBy = function(duration, deltaAngleX, deltaAngleY) { return new cc.RotateBy(duration, deltaAngleX, deltaAngleY); }; cc.MoveBy = cc.Class({ name: "cc.MoveBy", extends: cc.ActionInterval, ctor: function(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(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() { var action = new cc.MoveBy(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._positionDelta); return action; }, startWithTarget: function(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(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() { 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(duration, position, y) { this._endPosition = cc.v2(0, 0); void 0 !== position && this.initWithDuration(duration, position, y); }, initWithDuration: function(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() { var action = new cc.MoveTo(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._endPosition); return action; }, startWithTarget: function(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(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(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() { var action = new cc.SkewTo(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._endSkewX, this._endSkewY); return action; }, startWithTarget: function(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(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(t, sx, sy) { void 0 !== sy && this.initWithDuration(t, sx, sy); }, initWithDuration: function(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() { var action = new cc.SkewBy(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._skewX, this._skewY); return action; }, startWithTarget: function(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() { 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(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(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() { var action = new cc.JumpBy(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._delta, this._height, this._jumps); return action; }, startWithTarget: function(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(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() { 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(duration, position, y, height, jumps) { this._endPosition = cc.v2(0, 0); void 0 !== height && this.initWithDuration(duration, position, y, height, jumps); }, initWithDuration: function(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(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() { 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(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(t, c) { if (cc.ActionInterval.prototype.initWithDuration.call(this, t)) { this._config = c; return true; } return false; }, clone: function() { 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(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(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() { 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(t, c) { this._toConfig = []; c && this.initWithDuration(t, c); }, initWithDuration: function(t, c) { if (cc.ActionInterval.prototype.initWithDuration.call(this, t)) { this._toConfig = c; return true; } return false; }, clone: function() { var action = new cc.BezierTo(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._toConfig); return action; }, startWithTarget: function(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(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(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() { var action = new cc.ScaleTo(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._endScaleX, this._endScaleY); return action; }, startWithTarget: function(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(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(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() { var action = new cc.ScaleBy(this._duration, 1 / this._endScaleX, 1 / this._endScaleY); this._cloneDecoration(action); this._reverseEaseList(action); return action; }, clone: function() { 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(duration, blinks) { this._times = 0; this._originalState = false; void 0 !== blinks && this.initWithDuration(duration, blinks); }, initWithDuration: function(duration, blinks) { if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) { this._times = blinks; return true; } return false; }, clone: function() { var action = new cc.Blink(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._times); return action; }, update: function(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(target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); this._originalState = target.opacity; }, stop: function() { this.target.opacity = this._originalState; cc.ActionInterval.prototype.stop.call(this); }, reverse: function() { 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(duration, opacity) { this._toOpacity = 0; this._fromOpacity = 0; void 0 !== opacity && cc.FadeTo.prototype.initWithDuration.call(this, duration, opacity); }, initWithDuration: function(duration, opacity) { if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) { this._toOpacity = opacity; return true; } return false; }, clone: function() { var action = new cc.FadeTo(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._toOpacity); return action; }, update: function(time) { time = this._computeEaseTime(time); var fromOpacity = void 0 !== this._fromOpacity ? this._fromOpacity : 255; this.target.opacity = fromOpacity + (this._toOpacity - fromOpacity) * time; }, startWithTarget: function(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(duration) { null == duration && (duration = 0); this._reverseAction = null; this.initWithDuration(duration, 255); }, reverse: function() { var action = new cc.FadeOut(); action.initWithDuration(this._duration, 0); this._cloneDecoration(action); this._reverseEaseList(action); return action; }, clone: function() { var action = new cc.FadeIn(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._toOpacity); return action; }, startWithTarget: function(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(duration) { null == duration && (duration = 0); this._reverseAction = null; this.initWithDuration(duration, 0); }, reverse: function() { var action = new cc.FadeIn(); action._reverseAction = this; action.initWithDuration(this._duration, 255); this._cloneDecoration(action); this._reverseEaseList(action); return action; }, clone: function() { 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(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(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() { 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(target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); this._from = this.target.color; }, update: function(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(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(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() { var action = new cc.TintBy(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._deltaR, this._deltaG, this._deltaB); return action; }, startWithTarget: function(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(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() { 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(dt) {}, reverse: function() { var action = new cc.DelayTime(this._duration); this._cloneDecoration(action); this._reverseEaseList(action); return action; }, clone: function() { 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(action) { this._other = null; action && this.initWithAction(action); }, initWithAction: function(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() { var action = new cc.ReverseTime(); this._cloneDecoration(action); action.initWithAction(this._other.clone()); return action; }, startWithTarget: function(target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); this._other.startWithTarget(target); }, update: function(dt) { dt = this._computeEaseTime(dt); this._other && this._other.update(1 - dt); }, reverse: function() { return this._other.clone(); }, stop: function() { 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(target, action) { this._action = null; this._forcedTarget = null; action && this.initWithTarget(target, action); }, initWithTarget: function(target, action) { if (this.initWithDuration(action._duration)) { this._forcedTarget = target; this._action = action; return true; } return false; }, clone: function() { var action = new cc.TargetedAction(); this._cloneDecoration(action); action.initWithTarget(this._forcedTarget, this._action.clone()); return action; }, startWithTarget: function(target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); this._action.startWithTarget(this._forcedTarget); }, stop: function() { this._action.stop(); }, update: function(dt) { dt = this._computeEaseTime(dt); this._action.update(dt); }, getForcedTarget: function() { return this._forcedTarget; }, setForcedTarget: function(forcedTarget) { this._forcedTarget !== forcedTarget && (this._forcedTarget = forcedTarget); } }); cc.targetedAction = function(target, action) { return new cc.TargetedAction(target, action); }; }), {} ], 7: [ (function(require, module, exports) { require("../core/platform/CCClass"); var js = require("../core/platform/js"); var HashElement = function() { 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(arr, target) { for (var k = 0; k < arr.length; k++) if (target === arr[k].target) return arr[k]; return null; }, _getElement: function(target, paused) { var element = this._elementPool.pop(); element || (element = new HashElement()); element.target = target; element.paused = !!paused; return element; }, _putElement: function(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(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() { 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(target, forceDelete) { if (null == target) return; var element = this._hashTargets[target._id]; if (element) { element.actions.length = 0; this._deleteHashElement(element); } }, removeAction: function(action) { if (null == action) return; var target = action.getOriginalTarget(); var element = this._hashTargets[target._id]; if (element) { 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; } } else cc.logID(1001); }, removeActionByTag: function(tag, target) { tag === cc.Action.TAG_INVALID && cc.logID(1002); cc.assertID(target, 1003); var element = this._hashTargets[target._id]; if (element) { var limit = element.actions.length; for (var i = 0; i < limit; ++i) { var action = element.actions[i]; if (action && action.getTag() === tag && action.getOriginalTarget() === target) { this._removeActionAtIndex(i, element); break; } } } }, getActionByTag: function(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(target) { var element = this._hashTargets[target._id]; if (element) return element.actions ? element.actions.length : 0; return 0; }, pauseTarget: function(target) { var element = this._hashTargets[target._id]; element && (element.paused = true); }, resumeTarget: function(target) { var element = this._hashTargets[target._id]; element && (element.paused = false); }, pauseAllRunningActions: function() { 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(targetsToResume) { if (!targetsToResume) return; for (var i = 0; i < targetsToResume.length; i++) targetsToResume[i] && this.resumeTarget(targetsToResume[i]); }, pauseTargets: function(targetsToPause) { if (!targetsToPause) return; for (var i = 0; i < targetsToPause.length; i++) targetsToPause[i] && this.pauseTarget(targetsToPause[i]); }, purgeSharedManager: function() { cc.director.getScheduler().unscheduleUpdate(this); }, _removeActionAtIndex: function(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(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(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": 161, "../core/platform/js": 181 } ], 8: [ (function(require, module, exports) { 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) { var TweenAction = cc.Class({ name: "cc.TweenAction", extends: cc.ActionInterval, ctor: function(duration, props, opts) { this._opts = opts = opts || Object.create(null); this._props = Object.create(null); opts.progress = opts.progress || this.progress; opts.easing && "string" === (__typeofVal = typeof opts.easing, "object" === __typeofVal ? __realTypeOfObj(opts.easing) : __typeofVal) && (opts.easing = cc.easing[opts.easing]); for (var name in props) { var value = props[name]; var easing = void 0, progress = void 0; if (value.value && (value.easing || value.progress)) { easing = "string" === (__typeofVal = typeof value.easing, "object" === __typeofVal ? __realTypeOfObj(value.easing) : __typeofVal) ? cc.easing[value.easing] : value.easing; progress = value.progress; value = value.value; } var isNumber = "number" === (__typeofVal = typeof value, "object" === __typeofVal ? __realTypeOfObj(value) : __typeofVal); if (!isNumber && (!value.lerp || !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() { var action = new TweenAction(this._duration, this._originProps, this._opts); this._cloneDecoration(action); return action; }, startWithTarget: function(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" === (__typeofVal = typeof value, "object" === __typeofVal ? __realTypeOfObj(value) : __typeofVal)) { 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(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 = this._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; } }, progress: function(start, end, current, t) { "number" === (__typeofVal = typeof start, "object" === __typeofVal ? __realTypeOfObj(start) : __typeofVal) ? current = start + (end - start) * t : start.lerp(end, t, current); return current; } }); function Tween(target) { this._actions = []; this._finalAction = null; this._target = target; } Tween.prototype.then = function(other) { if (other instanceof cc.Action) this._actions.push(other.clone()); else { var _actions = other._actions; for (var i = 0; i < _actions.length; i++) this._actions.push(_actions[i].clone()); } return this; }; Tween.prototype.target = function(target) { this._target = target; return this; }; Tween.prototype.start = function() { if (!this._target) { cc.warn("Please set target to tween first"); return this; } this._finalAction || (this._finalAction = this._get()); cc.director.getActionManager().addAction(this._finalAction, this._target, false); return this; }; Tween.prototype.stop = function() { this._finalAction && cc.director.getActionManager().removeAction(this._finalAction); return this; }; Tween.prototype.clone = function(target) { var action = this._get(); return cc.tween(target).then(action.clone()); }; Tween.prototype._get = function() { var actions = this._actions; actions = 1 === actions.length ? actions[0] : cc.sequence(actions); return actions; }; var actions = { to: function(duration, props, opts) { opts = opts || Object.create(null); opts.relative = false; return new TweenAction(duration, props, opts); }, by: function(duration, props, opts) { opts = opts || Object.create(null); opts.relative = true; return new TweenAction(duration, props, opts); }, delay: cc.delayTime, call: cc.callFunc, hide: cc.hide, show: cc.show, removeSelf: cc.removeSelf, sequence: cc.sequence }; var otherActions = { repeat: cc.repeat, repeatForever: cc.repeatForever, reverseTime: cc.reverseTime }; var keys = Object.keys(actions); var _loop = function(i) { var key = keys[i]; Tween.prototype[key] = function() { var action = actions[key].apply(actions, arguments); this._actions.push(action); this._finalAction = null; return this; }; }; for (var i = 0; i < keys.length; i++) _loop(i); keys = Object.keys(otherActions); var _loop2 = function(i) { var key = keys[i]; Tween.prototype[key] = function() { var args = []; for (var l = arguments.length, _i = 0; _i < l; _i++) args[_i] = arguments[_i]; var action = arguments[0]; action instanceof cc.Action || (action = this._get()); action = otherActions[key].apply(otherActions, [ action ].concat(args)); this._actions.length = 0; this._actions.push(action); this._finalAction = null; return this; }; }; for (var i = 0; i < keys.length; i++) _loop2(i); cc.tween = function(target) { return new Tween(target); }; cc.Tween = Tween; }), {} ], 10: [ (function(require, module, exports) { var js = cc.js; var Playable = require("./playable"); var DynamicAnimCurve = require("./animation-curves").DynamicAnimCurve; var quickFindIndex = require("./animation-curves").quickFindIndex; var sampleMotionPaths = require("./motion-path-helper").sampleMotionPaths; var EventAnimCurve = require("./animation-curves").EventAnimCurve; var EventInfo = require("./animation-curves").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" === (__typeofVal = typeof startTime, "object" === __typeofVal ? __realTypeOfObj(startTime) : __typeofVal) && 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(3908); 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 splitPropPath(propPath) { var array = propPath.split("."); array.shift(); return array.length > 0 ? array : null; } function initClipData(root, state) { var clip = state.clip; var curves = state.curves; curves.length = 0; 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; 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 createPropCurve(target, propPath, keyframes) { var isMotionPathProp = target instanceof cc.Node && "position" === propPath && keyframes[0] && Array.isArray(keyframes[0].value); var motionPaths = []; var curve = new DynamicAnimCurve(); curve.target = target; var propName, propValue; var dotIndex = propPath.indexOf("."); var hasSubProp = -1 !== dotIndex; if (hasSubProp) { propName = propPath.slice(0, dotIndex); propValue = target[propName]; } else propName = propPath; curve.prop = propName; curve.subProps = splitPropPath(propPath); for (var i = 0, l = keyframes.length; i < l; i++) { var keyframe = keyframes[i]; var ratio = keyframe.frame / state.duration; curve.ratios.push(ratio); if (isMotionPathProp) { var motionPath = keyframe.motionPath; if (motionPath && !checkMotionPath(motionPath)) { cc.errorID(3904, target.name, propPath, i); motionPath = null; } motionPaths.push(motionPath); } var curveValue = keyframe.value; curve.values.push(curveValue); var curveTypes = keyframe.curve; if (curveTypes) { if ("string" === (__typeofVal = typeof curveTypes, "object" === __typeofVal ? __realTypeOfObj(curveTypes) : __typeofVal)) { 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, clip.duration, clip.sample); 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; return curve; } function createTargetCurves(target, curveData) { var propsData = curveData.props; var compsData = curveData.comps; if (propsData) for (var propPath in propsData) { var data = propsData[propPath]; var curve = 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 = createPropCurve(comp, propPath, data); curves.push(curve); } } } var curveData = clip.curveData; var childrenCurveDatas = curveData.paths; createTargetCurves(root, curveData); for (var namePath in childrenCurveDatas) { var target = cc.find(namePath, root); if (!target) continue; var childCurveDatas = childrenCurveDatas[namePath]; createTargetCurves(target, childCurveDatas); } 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; 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": 237, "./animation-curves": 12, "./motion-path-helper": 18, "./playable": 19, "./types": 20 } ], 11: [ (function(require, module, exports) { var AnimationClip = cc.Class({ name: "cc.AnimationClip", extends: cc.Asset, properties: { _duration: { default: 0, type: "Float" }, duration: { get: function() { return this._duration; } }, sample: { default: 60 }, speed: { default: 1 }, wrapMode: { default: cc.WrapMode.Normal }, curveData: { default: {}, visible: false }, events: { default: [], visible: false } }, statics: { createWithSpriteFrames: function(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; } } }); cc.AnimationClip = module.exports = AnimationClip; }), {} ], 12: [ (function(require, module, exports) { 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" === (__typeofVal = typeof type, "object" === __typeofVal ? __realTypeOfObj(type) : __typeofVal)) { 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(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 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, properties: { target: null, prop: "", values: [], ratios: [], types: [], subProps: null }, _findFrameIndex: binarySearch, sample: function(time, ratio, state) { var values = this.values; var ratios = this.ratios; var frameCount = ratios.length; if (0 === frameCount) return; var value; var index = this._findFrameIndex(ratios, ratio); 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]; var isNumber = "number" === (__typeofVal = typeof fromVal, "object" === __typeofVal ? __realTypeOfObj(fromVal) : __typeofVal); var canLerp = fromVal && fromVal.lerp; if (isNumber || canLerp) { 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]; isNumber ? value = fromVal + (toVal - fromVal) * ratioBetweenFrames : canLerp && (value = fromVal.lerp(toVal, ratioBetweenFrames)); } else value = fromVal; } } else value = values[index]; var subProps = this.subProps; if (subProps) { var mainProp = this.target[this.prop]; var subProp = mainProp; for (var i = 0; i < subProps.length - 1; i++) { var subPropName = subProps[i]; if (!subProp) return; subProp = subProp[subPropName]; } var propName = subProps[subProps.length - 1]; if (!subProp) return; subProp[propName] = value; value = mainProp; } this.target[this.prop] = value; } }); DynamicAnimCurve.Linear = null; DynamicAnimCurve.Bezier = function(controlPoints) { return controlPoints; }; var EventInfo = function() { 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() { return new WrappedInfo(); } }, _lastWrappedInfo: null, _ignoreIndex: NaN }, _wrapIterations: function(iterations) { iterations - (0 | iterations) === 0 && (iterations -= 1); return 0 | iterations; }, sample: function(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(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(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": 237, "./bezier": 15, "./types": 20 } ], 13: [ (function(require, module, exports) { var js = cc.js; var AnimationManager = cc.Class({ ctor: function() { this._anims = new js.array.MutableForwardIterator([]); this._delayEvents = []; cc.director._scheduler && cc.director._scheduler.enableForTarget(this); }, update: function(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, l = events.length; i < l; i++) { var event = events[i]; event.target[event.func].apply(event.target, event.args); } events.length = 0; }, destruct: function() {}, addAnimation: function(anim) { var index = this._anims.array.indexOf(anim); -1 === index && this._anims.push(anim); }, removeAnimation: function(anim) { var index = this._anims.array.indexOf(anim); index >= 0 ? this._anims.fastRemoveAt(index) : cc.errorID(3907); }, pushDelayEvent: function(target, func, args) { this._delayEvents.push({ target: target, func: func, args: args }); } }); cc.AnimationManager = module.exports = AnimationManager; }), {} ], 14: [ (function(require, module, exports) { 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) { var _this = this; if (!this._target || !this._target.isValid) return null; var _ret = (function() { "lastframe" === type && (_this._lastframeEventOn = true); var self = _this; return { v: _this._target.once(type, (function(event) { callback.call(target, event); self._lastframeEventOn = false; })) }; })(); if ("object" === (__typeofVal = typeof _ret, "object" === __typeofVal ? __realTypeOfObj(_ret) : __typeofVal)) return _ret.v; }; 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) { function bezier(C1, C2, C3, C4, t) { var t1 = 1 - t; return C1 * t1 * t1 * t1 + 3 * C2 * t1 * t1 * t + 3 * C3 * t1 * 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 p0y = 0; var p1y = controlPoints[1]; var p2y = controlPoints[3]; var p3y = 1; var t1 = 1 - percent; return p0y * t1 * t1 * t1 + 3 * p1y * percent * t1 * t1 + 3 * p2y * percent * percent * t1 + p3y * percent * percent * percent; } false; module.exports = { bezier: bezier, bezierByTime: bezierByTime }; }), {} ], 16: [ (function(require, module, exports) { var easing = { constant: function() { return 0; }, linear: function(k) { return k; }, quadIn: function(k) { return k * k; }, quadOut: function(k) { return k * (2 - k); }, quadInOut: function(k) { if ((k *= 2) < 1) return .5 * k * k; return -.5 * (--k * (k - 2) - 1); }, cubicIn: function(k) { return k * k * k; }, cubicOut: function(k) { return --k * k * k + 1; }, cubicInOut: function(k) { if ((k *= 2) < 1) return .5 * k * k * k; return .5 * ((k -= 2) * k * k + 2); }, quartIn: function(k) { return k * k * k * k; }, quartOut: function(k) { return 1 - --k * k * k * k; }, quartInOut: function(k) { if ((k *= 2) < 1) return .5 * k * k * k * k; return -.5 * ((k -= 2) * k * k * k - 2); }, quintIn: function(k) { return k * k * k * k * k; }, quintOut: function(k) { return --k * k * k * k * k + 1; }, quintInOut: function(k) { if ((k *= 2) < 1) return .5 * k * k * k * k * k; return .5 * ((k -= 2) * k * k * k * k + 2); }, sineIn: function(k) { return 1 - Math.cos(k * Math.PI / 2); }, sineOut: function(k) { return Math.sin(k * Math.PI / 2); }, sineInOut: function(k) { return .5 * (1 - Math.cos(Math.PI * k)); }, expoIn: function(k) { return 0 === k ? 0 : Math.pow(1024, k - 1); }, expoOut: function(k) { return 1 === k ? 1 : 1 - Math.pow(2, -10 * k); }, expoInOut: function(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(k) { return 1 - Math.sqrt(1 - k * k); }, circOut: function(k) { return Math.sqrt(1 - --k * k); }, circInOut: function(k) { if ((k *= 2) < 1) return -.5 * (Math.sqrt(1 - k * k) - 1); return .5 * (Math.sqrt(1 - (k -= 2) * k) + 1); }, elasticIn: function(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(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(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(k) { var s = 1.70158; return k * k * ((s + 1) * k - s); }, backOut: function(k) { var s = 1.70158; return --k * k * ((s + 1) * k + s) + 1; }, backInOut: function(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); }, bounceOut: function(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; }, smooth: function(t) { if (t <= 0) return 0; if (t >= 1) return 1; return t * t * (3 - 2 * t); }, fade: function(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.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) { 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) { 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 sampleMotionPaths(motionPaths, data, duration, fps) { 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; if (0 === motionPaths.length || 0 === values.length) return; values = values.map((function(value) { return v2(value[0], value[1]); })); if (1 === values.length) { data.values = values; 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": 237, "./animation-curves": 12, "./bezier": 15 } ], 19: [ (function(require, module, exports) { 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() {}; 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": 27 } ], 20: [ (function(require, module, exports) { 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) { var EventTarget = require("../core/event/event-target"); var sys = require("../core/platform/CCSys"); var LoadMode = require("../core/assets/CCAudioClip").LoadMode; var touchBinded = false; var touchPlayList = []; var Audio = function(src) { EventTarget.call(this); this._src = src; this._element = null; this.id = 0; this._volume = 1; this._loop = false; this._nextTime = 0; this._state = Audio.State.INITIALZING; this._onended = function() { this._state = Audio.State.STOPPED; this.emit("ended"); }.bind(this); }; cc.js.extend(Audio, EventTarget); Audio.State = { ERROR: -1, INITIALZING: 0, PLAYING: 1, PAUSED: 2, STOPPED: 3 }; (function(proto) { proto._bindEnded = function(callback) { callback = callback || this._onended; var elem = this._element; this._src && elem instanceof HTMLAudioElement ? elem.addEventListener("ended", callback) : elem.onended = callback; }; proto._unbindEnded = function() { var elem = this._element; elem instanceof HTMLAudioElement ? elem.removeEventListener("ended", this._onended) : elem && (elem.onended = null); }; proto._onLoaded = function() { var elem = this._src._nativeAsset; if (elem instanceof HTMLAudioElement) { this._element || (this._element = document.createElement("audio")); this._element.src = elem.src; } else this._element = new WebAudioElement(elem, this); this.setVolume(this._volume); this.setLoop(this._loop); 0 !== this._nextTime && this.setCurrentTime(this._nextTime); this._state === Audio.State.PLAYING ? this.play() : this._state = Audio.State.INITIALZING; }; proto.play = function() { this._state = Audio.State.PLAYING; if (!this._element) return; this._bindEnded(); this._element.play(); true, true; this._src && this._src.loadMode === LoadMode.DOM_AUDIO && this._element.paused && touchPlayList.push({ instance: this, offset: 0, audio: this._element }); if (touchBinded) return; touchBinded = true; cc.game.canvas.addEventListener("touchstart", (function() { var item = void 0; while (item = touchPlayList.pop()) item.audio.play(item.offset); })); }; proto.destroy = function() { false, false; this._element = null; }; proto.pause = function() { if (!this._element || this._state !== Audio.State.PLAYING) return; this._unbindEnded(); this._element.pause(); this._state = Audio.State.PAUSED; }; proto.resume = function() { if (!this._element || this._state !== Audio.State.PAUSED) return; this._bindEnded(); this._element.play(); this._state = Audio.State.PLAYING; }; proto.stop = function() { if (!this._element) return; this._element.pause(); try { this._element.currentTime = 0; } catch (error) {} for (var i = 0; i < touchPlayList.length; i++) if (touchPlayList[i].instance === this) { touchPlayList.splice(i, 1); break; } this._unbindEnded(); this.emit("stop"); this._state = Audio.State.STOPPED; }; proto.setLoop = function(loop) { this._loop = loop; this._element && (this._element.loop = loop); }; proto.getLoop = function() { return this._loop; }; proto.setVolume = function(num) { this._volume = num; this._element && (this._element.volume = num); }; proto.getVolume = function() { return this._volume; }; proto.setCurrentTime = function(num) { var _this = this; if (!this._element) { this._nextTime = num; return; } this._nextTime = 0; if (!(false, false)) { this._unbindEnded(); this._bindEnded(function() { this._bindEnded(); }.bind(this)); } try { this._element.currentTime = num; } catch (err) { (function() { var _element = _this._element; _element.addEventListener && (function() { var func = function() { _element.removeEventListener("loadedmetadata", func); _element.currentTime = num; }; _element.addEventListener("loadedmetadata", func); })(); })(); } }; proto.getCurrentTime = function() { return this._element ? this._element.currentTime : 0; }; proto.getDuration = function() { return this._element ? this._element.duration : 0; }; proto.getState = function() { true, true; var elem = this._element; elem && Audio.State.PLAYING === this._state && elem.paused && (this._state = Audio.State.STOPPED); return this._state; }; proto.__defineGetter__("src", (function() { return this._src; })); proto.__defineSetter__("src", (function(clip) { var _this2 = this; this._unbindEnded(); if (clip) { this._src = clip; clip.loaded ? this._onLoaded() : (function() { var self = _this2; clip.once("load", (function() { clip === self._src && self._onLoaded(); })); cc.loader.load({ url: clip.nativeUrl, skips: [ "Loader" ] }, (function(err, audioNativeAsset) { if (err) { cc.error(err); return; } clip.loaded || (clip._nativeAsset = audioNativeAsset); })); })(); } else { this._src = null; this._element instanceof HTMLAudioElement ? this._element.src = "" : this._element = null; this._state = Audio.State.INITIALZING; } return clip; })); proto.__defineGetter__("paused", (function() { return !this._element || this._element.paused; })); })(Audio.prototype); var WebAudioElement = function(buffer, audio) { this._audio = audio; this._context = sys.__audioSupport.context; this._buffer = buffer; this._gainObj = this._context["createGain"](); this._volume = 1; this._gainObj["gain"].setTargetAtTime ? this._gainObj["gain"].setTargetAtTime(this._volume, this._context.currentTime, .01) : this._gainObj["gain"].value = 1; this._gainObj["connect"](this._context["destination"]); this._loop = false; this._startTime = -1; this._currentSource = null; this.playedLength = 0; this._currextTimer = null; this._endCallback = function() { this.onended && this.onended(this); }.bind(this); }; (function(proto) { proto.play = function(offset) { var _this3 = this; if (this._currentSource && !this.paused) { this._currentSource.onended = null; this._currentSource.stop(0); this.playedLength = 0; } var audio = this._context["createBufferSource"](); audio.buffer = this._buffer; audio["connect"](this._gainObj); audio.loop = this._loop; this._startTime = this._context.currentTime; offset = offset || this.playedLength; offset && (this._startTime -= offset); var duration = this._buffer.duration; var startTime = offset; var endTime = void 0; if (this._loop) audio.start ? audio.start(0, startTime) : audio["notoGrainOn"] ? audio["noteGrainOn"](0, startTime) : audio["noteOn"](0, startTime); else { endTime = duration - offset; audio.start ? audio.start(0, startTime, endTime) : audio["notoGrainOn"] ? audio["noteGrainOn"](0, startTime, endTime) : audio["noteOn"](0, startTime, endTime); } this._currentSource = audio; audio.onended = this._endCallback; audio.context.state && "suspended" !== audio.context.state || 0 !== this._context.currentTime || (function() { var self = _this3; clearTimeout(_this3._currextTimer); _this3._currextTimer = setTimeout((function() { (false, false) || 0 !== self._context.currentTime || touchPlayList.push({ instance: self._audio, offset: offset, audio: self }); }), 10); })(); }; proto.pause = function() { clearTimeout(this._currextTimer); if (this.paused) return; this.playedLength = this._context.currentTime - this._startTime; this.playedLength %= this._buffer.duration; var audio = this._currentSource; this._currentSource = null; this._startTime = -1; audio && audio.stop(0); }; proto.__defineGetter__("paused", (function() { if (this._currentSource && this._currentSource.loop) return false; if (-1 === this._startTime) return true; return this._context.currentTime - this._startTime > this._buffer.duration; })); proto.__defineGetter__("loop", (function() { return this._loop; })); proto.__defineSetter__("loop", (function(bool) { this._currentSource && (this._currentSource.loop = bool); return this._loop = bool; })); proto.__defineGetter__("volume", (function() { return this._volume; })); proto.__defineSetter__("volume", (function(num) { this._volume = num; this._gainObj["gain"].setTargetAtTime ? this._gainObj["gain"].setTargetAtTime(this._volume, this._context.currentTime, .01) : this._volume["gain"].value = num; if (sys.os === sys.OS_IOS && !this.paused && this._currentSource) { this._currentSource.onended = null; this.pause(); this.play(); } return num; })); proto.__defineGetter__("currentTime", (function() { if (this.paused) return this.playedLength; this.playedLength = this._context.currentTime - this._startTime; this.playedLength %= this._buffer.duration; return this.playedLength; })); proto.__defineSetter__("currentTime", (function(num) { if (this.paused) this.playedLength = num; else { this.pause(); this.playedLength = num; this.play(); } return num; })); proto.__defineGetter__("duration", (function() { return this._buffer.duration; })); })(WebAudioElement.prototype); module.exports = cc.Audio = Audio; }), { "../core/assets/CCAudioClip": 35, "../core/event/event-target": 103, "../core/platform/CCSys": 170 } ], 22: [ (function(require, module, exports) { var Audio = require("./CCAudio"); var AudioClip = require("../core/assets/CCAudioClip"); var js = cc.js; var _instanceId = 0; var _id2audio = js.createMap(true); var _url2id = {}; var _audioPool = []; var recycleAudio = function(audio) { audio._finishCallback = null; if (_audioPool.length < 32) { audio.off("ended"); audio.off("stop"); audio.src = null; _audioPool.push(audio); } else audio.destroy(); }; var getAudioFromPath = function(path) { var id = _instanceId++; var list = _url2id[path]; list || (list = _url2id[path] = []); if (audioEngine._maxAudioInstance <= list.length) { var oldId = list.shift(); var oldAudio = getAudioFromId(oldId); oldAudio && oldAudio.stop(); } var audio = _audioPool.pop() || new Audio(); var callback = function() { var audioInList = getAudioFromId(this.id); if (audioInList) { delete _id2audio[this.id]; var index = list.indexOf(this.id); cc.js.array.fastRemoveAt(list, index); } recycleAudio(this); }; audio.on("ended", (function() { this._finishCallback && this._finishCallback(); callback.call(this); }), audio); audio.on("stop", callback, audio); audio.id = id; _id2audio[id] = audio; list.push(id); return audio; }; var getAudioFromId = function(id) { return _id2audio[id]; }; var handleVolume = function(volume) { void 0 === volume ? volume = 1 : "string" === (__typeofVal = typeof volume, "object" === __typeofVal ? __realTypeOfObj(volume) : __typeofVal) && (volume = Number.parseFloat(volume)); return volume; }; var audioEngine = { AudioState: Audio.State, _maxWebAudioSize: 2097152, _maxAudioInstance: 24, _id2audio: _id2audio, play: function(clip, loop, volume) { var path = clip; var audio; if ("string" === (__typeofVal = typeof clip, "object" === __typeofVal ? __realTypeOfObj(clip) : __typeofVal)) { cc.warnID(8401, "cc.audioEngine", "cc.AudioClip", "AudioClip", "cc.AudioClip", "audio"); path = clip; audio = getAudioFromPath(path); AudioClip._loadByUrl(path, (function(err, clip) { clip && (audio.src = clip); })); } else { if (!clip) return; path = clip.nativeUrl; audio = getAudioFromPath(path); audio.src = clip; } audio.setLoop(loop || false); volume = handleVolume(volume); audio.setVolume(volume); audio.play(); return audio.id; }, setLoop: function(audioID, loop) { var audio = getAudioFromId(audioID); if (!audio || !audio.setLoop) return; audio.setLoop(loop); }, isLoop: function(audioID) { var audio = getAudioFromId(audioID); if (!audio || !audio.getLoop) return false; return audio.getLoop(); }, setVolume: function(audioID, volume) { var audio = getAudioFromId(audioID); audio && audio.setVolume(volume); }, getVolume: function(audioID) { var audio = getAudioFromId(audioID); return audio ? audio.getVolume() : 1; }, setCurrentTime: function(audioID, sec) { var audio = getAudioFromId(audioID); if (audio) { audio.setCurrentTime(sec); return true; } return false; }, getCurrentTime: function(audioID) { var audio = getAudioFromId(audioID); return audio ? audio.getCurrentTime() : 0; }, getDuration: function(audioID) { var audio = getAudioFromId(audioID); return audio ? audio.getDuration() : 0; }, getState: function(audioID) { var audio = getAudioFromId(audioID); return audio ? audio.getState() : this.AudioState.ERROR; }, setFinishCallback: function(audioID, callback) { var audio = getAudioFromId(audioID); if (!audio) return; audio._finishCallback = callback; }, pause: function(audioID) { var audio = getAudioFromId(audioID); if (audio) { audio.pause(); return true; } return false; }, _pauseIDCache: [], pauseAll: function() { for (var id in _id2audio) { var audio = _id2audio[id]; var state = audio.getState(); if (state === Audio.State.PLAYING) { this._pauseIDCache.push(id); audio.pause(); } } }, resume: function(audioID) { var audio = getAudioFromId(audioID); audio && audio.resume(); }, resumeAll: function() { for (var i = 0; i < this._pauseIDCache.length; ++i) { var id = this._pauseIDCache[i]; var audio = getAudioFromId(id); audio && audio.resume(); } this._pauseIDCache.length = 0; }, stop: function(audioID) { var audio = getAudioFromId(audioID); if (audio) { audio.stop(); return true; } return false; }, stopAll: function() { for (var id in _id2audio) { var audio = _id2audio[id]; audio && audio.stop(); } }, setMaxAudioInstance: function(num) { this._maxAudioInstance = num; }, getMaxAudioInstance: function() { return this._maxAudioInstance; }, uncache: function(clip) { var filePath = clip; if ("string" === (__typeofVal = typeof clip, "object" === __typeofVal ? __realTypeOfObj(clip) : __typeofVal)) { cc.warnID(8401, "cc.audioEngine", "cc.AudioClip", "AudioClip", "cc.AudioClip", "audio"); filePath = clip; } else { if (!clip) return; filePath = clip.nativeUrl; } var list = _url2id[filePath]; if (!list) return; while (list.length > 0) { var id = list.pop(); var audio = _id2audio[id]; if (audio) { audio.stop(); delete _id2audio[id]; } } }, uncacheAll: function() { this.stopAll(); var audio = void 0; for (var id in _id2audio) { audio = _id2audio[id]; audio && audio.destroy(); } while (audio = _audioPool.pop()) audio.destroy(); _id2audio = js.createMap(true); _url2id = {}; }, getProfile: function(profileName) {}, preload: function(filePath, callback) { true; cc.warn("`cc.audioEngine.preload` is deprecated, use `cc.loader.loadRes(url, cc.AudioClip)` instead please."); cc.loader.load(filePath, callback && function(error) { error || callback(); }); }, setMaxWebAudioSize: function(kb) { this._maxWebAudioSize = 1024 * kb; }, _breakCache: null, _break: function() { this._breakCache = []; for (var id in _id2audio) { var audio = _id2audio[id]; var state = audio.getState(); if (state === Audio.State.PLAYING) { this._breakCache.push(id); audio.pause(); } } }, _restore: function() { if (!this._breakCache) return; while (this._breakCache.length > 0) { var id = this._breakCache.pop(); var audio = getAudioFromId(id); audio && audio.resume && audio.resume(); } this._breakCache = null; }, _music: { id: -1, loop: false, volume: 1 }, _effect: { volume: 1, pauseCache: [] }, playMusic: function(clip, loop) { var music = this._music; this.stop(music.id); music.id = this.play(clip, loop, music.volume); music.loop = loop; return music.id; }, stopMusic: function() { this.stop(this._music.id); }, pauseMusic: function() { this.pause(this._music.id); return this._music.id; }, resumeMusic: function() { this.resume(this._music.id); return this._music.id; }, getMusicVolume: function() { return this._music.volume; }, setMusicVolume: function(volume) { volume = handleVolume(volume); var music = this._music; music.volume = volume; this.setVolume(music.id, music.volume); return music.volume; }, isMusicPlaying: function() { return this.getState(this._music.id) === this.AudioState.PLAYING; }, playEffect: function(clip, loop) { return this.play(clip, loop || false, this._effect.volume); }, setEffectsVolume: function(volume) { volume = handleVolume(volume); var musicId = this._music.id; this._effect.volume = volume; for (var id in _id2audio) { var audio = _id2audio[id]; if (!audio || audio.id === musicId) continue; audioEngine.setVolume(id, volume); } }, getEffectsVolume: function() { return this._effect.volume; }, pauseEffect: function(audioID) { return this.pause(audioID); }, pauseAllEffects: function() { var musicId = this._music.id; var effect = this._effect; effect.pauseCache.length = 0; for (var id in _id2audio) { var audio = _id2audio[id]; if (!audio || audio.id === musicId) continue; var state = audio.getState(); if (state === this.AudioState.PLAYING) { effect.pauseCache.push(id); audio.pause(); } } }, resumeEffect: function(id) { this.resume(id); }, resumeAllEffects: function() { var pauseIDCache = this._effect.pauseCache; for (var i = 0; i < pauseIDCache.length; ++i) { var id = pauseIDCache[i]; var audio = _id2audio[id]; audio && audio.resume(); } }, stopEffect: function(audioID) { return this.stop(audioID); }, stopAllEffects: function() { var musicId = this._music.id; for (var id in _id2audio) { var audio = _id2audio[id]; if (!audio || audio.id === musicId) continue; var state = audio.getState(); state === audioEngine.AudioState.PLAYING && audio.stop(); } } }; module.exports = cc.audioEngine = audioEngine; }), { "../core/assets/CCAudioClip": 35, "./CCAudio": 21 } ], 23: [ (function(require, module, exports) { var codec = { name: "Jacob__Codec" }; codec.Base64 = require("./base64"); codec.GZip = require("./gzip"); codec.unzip = function() { return codec.GZip.gunzip.apply(codec.GZip, arguments); }; codec.unzipBase64 = function() { var buffer = codec.Base64.decode.apply(codec.Base64, arguments); try { return codec.GZip.gunzip.call(codec.GZip, buffer); } catch (e) { return buffer.slice(7); } }; codec.unzipBase64AsArray = function(input, bytes) { bytes = bytes || 1; var dec = this.unzipBase64(input), ar = [], i, j, len; for (i = 0, len = dec.length / bytes; i < len; i++) { ar[i] = 0; for (j = bytes - 1; j >= 0; --j) ar[i] += dec.charCodeAt(i * bytes + j) << 8 * j; } return ar; }; codec.unzipAsArray = function(input, bytes) { bytes = bytes || 1; var dec = this.unzip(input), ar = [], i, j, len; for (i = 0, len = dec.length / bytes; i < len; i++) { ar[i] = 0; for (j = bytes - 1; j >= 0; --j) ar[i] += dec.charCodeAt(i * bytes + j) << 8 * j; } return ar; }; cc.codec = module.exports = codec; }), { "./base64": 24, "./gzip": 25 } ], 24: [ (function(require, module, exports) { var misc = require("../core/utils/misc"); var strValue = misc.BASE64_VALUES; var Base64 = { name: "Jacob__Codec__Base64" }; Base64.decode = function Jacob__Codec__Base64__decode(input) { var output = [], chr1, chr2, chr3, enc1, enc2, enc3, enc4, i = 0; input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); while (i < input.length) { enc1 = strValue[input.charCodeAt(i++)]; enc2 = strValue[input.charCodeAt(i++)]; enc3 = strValue[input.charCodeAt(i++)]; enc4 = strValue[input.charCodeAt(i++)]; chr1 = enc1 << 2 | enc2 >> 4; chr2 = (15 & enc2) << 4 | enc3 >> 2; chr3 = (3 & enc3) << 6 | enc4; output.push(String.fromCharCode(chr1)); 64 !== enc3 && output.push(String.fromCharCode(chr2)); 64 !== enc4 && output.push(String.fromCharCode(chr3)); } output = output.join(""); return output; }; Base64.decodeAsArray = function Jacob__Codec__Base64___decodeAsArray(input, bytes) { var dec = this.decode(input), ar = [], i, j, len; for (i = 0, len = dec.length / bytes; i < len; i++) { ar[i] = 0; for (j = bytes - 1; j >= 0; --j) ar[i] += dec.charCodeAt(i * bytes + j) << 8 * j; } return ar; }; module.exports = Base64; }), { "../core/utils/misc": 243 } ], 25: [ (function(require, module, exports) { var GZip = function Jacob__GZip(data) { this.data = data; this.debug = false; this.gpflags = void 0; this.files = 0; this.unzipped = []; this.buf32k = new Array(32768); this.bIdx = 0; this.modeZIP = false; this.bytepos = 0; this.bb = 1; this.bits = 0; this.nameBuf = []; this.fileout = void 0; this.literalTree = new Array(GZip.LITERALS); this.distanceTree = new Array(32); this.treepos = 0; this.Places = null; this.len = 0; this.fpos = new Array(17); this.fpos[0] = 0; this.flens = void 0; this.fmax = void 0; }; GZip.gunzip = function(string) { string.constructor === Array || string.constructor === String; var gzip = new GZip(string); return gzip.gunzip()[0][0]; }; GZip.HufNode = function() { this.b0 = 0; this.b1 = 0; this.jump = null; this.jumppos = -1; }; GZip.LITERALS = 288; GZip.NAMEMAX = 256; GZip.bitReverse = [ 0, 128, 64, 192, 32, 160, 96, 224, 16, 144, 80, 208, 48, 176, 112, 240, 8, 136, 72, 200, 40, 168, 104, 232, 24, 152, 88, 216, 56, 184, 120, 248, 4, 132, 68, 196, 36, 164, 100, 228, 20, 148, 84, 212, 52, 180, 116, 244, 12, 140, 76, 204, 44, 172, 108, 236, 28, 156, 92, 220, 60, 188, 124, 252, 2, 130, 66, 194, 34, 162, 98, 226, 18, 146, 82, 210, 50, 178, 114, 242, 10, 138, 74, 202, 42, 170, 106, 234, 26, 154, 90, 218, 58, 186, 122, 250, 6, 134, 70, 198, 38, 166, 102, 230, 22, 150, 86, 214, 54, 182, 118, 246, 14, 142, 78, 206, 46, 174, 110, 238, 30, 158, 94, 222, 62, 190, 126, 254, 1, 129, 65, 193, 33, 161, 97, 225, 17, 145, 81, 209, 49, 177, 113, 241, 9, 137, 73, 201, 41, 169, 105, 233, 25, 153, 89, 217, 57, 185, 121, 249, 5, 133, 69, 197, 37, 165, 101, 229, 21, 149, 85, 213, 53, 181, 117, 245, 13, 141, 77, 205, 45, 173, 109, 237, 29, 157, 93, 221, 61, 189, 125, 253, 3, 131, 67, 195, 35, 163, 99, 227, 19, 147, 83, 211, 51, 179, 115, 243, 11, 139, 75, 203, 43, 171, 107, 235, 27, 155, 91, 219, 59, 187, 123, 251, 7, 135, 71, 199, 39, 167, 103, 231, 23, 151, 87, 215, 55, 183, 119, 247, 15, 143, 79, 207, 47, 175, 111, 239, 31, 159, 95, 223, 63, 191, 127, 255 ]; GZip.cplens = [ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 ]; GZip.cplext = [ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 99, 99 ]; GZip.cpdist = [ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577 ]; GZip.cpdext = [ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 ]; GZip.border = [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]; GZip.prototype.gunzip = function() { this.outputArr = []; this.nextFile(); return this.unzipped; }; GZip.prototype.readByte = function() { this.bits += 8; return this.bytepos < this.data.length ? this.data.charCodeAt(this.bytepos++) : -1; }; GZip.prototype.byteAlign = function() { this.bb = 1; }; GZip.prototype.readBit = function() { var carry; this.bits++; carry = 1 & this.bb; this.bb >>= 1; if (0 === this.bb) { this.bb = this.readByte(); carry = 1 & this.bb; this.bb = this.bb >> 1 | 128; } return carry; }; GZip.prototype.readBits = function(a) { var res = 0, i = a; while (i--) res = res << 1 | this.readBit(); a && (res = GZip.bitReverse[res] >> 8 - a); return res; }; GZip.prototype.flushBuffer = function() { this.bIdx = 0; }; GZip.prototype.addBuffer = function(a) { this.buf32k[this.bIdx++] = a; this.outputArr.push(String.fromCharCode(a)); 32768 === this.bIdx && (this.bIdx = 0); }; GZip.prototype.IsPat = function() { while (1) { if (this.fpos[this.len] >= this.fmax) return -1; if (this.flens[this.fpos[this.len]] === this.len) return this.fpos[this.len]++; this.fpos[this.len]++; } }; GZip.prototype.Rec = function() { var curplace = this.Places[this.treepos]; var tmp; if (17 === this.len) return -1; this.treepos++; this.len++; tmp = this.IsPat(); if (tmp >= 0) curplace.b0 = tmp; else { curplace.b0 = 32768; if (this.Rec()) return -1; } tmp = this.IsPat(); if (tmp >= 0) { curplace.b1 = tmp; curplace.jump = null; } else { curplace.b1 = 32768; curplace.jump = this.Places[this.treepos]; curplace.jumppos = this.treepos; if (this.Rec()) return -1; } this.len--; return 0; }; GZip.prototype.CreateTree = function(currentTree, numval, lengths, show) { var i; this.Places = currentTree; this.treepos = 0; this.flens = lengths; this.fmax = numval; for (i = 0; i < 17; i++) this.fpos[i] = 0; this.len = 0; if (this.Rec()) return -1; return 0; }; GZip.prototype.DecodeValue = function(currentTree) { var len, i, xtreepos = 0, X = currentTree[xtreepos], b; while (1) { b = this.readBit(); if (b) { if (!(32768 & X.b1)) return X.b1; X = X.jump; len = currentTree.length; for (i = 0; i < len; i++) if (currentTree[i] === X) { xtreepos = i; break; } } else { if (!(32768 & X.b0)) return X.b0; xtreepos++; X = currentTree[xtreepos]; } } return -1; }; GZip.prototype.DeflateLoop = function() { var last, c, type, i, len; do { last = this.readBit(); type = this.readBits(2); if (0 === type) { var blockLen, cSum; this.byteAlign(); blockLen = this.readByte(); blockLen |= this.readByte() << 8; cSum = this.readByte(); cSum |= this.readByte() << 8; 65535 & (blockLen ^ ~cSum) && document.write("BlockLen checksum mismatch\n"); while (blockLen--) { c = this.readByte(); this.addBuffer(c); } } else if (1 === type) { var j; while (1) { j = GZip.bitReverse[this.readBits(7)] >> 1; if (j > 23) { j = j << 1 | this.readBit(); if (j > 199) { j -= 128; j = j << 1 | this.readBit(); } else { j -= 48; j > 143 && (j += 136); } } else j += 256; if (j < 256) this.addBuffer(j); else { if (256 === j) break; var len, dist; j -= 257; len = this.readBits(GZip.cplext[j]) + GZip.cplens[j]; j = GZip.bitReverse[this.readBits(5)] >> 3; if (GZip.cpdext[j] > 8) { dist = this.readBits(8); dist |= this.readBits(GZip.cpdext[j] - 8) << 8; } else dist = this.readBits(GZip.cpdext[j]); dist += GZip.cpdist[j]; for (j = 0; j < len; j++) { var c = this.buf32k[this.bIdx - dist & 32767]; this.addBuffer(c); } } } } else if (2 === type) { var j, n, literalCodes, distCodes, lenCodes; var ll = new Array(320); literalCodes = 257 + this.readBits(5); distCodes = 1 + this.readBits(5); lenCodes = 4 + this.readBits(4); for (j = 0; j < 19; j++) ll[j] = 0; for (j = 0; j < lenCodes; j++) ll[GZip.border[j]] = this.readBits(3); len = this.distanceTree.length; for (i = 0; i < len; i++) this.distanceTree[i] = new GZip.HufNode(); if (this.CreateTree(this.distanceTree, 19, ll, 0)) { this.flushBuffer(); return 1; } n = literalCodes + distCodes; i = 0; var z = -1; while (i < n) { z++; j = this.DecodeValue(this.distanceTree); if (j < 16) ll[i++] = j; else if (16 === j) { var l; j = 3 + this.readBits(2); if (i + j > n) { this.flushBuffer(); return 1; } l = i ? ll[i - 1] : 0; while (j--) ll[i++] = l; } else { j = 17 === j ? 3 + this.readBits(3) : 11 + this.readBits(7); if (i + j > n) { this.flushBuffer(); return 1; } while (j--) ll[i++] = 0; } } len = this.literalTree.length; for (i = 0; i < len; i++) this.literalTree[i] = new GZip.HufNode(); if (this.CreateTree(this.literalTree, literalCodes, ll, 0)) { this.flushBuffer(); return 1; } len = this.literalTree.length; for (i = 0; i < len; i++) this.distanceTree[i] = new GZip.HufNode(); var ll2 = new Array(); for (i = literalCodes; i < ll.length; i++) ll2[i - literalCodes] = ll[i]; if (this.CreateTree(this.distanceTree, distCodes, ll2, 0)) { this.flushBuffer(); return 1; } while (1) { j = this.DecodeValue(this.literalTree); if (j >= 256) { var len, dist; j -= 256; if (0 === j) break; j--; len = this.readBits(GZip.cplext[j]) + GZip.cplens[j]; j = this.DecodeValue(this.distanceTree); if (GZip.cpdext[j] > 8) { dist = this.readBits(8); dist |= this.readBits(GZip.cpdext[j] - 8) << 8; } else dist = this.readBits(GZip.cpdext[j]); dist += GZip.cpdist[j]; while (len--) { var c = this.buf32k[this.bIdx - dist & 32767]; this.addBuffer(c); } } else this.addBuffer(j); } } } while (!last); this.flushBuffer(); this.byteAlign(); return 0; }; GZip.prototype.unzipFile = function(name) { var i; this.gunzip(); for (i = 0; i < this.unzipped.length; i++) if (this.unzipped[i][1] === name) return this.unzipped[i][0]; }; GZip.prototype.nextFile = function() { this.outputArr = []; this.modeZIP = false; var tmp = []; tmp[0] = this.readByte(); tmp[1] = this.readByte(); if (120 === tmp[0] && 218 === tmp[1]) { this.DeflateLoop(); this.unzipped[this.files] = [ this.outputArr.join(""), "geonext.gxt" ]; this.files++; } if (31 === tmp[0] && 139 === tmp[1]) { this.skipdir(); this.unzipped[this.files] = [ this.outputArr.join(""), "file" ]; this.files++; } if (80 === tmp[0] && 75 === tmp[1]) { this.modeZIP = true; tmp[2] = this.readByte(); tmp[3] = this.readByte(); if (3 === tmp[2] && 4 === tmp[3]) { tmp[0] = this.readByte(); tmp[1] = this.readByte(); this.gpflags = this.readByte(); this.gpflags |= this.readByte() << 8; var method = this.readByte(); method |= this.readByte() << 8; this.readByte(); this.readByte(); this.readByte(); this.readByte(); var compSize = this.readByte(); compSize |= this.readByte() << 8; compSize |= this.readByte() << 16; compSize |= this.readByte() << 24; var size = this.readByte(); size |= this.readByte() << 8; size |= this.readByte() << 16; size |= this.readByte() << 24; var filelen = this.readByte(); filelen |= this.readByte() << 8; var extralen = this.readByte(); extralen |= this.readByte() << 8; i = 0; this.nameBuf = []; while (filelen--) { var c = this.readByte(); "/" === c | ":" === c ? i = 0 : i < GZip.NAMEMAX - 1 && (this.nameBuf[i++] = String.fromCharCode(c)); } this.fileout || (this.fileout = this.nameBuf); var i = 0; while (i < extralen) { c = this.readByte(); i++; } if (8 === method) { this.DeflateLoop(); this.unzipped[this.files] = [ this.outputArr.join(""), this.nameBuf.join("") ]; this.files++; } this.skipdir(); } } }; GZip.prototype.skipdir = function() { var tmp = []; var compSize, size, os, i, c; if (8 & this.gpflags) { tmp[0] = this.readByte(); tmp[1] = this.readByte(); tmp[2] = this.readByte(); tmp[3] = this.readByte(); compSize = this.readByte(); compSize |= this.readByte() << 8; compSize |= this.readByte() << 16; compSize |= this.readByte() << 24; size = this.readByte(); size |= this.readByte() << 8; size |= this.readByte() << 16; size |= this.readByte() << 24; } this.modeZIP && this.nextFile(); tmp[0] = this.readByte(); if (8 !== tmp[0]) return 0; this.gpflags = this.readByte(); this.readByte(); this.readByte(); this.readByte(); this.readByte(); this.readByte(); os = this.readByte(); if (4 & this.gpflags) { tmp[0] = this.readByte(); tmp[2] = this.readByte(); this.len = tmp[0] + 256 * tmp[1]; for (i = 0; i < this.len; i++) this.readByte(); } if (8 & this.gpflags) { i = 0; this.nameBuf = []; while (c = this.readByte()) { "7" !== c && ":" !== c || (i = 0); i < GZip.NAMEMAX - 1 && (this.nameBuf[i++] = c); } } if (16 & this.gpflags) while (c = this.readByte()) ; if (2 & this.gpflags) { this.readByte(); this.readByte(); } this.DeflateLoop(); size = this.readByte(); size |= this.readByte() << 8; size |= this.readByte() << 16; size |= this.readByte() << 24; this.modeZIP && this.nextFile(); }; module.exports = GZip; }), {} ], 26: [ (function(require, module, exports) { (function() { "use strict"; function i(a) { throw a; } var r = void 0, v = !0, aa = this; function y(a, c) { var b = a.split("."), e = aa; !(b[0] in e) && e.execScript && e.execScript("var " + b[0]); for (var f; b.length && (f = b.shift()); ) b.length || c === r ? e = e[f] ? e[f] : e[f] = {} : e[f] = c; } var H = "undefined" !== (__typeofVal = typeof Uint8Array, "object" === __typeofVal ? __realTypeOfObj(Uint8Array) : __typeofVal) && "undefined" !== (__typeofVal = typeof Uint16Array, "object" === __typeofVal ? __realTypeOfObj(Uint16Array) : __typeofVal) && "undefined" !== (__typeofVal = typeof Uint32Array, "object" === __typeofVal ? __realTypeOfObj(Uint32Array) : __typeofVal); function ba(a) { if ("string" === (__typeofVal = typeof a, "object" === __typeofVal ? __realTypeOfObj(a) : __typeofVal)) { var c = a.split(""), b, e; b = 0; for (e = c.length; b < e; b++) c[b] = (255 & c[b].charCodeAt(0)) >>> 0; a = c; } for (var f = 1, d = 0, g = a.length, h, m = 0; 0 < g; ) { h = 1024 < g ? 1024 : g; g -= h; do { f += a[m++], d += f; } while (--h); f %= 65521; d %= 65521; } return (d << 16 | f) >>> 0; } function J(a, c) { this.index = "number" === (__typeofVal = typeof c, "object" === __typeofVal ? __realTypeOfObj(c) : __typeofVal) ? c : 0; this.i = 0; this.buffer = a instanceof (H ? Uint8Array : Array) ? a : new (H ? Uint8Array : Array)(32768); 2 * this.buffer.length <= this.index && i(Error("invalid index")); this.buffer.length <= this.index && this.f(); } J.prototype.f = function() { var a = this.buffer, c, b = a.length, e = new (H ? Uint8Array : Array)(b << 1); if (H) e.set(a); else for (c = 0; c < b; ++c) e[c] = a[c]; return this.buffer = e; }; J.prototype.d = function(a, c, b) { var e = this.buffer, f = this.index, d = this.i, g = e[f], h; b && 1 < c && (a = 8 < c ? (N[255 & a] << 24 | N[a >>> 8 & 255] << 16 | N[a >>> 16 & 255] << 8 | N[a >>> 24 & 255]) >> 32 - c : N[a] >> 8 - c); if (8 > c + d) g = g << c | a, d += c; else for (h = 0; h < c; ++h) g = g << 1 | a >> c - h - 1 & 1, 8 === ++d && (d = 0, e[f++] = N[g], g = 0, f === e.length && (e = this.f())); e[f] = g; this.buffer = e; this.i = d; this.index = f; }; J.prototype.finish = function() { var a = this.buffer, c = this.index, b; 0 < this.i && (a[c] <<= 8 - this.i, a[c] = N[a[c]], c++); H ? b = a.subarray(0, c) : (a.length = c, b = a); return b; }; var ca = new (H ? Uint8Array : Array)(256), ha; for (ha = 0; 256 > ha; ++ha) { for (var R = ha, ia = R, ja = 7, R = R >>> 1; R; R >>>= 1) ia <<= 1, ia |= 1 & R, --ja; ca[ha] = (ia << ja & 255) >>> 0; } var N = ca; var ka = [ 0, 1996959894, 3993919788, 2567524794, 124634137, 1886057615, 3915621685, 2657392035, 249268274, 2044508324, 3772115230, 2547177864, 162941995, 2125561021, 3887607047, 2428444049, 498536548, 1789927666, 4089016648, 2227061214, 450548861, 1843258603, 4107580753, 2211677639, 325883990, 1684777152, 4251122042, 2321926636, 335633487, 1661365465, 4195302755, 2366115317, 997073096, 1281953886, 3579855332, 2724688242, 1006888145, 1258607687, 3524101629, 2768942443, 901097722, 1119000684, 3686517206, 2898065728, 853044451, 1172266101, 3705015759, 2882616665, 651767980, 1373503546, 3369554304, 3218104598, 565507253, 1454621731, 3485111705, 3099436303, 671266974, 1594198024, 3322730930, 2970347812, 795835527, 1483230225, 3244367275, 3060149565, 1994146192, 31158534, 2563907772, 4023717930, 1907459465, 112637215, 2680153253, 3904427059, 2013776290, 251722036, 2517215374, 3775830040, 2137656763, 141376813, 2439277719, 3865271297, 1802195444, 476864866, 2238001368, 4066508878, 1812370925, 453092731, 2181625025, 4111451223, 1706088902, 314042704, 2344532202, 4240017532, 1658658271, 366619977, 2362670323, 4224994405, 1303535960, 984961486, 2747007092, 3569037538, 1256170817, 1037604311, 2765210733, 3554079995, 1131014506, 879679996, 2909243462, 3663771856, 1141124467, 855842277, 2852801631, 3708648649, 1342533948, 654459306, 3188396048, 3373015174, 1466479909, 544179635, 3110523913, 3462522015, 1591671054, 702138776, 2966460450, 3352799412, 1504918807, 783551873, 3082640443, 3233442989, 3988292384, 2596254646, 62317068, 1957810842, 3939845945, 2647816111, 81470997, 1943803523, 3814918930, 2489596804, 225274430, 2053790376, 3826175755, 2466906013, 167816743, 2097651377, 4027552580, 2265490386, 503444072, 1762050814, 4150417245, 2154129355, 426522225, 1852507879, 4275313526, 2312317920, 282753626, 1742555852, 4189708143, 2394877945, 397917763, 1622183637, 3604390888, 2714866558, 953729732, 1340076626, 3518719985, 2797360999, 1068828381, 1219638859, 3624741850, 2936675148, 906185462, 1090812512, 3747672003, 2825379669, 829329135, 1181335161, 3412177804, 3160834842, 628085408, 1382605366, 3423369109, 3138078467, 570562233, 1426400815, 3317316542, 2998733608, 733239954, 1555261956, 3268935591, 3050360625, 752459403, 1541320221, 2607071920, 3965973030, 1969922972, 40735498, 2617837225, 3943577151, 1913087877, 83908371, 2512341634, 3803740692, 2075208622, 213261112, 2463272603, 3855990285, 2094854071, 198958881, 2262029012, 4057260610, 1759359992, 534414190, 2176718541, 4139329115, 1873836001, 414664567, 2282248934, 4279200368, 1711684554, 285281116, 2405801727, 4167216745, 1634467795, 376229701, 2685067896, 3608007406, 1308918612, 956543938, 2808555105, 3495958263, 1231636301, 1047427035, 2932959818, 3654703836, 1088359270, 936918e3, 2847714899, 3736837829, 1202900863, 817233897, 3183342108, 3401237130, 1404277552, 615818150, 3134207493, 3453421203, 1423857449, 601450431, 3009837614, 3294710456, 1567103746, 711928724, 3020668471, 3272380065, 1510334235, 755167117 ]; H && new Uint32Array(ka); function la(a) { this.buffer = new (H ? Uint16Array : Array)(2 * a); this.length = 0; } la.prototype.getParent = function(a) { return 2 * ((a - 2) / 4 | 0); }; la.prototype.push = function(a, c) { var b, e, f = this.buffer, d; b = this.length; f[this.length++] = c; for (f[this.length++] = a; 0 < b; ) { if (e = this.getParent(b), !(f[b] > f[e])) break; d = f[b], f[b] = f[e], f[e] = d, d = f[b + 1], f[b + 1] = f[e + 1], f[e + 1] = d, b = e; } return this.length; }; la.prototype.pop = function() { var a, c, b = this.buffer, e, f, d; c = b[0]; a = b[1]; this.length -= 2; b[0] = b[this.length]; b[1] = b[this.length + 1]; for (d = 0; ;) { f = 2 * d + 2; if (f >= this.length) break; f + 2 < this.length && b[f + 2] > b[f] && (f += 2); if (!(b[f] > b[d])) break; e = b[d], b[d] = b[f], b[f] = e, e = b[d + 1], b[d + 1] = b[f + 1], b[f + 1] = e; d = f; } return { index: a, value: c, length: this.length }; }; function S(a) { var c = a.length, b = 0, e = Number.POSITIVE_INFINITY, f, d, g, h, m, j, s, n, l; for (n = 0; n < c; ++n) a[n] > b && (b = a[n]), a[n] < e && (e = a[n]); f = 1 << b; d = new (H ? Uint32Array : Array)(f); g = 1; h = 0; for (m = 2; g <= b; ) { for (n = 0; n < c; ++n) if (a[n] === g) { j = 0; s = h; for (l = 0; l < g; ++l) j = j << 1 | 1 & s, s >>= 1; for (l = j; l < f; l += m) d[l] = g << 16 | n; ++h; } ++g; h <<= 1; m <<= 1; } return [ d, b, e ]; } function ma(a, c) { this.h = pa; this.w = 0; this.input = a; this.b = 0; c && (c.lazy && (this.w = c.lazy), "number" === (__typeofVal = typeof c.compressionType, "object" === __typeofVal ? __realTypeOfObj(c.compressionType) : __typeofVal) && (this.h = c.compressionType), c.outputBuffer && (this.a = H && c.outputBuffer instanceof Array ? new Uint8Array(c.outputBuffer) : c.outputBuffer), "number" === (__typeofVal = typeof c.outputIndex, "object" === __typeofVal ? __realTypeOfObj(c.outputIndex) : __typeofVal) && (this.b = c.outputIndex)); this.a || (this.a = new (H ? Uint8Array : Array)(32768)); } var pa = 2, qa = { NONE: 0, r: 1, j: pa, N: 3 }, ra = [], T; for (T = 0; 288 > T; T++) switch (v) { case 143 >= T: ra.push([ T + 48, 8 ]); break; case 255 >= T: ra.push([ T - 144 + 400, 9 ]); break; case 279 >= T: ra.push([ T - 256 + 0, 7 ]); break; case 287 >= T: ra.push([ T - 280 + 192, 8 ]); break; default: i("invalid literal: " + T); } ma.prototype.n = function() { var a, c, b, e, f = this.input; switch (this.h) { case 0: b = 0; for (e = f.length; b < e; ) { c = H ? f.subarray(b, b + 65535) : f.slice(b, b + 65535); b += c.length; var d = c, g = b === e, h = r, m = r, j = r, s = r, n = r, l = this.a, q = this.b; if (H) { for (l = new Uint8Array(this.a.buffer); l.length <= q + d.length + 5; ) l = new Uint8Array(l.length << 1); l.set(this.a); } h = g ? 1 : 0; l[q++] = 0 | h; m = d.length; j = 65536 + ~m & 65535; l[q++] = 255 & m; l[q++] = m >>> 8 & 255; l[q++] = 255 & j; l[q++] = j >>> 8 & 255; if (H) l.set(d, q), q += d.length, l = l.subarray(0, q); else { s = 0; for (n = d.length; s < n; ++s) l[q++] = d[s]; l.length = q; } this.b = q; this.a = l; } break; case 1: var E = new J(new Uint8Array(this.a.buffer), this.b); E.d(1, 1, v); E.d(1, 2, v); var t = sa(this, f), z, K, A; z = 0; for (K = t.length; z < K; z++) if (A = t[z], J.prototype.d.apply(E, ra[A]), 256 < A) E.d(t[++z], t[++z], v), E.d(t[++z], 5), E.d(t[++z], t[++z], v); else if (256 === A) break; this.a = E.finish(); this.b = this.a.length; break; case pa: var x = new J(new Uint8Array(this.a), this.b), B, k, p, D, C, da = [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ], W, Ma, ea, Na, na, va = Array(19), Oa, $, oa, F, Pa; B = pa; x.d(1, 1, v); x.d(B, 2, v); k = sa(this, f); W = ta(this.L, 15); Ma = ua(W); ea = ta(this.K, 7); Na = ua(ea); for (p = 286; 257 < p && 0 === W[p - 1]; p--) ; for (D = 30; 1 < D && 0 === ea[D - 1]; D--) ; var Qa = p, Ra = D, M = new (H ? Uint32Array : Array)(Qa + Ra), u, O, w, fa, L = new (H ? Uint32Array : Array)(316), I, G, P = new (H ? Uint8Array : Array)(19); for (u = O = 0; u < Qa; u++) M[O++] = W[u]; for (u = 0; u < Ra; u++) M[O++] = ea[u]; if (!H) { u = 0; for (fa = P.length; u < fa; ++u) P[u] = 0; } u = I = 0; for (fa = M.length; u < fa; u += O) { for (O = 1; u + O < fa && M[u + O] === M[u]; ++O) ; w = O; if (0 === M[u]) if (3 > w) for (;0 < w--; ) L[I++] = 0, P[0]++; else for (;0 < w; ) G = 138 > w ? w : 138, G > w - 3 && G < w && (G = w - 3), 10 >= G ? (L[I++] = 17, L[I++] = G - 3, P[17]++) : (L[I++] = 18, L[I++] = G - 11, P[18]++), w -= G; else if (L[I++] = M[u], P[M[u]]++, w--, 3 > w) for (;0 < w--; ) L[I++] = M[u], P[M[u]]++; else for (;0 < w; ) G = 6 > w ? w : 6, G > w - 3 && G < w && (G = w - 3), L[I++] = 16, L[I++] = G - 3, P[16]++, w -= G; } a = H ? L.subarray(0, I) : L.slice(0, I); na = ta(P, 7); for (F = 0; 19 > F; F++) va[F] = na[da[F]]; for (C = 19; 4 < C && 0 === va[C - 1]; C--) ; Oa = ua(na); x.d(p - 257, 5, v); x.d(D - 1, 5, v); x.d(C - 4, 4, v); for (F = 0; F < C; F++) x.d(va[F], 3, v); F = 0; for (Pa = a.length; F < Pa; F++) if ($ = a[F], x.d(Oa[$], na[$], v), 16 <= $) { F++; switch ($) { case 16: oa = 2; break; case 17: oa = 3; break; case 18: oa = 7; break; default: i("invalid code: " + $); } x.d(a[F], oa, v); } var Sa = [ Ma, W ], Ta = [ Na, ea ], Q, Ua, ga, ya, Va, Wa, Xa, Ya; Va = Sa[0]; Wa = Sa[1]; Xa = Ta[0]; Ya = Ta[1]; Q = 0; for (Ua = k.length; Q < Ua; ++Q) if (ga = k[Q], x.d(Va[ga], Wa[ga], v), 256 < ga) x.d(k[++Q], k[++Q], v), ya = k[++Q], x.d(Xa[ya], Ya[ya], v), x.d(k[++Q], k[++Q], v); else if (256 === ga) break; this.a = x.finish(); this.b = this.a.length; break; default: i("invalid compression type"); } return this.a; }; function wa(a, c) { this.length = a; this.G = c; } function xa() { var a = za; switch (v) { case 3 === a: return [ 257, a - 3, 0 ]; case 4 === a: return [ 258, a - 4, 0 ]; case 5 === a: return [ 259, a - 5, 0 ]; case 6 === a: return [ 260, a - 6, 0 ]; case 7 === a: return [ 261, a - 7, 0 ]; case 8 === a: return [ 262, a - 8, 0 ]; case 9 === a: return [ 263, a - 9, 0 ]; case 10 === a: return [ 264, a - 10, 0 ]; case 12 >= a: return [ 265, a - 11, 1 ]; case 14 >= a: return [ 266, a - 13, 1 ]; case 16 >= a: return [ 267, a - 15, 1 ]; case 18 >= a: return [ 268, a - 17, 1 ]; case 22 >= a: return [ 269, a - 19, 2 ]; case 26 >= a: return [ 270, a - 23, 2 ]; case 30 >= a: return [ 271, a - 27, 2 ]; case 34 >= a: return [ 272, a - 31, 2 ]; case 42 >= a: return [ 273, a - 35, 3 ]; case 50 >= a: return [ 274, a - 43, 3 ]; case 58 >= a: return [ 275, a - 51, 3 ]; case 66 >= a: return [ 276, a - 59, 3 ]; case 82 >= a: return [ 277, a - 67, 4 ]; case 98 >= a: return [ 278, a - 83, 4 ]; case 114 >= a: return [ 279, a - 99, 4 ]; case 130 >= a: return [ 280, a - 115, 4 ]; case 162 >= a: return [ 281, a - 131, 5 ]; case 194 >= a: return [ 282, a - 163, 5 ]; case 226 >= a: return [ 283, a - 195, 5 ]; case 257 >= a: return [ 284, a - 227, 5 ]; case 258 === a: return [ 285, a - 258, 0 ]; default: i("invalid length: " + a); } } var Aa = [], za, Ba; for (za = 3; 258 >= za; za++) Ba = xa(), Aa[za] = Ba[2] << 24 | Ba[1] << 16 | Ba[0]; var Ca = H ? new Uint32Array(Aa) : Aa; function sa(a, c) { function b(a, c) { var b = a.G, d = [], e = 0, f; f = Ca[a.length]; d[e++] = 65535 & f; d[e++] = f >> 16 & 255; d[e++] = f >> 24; var g; switch (v) { case 1 === b: g = [ 0, b - 1, 0 ]; break; case 2 === b: g = [ 1, b - 2, 0 ]; break; case 3 === b: g = [ 2, b - 3, 0 ]; break; case 4 === b: g = [ 3, b - 4, 0 ]; break; case 6 >= b: g = [ 4, b - 5, 1 ]; break; case 8 >= b: g = [ 5, b - 7, 1 ]; break; case 12 >= b: g = [ 6, b - 9, 2 ]; break; case 16 >= b: g = [ 7, b - 13, 2 ]; break; case 24 >= b: g = [ 8, b - 17, 3 ]; break; case 32 >= b: g = [ 9, b - 25, 3 ]; break; case 48 >= b: g = [ 10, b - 33, 4 ]; break; case 64 >= b: g = [ 11, b - 49, 4 ]; break; case 96 >= b: g = [ 12, b - 65, 5 ]; break; case 128 >= b: g = [ 13, b - 97, 5 ]; break; case 192 >= b: g = [ 14, b - 129, 6 ]; break; case 256 >= b: g = [ 15, b - 193, 6 ]; break; case 384 >= b: g = [ 16, b - 257, 7 ]; break; case 512 >= b: g = [ 17, b - 385, 7 ]; break; case 768 >= b: g = [ 18, b - 513, 8 ]; break; case 1024 >= b: g = [ 19, b - 769, 8 ]; break; case 1536 >= b: g = [ 20, b - 1025, 9 ]; break; case 2048 >= b: g = [ 21, b - 1537, 9 ]; break; case 3072 >= b: g = [ 22, b - 2049, 10 ]; break; case 4096 >= b: g = [ 23, b - 3073, 10 ]; break; case 6144 >= b: g = [ 24, b - 4097, 11 ]; break; case 8192 >= b: g = [ 25, b - 6145, 11 ]; break; case 12288 >= b: g = [ 26, b - 8193, 12 ]; break; case 16384 >= b: g = [ 27, b - 12289, 12 ]; break; case 24576 >= b: g = [ 28, b - 16385, 13 ]; break; case 32768 >= b: g = [ 29, b - 24577, 13 ]; break; default: i("invalid distance"); } f = g; d[e++] = f[0]; d[e++] = f[1]; d[e++] = f[2]; var h, j; h = 0; for (j = d.length; h < j; ++h) l[q++] = d[h]; t[d[0]]++; z[d[3]]++; E = a.length + c - 1; n = null; } var e, f, d, g, h, m = {}, j, s, n, l = H ? new Uint16Array(2 * c.length) : [], q = 0, E = 0, t = new (H ? Uint32Array : Array)(286), z = new (H ? Uint32Array : Array)(30), K = a.w, A; if (!H) { for (d = 0; 285 >= d; ) t[d++] = 0; for (d = 0; 29 >= d; ) z[d++] = 0; } t[256] = 1; e = 0; for (f = c.length; e < f; ++e) { d = h = 0; for (g = 3; d < g && e + d !== f; ++d) h = h << 8 | c[e + d]; m[h] === r && (m[h] = []); j = m[h]; if (!(0 < E--)) { for (;0 < j.length && 32768 < e - j[0]; ) j.shift(); if (e + 3 >= f) { n && b(n, -1); d = 0; for (g = f - e; d < g; ++d) A = c[e + d], l[q++] = A, ++t[A]; break; } if (0 < j.length) { var x = r, B = r, k = 0, p = r, D = r, C = r, da = r, W = c.length, D = 0, da = j.length; a: for (;D < da; D++) { x = j[da - D - 1]; p = 3; if (3 < k) { for (C = k; 3 < C; C--) if (c[x + C - 1] !== c[e + C - 1]) continue a; p = k; } for (;258 > p && e + p < W && c[x + p] === c[e + p]; ) ++p; p > k && (B = x, k = p); if (258 === p) break; } s = new wa(k, e - B); n ? n.length < s.length ? (A = c[e - 1], l[q++] = A, ++t[A], b(s, 0)) : b(n, -1) : s.length < K ? n = s : b(s, 0); } else n ? b(n, -1) : (A = c[e], l[q++] = A, ++t[A]); } j.push(e); } l[q++] = 256; t[256]++; a.L = t; a.K = z; return H ? l.subarray(0, q) : l; } function ta(a, c) { function b(a) { var c = z[a][K[a]]; c === n ? (b(a + 1), b(a + 1)) : --E[c]; ++K[a]; } var e = a.length, f = new la(572), d = new (H ? Uint8Array : Array)(e), g, h, m, j, s; if (!H) for (j = 0; j < e; j++) d[j] = 0; for (j = 0; j < e; ++j) 0 < a[j] && f.push(j, a[j]); g = Array(f.length / 2); h = new (H ? Uint32Array : Array)(f.length / 2); if (1 === g.length) return d[f.pop().index] = 1, d; j = 0; for (s = f.length / 2; j < s; ++j) g[j] = f.pop(), h[j] = g[j].value; var n = h.length, l = new (H ? Uint16Array : Array)(c), q = new (H ? Uint8Array : Array)(c), E = new (H ? Uint8Array : Array)(n), t = Array(c), z = Array(c), K = Array(c), A = (1 << c) - n, x = 1 << c - 1, B, k, p, D, C; l[c - 1] = n; for (k = 0; k < c; ++k) A < x ? q[k] = 0 : (q[k] = 1, A -= x), A <<= 1, l[c - 2 - k] = (l[c - 1 - k] / 2 | 0) + n; l[0] = q[0]; t[0] = Array(l[0]); z[0] = Array(l[0]); for (k = 1; k < c; ++k) l[k] > 2 * l[k - 1] + q[k] && (l[k] = 2 * l[k - 1] + q[k]), t[k] = Array(l[k]), z[k] = Array(l[k]); for (B = 0; B < n; ++B) E[B] = c; for (p = 0; p < l[c - 1]; ++p) t[c - 1][p] = h[p], z[c - 1][p] = p; for (B = 0; B < c; ++B) K[B] = 0; 1 === q[c - 1] && (--E[0], ++K[c - 1]); for (k = c - 2; 0 <= k; --k) { D = B = 0; C = K[k + 1]; for (p = 0; p < l[k]; p++) D = t[k + 1][C] + t[k + 1][C + 1], D > h[B] ? (t[k][p] = D, z[k][p] = n, C += 2) : (t[k][p] = h[B], z[k][p] = B, ++B); K[k] = 0; 1 === q[k] && b(k); } m = E; j = 0; for (s = g.length; j < s; ++j) d[g[j].index] = m[j]; return d; } function ua(a) { var c = new (H ? Uint16Array : Array)(a.length), b = [], e = [], f = 0, d, g, h, m; d = 0; for (g = a.length; d < g; d++) b[a[d]] = 1 + (0 | b[a[d]]); d = 1; for (g = 16; d <= g; d++) e[d] = f, f += 0 | b[d], f > 1 << d && i("overcommitted"), f <<= 1; 65536 > f && i("undercommitted"); d = 0; for (g = a.length; d < g; d++) { f = e[a[d]]; e[a[d]] += 1; h = c[d] = 0; for (m = a[d]; h < m; h++) c[d] = c[d] << 1 | 1 & f, f >>>= 1; } return c; } function Da(a, c) { this.input = a; this.a = new (H ? Uint8Array : Array)(32768); this.h = U.j; var b = {}, e; !c && (c = {}) || "number" !== (__typeofVal = typeof c.compressionType, "object" === __typeofVal ? __realTypeOfObj(c.compressionType) : __typeofVal) || (this.h = c.compressionType); for (e in c) b[e] = c[e]; b.outputBuffer = this.a; this.z = new ma(this.input, b); } var U = qa; Da.prototype.n = function() { var a, c, b, e, f, d, g, h = 0; g = this.a; a = Ea; switch (a) { case Ea: c = Math.LOG2E * Math.log(32768) - 8; break; default: i(Error("invalid compression method")); } b = c << 4 | a; g[h++] = b; switch (a) { case Ea: switch (this.h) { case U.NONE: f = 0; break; case U.r: f = 1; break; case U.j: f = 2; break; default: i(Error("unsupported compression type")); } break; default: i(Error("invalid compression method")); } e = f << 6 | 0; g[h++] = e | 31 - (256 * b + e) % 31; d = ba(this.input); this.z.b = h; g = this.z.n(); h = g.length; H && (g = new Uint8Array(g.buffer), g.length <= h + 4 && (this.a = new Uint8Array(g.length + 4), this.a.set(g), g = this.a), g = g.subarray(0, h + 4)); g[h++] = d >> 24 & 255; g[h++] = d >> 16 & 255; g[h++] = d >> 8 & 255; g[h++] = 255 & d; return g; }; y("Zlib.Deflate", Da); y("Zlib.Deflate.compress", (function(a, c) { return new Da(a, c).n(); })); y("Zlib.Deflate.CompressionType", U); y("Zlib.Deflate.CompressionType.NONE", U.NONE); y("Zlib.Deflate.CompressionType.FIXED", U.r); y("Zlib.Deflate.CompressionType.DYNAMIC", U.j); function V(a, c) { this.k = []; this.l = 32768; this.e = this.g = this.c = this.q = 0; this.input = H ? new Uint8Array(a) : a; this.s = !1; this.m = Fa; this.B = !1; !c && (c = {}) || (c.index && (this.c = c.index), c.bufferSize && (this.l = c.bufferSize), c.bufferType && (this.m = c.bufferType), c.resize && (this.B = c.resize)); switch (this.m) { case Ga: this.b = 32768; this.a = new (H ? Uint8Array : Array)(32768 + this.l + 258); break; case Fa: this.b = 0; this.a = new (H ? Uint8Array : Array)(this.l); this.f = this.J; this.t = this.H; this.o = this.I; break; default: i(Error("invalid inflate mode")); } } var Ga = 0, Fa = 1, Ha = { D: Ga, C: Fa }; V.prototype.p = function() { for (;!this.s; ) { var a = X(this, 3); 1 & a && (this.s = v); a >>>= 1; switch (a) { case 0: var c = this.input, b = this.c, e = this.a, f = this.b, d = r, g = r, h = r, m = e.length, j = r; this.e = this.g = 0; d = c[b++]; d === r && i(Error("invalid uncompressed block header: LEN (first byte)")); g = d; d = c[b++]; d === r && i(Error("invalid uncompressed block header: LEN (second byte)")); g |= d << 8; d = c[b++]; d === r && i(Error("invalid uncompressed block header: NLEN (first byte)")); h = d; d = c[b++]; d === r && i(Error("invalid uncompressed block header: NLEN (second byte)")); h |= d << 8; g === ~h && i(Error("invalid uncompressed block header: length verify")); b + g > c.length && i(Error("input buffer is broken")); switch (this.m) { case Ga: for (;f + g > e.length; ) { j = m - f; g -= j; if (H) e.set(c.subarray(b, b + j), f), f += j, b += j; else for (;j--; ) e[f++] = c[b++]; this.b = f; e = this.f(); f = this.b; } break; case Fa: for (;f + g > e.length; ) e = this.f({ v: 2 }); break; default: i(Error("invalid inflate mode")); } if (H) e.set(c.subarray(b, b + g), f), f += g, b += g; else for (;g--; ) e[f++] = c[b++]; this.c = b; this.b = f; this.a = e; break; case 1: this.o(Ia, Ja); break; case 2: Ka(this); break; default: i(Error("unknown BTYPE: " + a)); } } return this.t(); }; var La = [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ], Za = H ? new Uint16Array(La) : La, $a = [ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 258, 258 ], ab = H ? new Uint16Array($a) : $a, bb = [ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0 ], cb = H ? new Uint8Array(bb) : bb, db = [ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577 ], eb = H ? new Uint16Array(db) : db, fb = [ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 ], gb = H ? new Uint8Array(fb) : fb, hb = new (H ? Uint8Array : Array)(288), Y, ib; Y = 0; for (ib = hb.length; Y < ib; ++Y) hb[Y] = 143 >= Y ? 8 : 255 >= Y ? 9 : 279 >= Y ? 7 : 8; var Ia = S(hb), jb = new (H ? Uint8Array : Array)(30), kb, lb; kb = 0; for (lb = jb.length; kb < lb; ++kb) jb[kb] = 5; var Ja = S(jb); function X(a, c) { for (var b = a.g, e = a.e, f = a.input, d = a.c, g; e < c; ) g = f[d++], g === r && i(Error("input buffer is broken")), b |= g << e, e += 8; g = b & (1 << c) - 1; a.g = b >>> c; a.e = e - c; a.c = d; return g; } function mb(a, c) { for (var b = a.g, e = a.e, f = a.input, d = a.c, g = c[0], h = c[1], m, j, s; e < h; ) m = f[d++], m === r && i(Error("input buffer is broken")), b |= m << e, e += 8; j = g[b & (1 << h) - 1]; s = j >>> 16; a.g = b >> s; a.e = e - s; a.c = d; return 65535 & j; } function Ka(a) { function c(a, b, c) { var d, e, f, g; for (g = 0; g < a; ) switch (d = mb(this, b), d) { case 16: for (f = 3 + X(this, 2); f--; ) c[g++] = e; break; case 17: for (f = 3 + X(this, 3); f--; ) c[g++] = 0; e = 0; break; case 18: for (f = 11 + X(this, 7); f--; ) c[g++] = 0; e = 0; break; default: e = c[g++] = d; } return c; } var b = X(a, 5) + 257, e = X(a, 5) + 1, f = X(a, 4) + 4, d = new (H ? Uint8Array : Array)(Za.length), g, h, m, j; for (j = 0; j < f; ++j) d[Za[j]] = X(a, 3); g = S(d); h = new (H ? Uint8Array : Array)(b); m = new (H ? Uint8Array : Array)(e); a.o(S(c.call(a, b, g, h)), S(c.call(a, e, g, m))); } V.prototype.o = function(a, c) { var b = this.a, e = this.b; this.u = a; for (var f = b.length - 258, d, g, h, m; 256 !== (d = mb(this, a)); ) if (256 > d) e >= f && (this.b = e, b = this.f(), e = this.b), b[e++] = d; else { g = d - 257; m = ab[g]; 0 < cb[g] && (m += X(this, cb[g])); d = mb(this, c); h = eb[d]; 0 < gb[d] && (h += X(this, gb[d])); e >= f && (this.b = e, b = this.f(), e = this.b); for (;m--; ) b[e] = b[e++ - h]; } for (;8 <= this.e; ) this.e -= 8, this.c--; this.b = e; }; V.prototype.I = function(a, c) { var b = this.a, e = this.b; this.u = a; for (var f = b.length, d, g, h, m; 256 !== (d = mb(this, a)); ) if (256 > d) e >= f && (b = this.f(), f = b.length), b[e++] = d; else { g = d - 257; m = ab[g]; 0 < cb[g] && (m += X(this, cb[g])); d = mb(this, c); h = eb[d]; 0 < gb[d] && (h += X(this, gb[d])); e + m > f && (b = this.f(), f = b.length); for (;m--; ) b[e] = b[e++ - h]; } for (;8 <= this.e; ) this.e -= 8, this.c--; this.b = e; }; V.prototype.f = function() { var a = new (H ? Uint8Array : Array)(this.b - 32768), c = this.b - 32768, b, e, f = this.a; if (H) a.set(f.subarray(32768, a.length)); else { b = 0; for (e = a.length; b < e; ++b) a[b] = f[b + 32768]; } this.k.push(a); this.q += a.length; if (H) f.set(f.subarray(c, c + 32768)); else for (b = 0; 32768 > b; ++b) f[b] = f[c + b]; this.b = 32768; return f; }; V.prototype.J = function(a) { var c, b = this.input.length / this.c + 1 | 0, e, f, d, g = this.input, h = this.a; a && ("number" === (__typeofVal = typeof a.v, "object" === __typeofVal ? __realTypeOfObj(a.v) : __typeofVal) && (b = a.v), "number" === (__typeofVal = typeof a.F, "object" === __typeofVal ? __realTypeOfObj(a.F) : __typeofVal) && (b += a.F)); 2 > b ? (e = (g.length - this.c) / this.u[2], d = e / 2 * 258 | 0, f = d < h.length ? h.length + d : h.length << 1) : f = h.length * b; H ? (c = new Uint8Array(f), c.set(h)) : c = h; return this.a = c; }; V.prototype.t = function() { var a = 0, c = this.a, b = this.k, e, f = new (H ? Uint8Array : Array)(this.q + (this.b - 32768)), d, g, h, m; if (0 === b.length) return H ? this.a.subarray(32768, this.b) : this.a.slice(32768, this.b); d = 0; for (g = b.length; d < g; ++d) { e = b[d]; h = 0; for (m = e.length; h < m; ++h) f[a++] = e[h]; } d = 32768; for (g = this.b; d < g; ++d) f[a++] = c[d]; this.k = []; return this.buffer = f; }; V.prototype.H = function() { var a, c = this.b; H ? this.B ? (a = new Uint8Array(c), a.set(this.a.subarray(0, c))) : a = this.a.subarray(0, c) : (this.a.length > c && (this.a.length = c), a = this.a); return this.buffer = a; }; function nb(a, c) { var b, e; this.input = a; this.c = 0; !c && (c = {}) || (c.index && (this.c = c.index), c.verify && (this.M = c.verify)); b = a[this.c++]; e = a[this.c++]; switch (15 & b) { case Ea: this.method = Ea; break; default: i(Error("unsupported compression method")); } 0 !== ((b << 8) + e) % 31 && i(Error("invalid fcheck flag:" + ((b << 8) + e) % 31)); 32 & e && i(Error("fdict flag is not supported")); this.A = new V(a, { index: this.c, bufferSize: c.bufferSize, bufferType: c.bufferType, resize: c.resize }); } nb.prototype.p = function() { var a = this.input, c, b; c = this.A.p(); this.c = this.A.c; this.M && (b = (a[this.c++] << 24 | a[this.c++] << 16 | a[this.c++] << 8 | a[this.c++]) >>> 0, b !== ba(c) && i(Error("invalid adler-32 checksum"))); return c; }; y("Zlib.Inflate", nb); y("Zlib.Inflate.BufferType", Ha); Ha.ADAPTIVE = Ha.C; Ha.BLOCK = Ha.D; y("Zlib.Inflate.prototype.decompress", nb.prototype.p); var ob = [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]; H && new Uint16Array(ob); var pb = [ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 258, 258 ]; H && new Uint16Array(pb); var qb = [ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0 ]; H && new Uint8Array(qb); var rb = [ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577 ]; H && new Uint16Array(rb); var sb = [ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 ]; H && new Uint8Array(sb); var tb = new (H ? Uint8Array : Array)(288), Z, ub; Z = 0; for (ub = tb.length; Z < ub; ++Z) tb[Z] = 143 >= Z ? 8 : 255 >= Z ? 9 : 279 >= Z ? 7 : 8; S(tb); var vb = new (H ? Uint8Array : Array)(30), wb, xb; wb = 0; for (xb = vb.length; wb < xb; ++wb) vb[wb] = 5; S(vb); var Ea = 8; }).call(window); var _p = window.Zlib; _p.Deflate = _p["Deflate"]; _p.Deflate.compress = _p.Deflate["compress"]; _p.Inflate = _p["Inflate"]; _p.Inflate.BufferType = _p.Inflate["BufferType"]; _p.Inflate.prototype.decompress = _p.Inflate.prototype["decompress"]; module.exports = _p; }), {} ], 27: [ (function(require, module, exports) { var debugInfos = require("../../DebugInfos") || {}; var ERROR_MAP_URL = "https://github.com/cocos-creator/engine/blob/master/EngineErrorMap.md"; var logList = void 0; cc.log = cc.warn = cc.error = cc.assert = console.log; var resetDebugSetting = function(mode) { cc.log = cc.warn = cc.error = cc.assert = function() {}; if (mode === DebugMode.NONE) return; if (mode > DebugMode.ERROR) (function() { 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) { "use strict"; 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 = console.error; 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 = console.warn; } false; if (mode === DebugMode.INFO) { true; "JavaScriptCore" === scriptEngineType ? cc.log = function() { return console.log.apply(console, arguments); } : cc.log = console.log; } }; cc._throw = function(error) { var stack = error.stack; stack ? cc.error(error + "\n" + stack) : cc.error(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) { "use strict"; 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() { return !!cc.profiler && cc.profiler.isShowingStats(); }, setDisplayStats: function(displayStats) { if (cc.profiler) { displayStats ? cc.profiler.showStats() : cc.profiler.hideStats(); cc.game.config.showFPS = !!displayStats; } } }; }), { "../../DebugInfos": 1 } ], 28: [ (function(require, module, exports) { var EventTarget = require("./event/event-target"); var AutoReleaseUtils = require("./load-pipeline/auto-release-utils"); 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.invalid = false; this._paused = false; this._purgeDirectorInNextLoop = false; this._winSizeInPoints = null; this._loadingScene = ""; this._scene = null; this._totalFrames = 0; this._lastUpdate = 0; this._deltaTime = 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() { this._totalFrames = 0; this._lastUpdate = performance.now(); 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() { 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; cc._widgetManager && cc._widgetManager.init(this); cc.loader.init(this); }, calculateDeltaTime: function() { var now = performance.now(); this._deltaTime = (now - this._lastUpdate) / 1e3; (true, this._deltaTime > 1) && (this._deltaTime = 1 / 60); this._lastUpdate = now; }, convertToGL: function(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(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() { this._purgeDirectorInNextLoop = true; }, getWinSize: function() { return cc.size(cc.winSize); }, getWinSizeInPixels: function() { return cc.size(cc.winSize); }, pause: function() { if (this._paused) return; this._paused = true; }, purgeCachedData: function() { cc.loader.releaseAll(); }, purgeDirector: function() { this._scheduler.unscheduleAll(); this._compScheduler.unscheduleAll(); this._nodeActivator.reset(); eventManager && eventManager.setEnabled(false); cc.renderer.clear(); true; cc.isValid(this._scene) && this._scene.destroy(); this._scene = null; this.stopAnimation(); cc.loader.releaseAll(); }, reset: function() { 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); this.startAnimation(); }, runSceneImmediate: function(scene, onBeforeLoadScene, onLaunched) { cc.assertID(scene instanceof cc.Scene, 1216); (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"); var autoReleaseAssets = oldScene && oldScene.autoReleaseAssets && oldScene.dependAssets; AutoReleaseUtils.autoRelease(autoReleaseAssets, scene.dependAssets, persistNodeList); (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"); this.startAnimation(); onLaunched && onLaunched(null, scene); this.emit(cc.Director.EVENT_AFTER_SCENE_LAUNCH, scene); }, runScene: function(scene, onBeforeLoadScene, onLaunched) { cc.assertID(scene, 1205); cc.assertID(scene instanceof cc.Scene, 1216); scene._load(); this.once(cc.Director.EVENT_AFTER_UPDATE, (function() { this.runSceneImmediate(scene, onBeforeLoadScene, onLaunched); }), this); }, _getSceneUuid: function(key) { var scenes = game._sceneInfos; if ("string" === (__typeofVal = typeof key, "object" === __typeofVal ? __realTypeOfObj(key) : __typeofVal)) { key.endsWith(".fire") || (key += ".fire"); "/" === key[0] || key.startsWith("db://") || (key = "/" + key); for (var i = 0; i < scenes.length; i++) { var info = scenes[i]; if (info.url.endsWith(key)) return info; } } else if ("number" === (__typeofVal = typeof key, "object" === __typeofVal ? __realTypeOfObj(key) : __typeofVal)) { if (0 <= key && key < scenes.length) return scenes[key]; cc.errorID(1206, key); } else cc.errorID(1207, key); return null; }, loadScene: function(sceneName, onLaunched, _onUnloaded) { if (this._loadingScene) { cc.errorID(1208, sceneName, this._loadingScene); return false; } var info = this._getSceneUuid(sceneName); if (info) { var uuid = info.uuid; this.emit(cc.Director.EVENT_BEFORE_SCENE_LOADING, sceneName); this._loadingScene = sceneName; this._loadSceneByUuid(uuid, onLaunched, _onUnloaded); return true; } cc.errorID(1209, sceneName); return false; }, preloadScene: function(sceneName, onProgress, onLoaded) { if (void 0 === onLoaded) { onLoaded = onProgress; onProgress = null; } var info = this._getSceneUuid(sceneName); if (info) { this.emit(cc.Director.EVENT_BEFORE_SCENE_LOADING, sceneName); cc.loader.load({ uuid: info.uuid, type: "uuid" }, onProgress, (function(error, asset) { error && cc.errorID(1210, sceneName, error.message); onLoaded && onLoaded(error, asset); })); } else { var error = 'Can not preload the scene "' + sceneName + '" because it is not in the build settings.'; onLoaded(new Error(error)); cc.error("preloadScene: " + error); } }, _loadSceneByUuid: function(uuid, onLaunched, onUnloaded, dontRunScene) { false; console.time("LoadScene " + uuid); cc.AssetLibrary.loadAsset(uuid, (function(error, sceneAsset) { console.timeEnd("LoadScene " + uuid); var self = cc.director; self._loadingScene = ""; if (error) { error = "Failed to load scene: " + error; cc.error(error); } else { if (sceneAsset instanceof cc.SceneAsset) { var scene = sceneAsset.scene; scene._id = sceneAsset._uuid; scene._name = sceneAsset._name; false; self.runSceneImmediate(scene, onUnloaded, onLaunched); return; } error = "The asset " + uuid + " is not a scene"; cc.error(error); } onLaunched && onLaunched(error); })); }, resume: function() { if (!this._paused) return; this._lastUpdate = performance.now(); this._lastUpdate || cc.logID(1200); this._paused = false; this._deltaTime = 0; }, setDepthTest: function(value) { if (!cc.Camera.main) return; cc.Camera.main.depth = !!value; }, setClearColor: function(clearColor) { if (!cc.Camera.main) return; cc.Camera.main.backgroundColor = clearColor; }, getRunningScene: function() { return this._scene; }, getScene: function() { return this._scene; }, getAnimationInterval: function() { return 1e3 / game.getFrameRate(); }, setAnimationInterval: function(value) { game.setFrameRate(Math.round(1e3 / value)); }, getDeltaTime: function() { return this._deltaTime; }, getTotalFrames: function() { return this._totalFrames; }, isPaused: function() { return this._paused; }, getScheduler: function() { return this._scheduler; }, setScheduler: function(scheduler) { this._scheduler !== scheduler && (this._scheduler = scheduler); }, getActionManager: function() { return this._actionManager; }, setActionManager: function(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() { return this._animationManager; }, getCollisionManager: function() { return this._collisionManager; }, getPhysicsManager: function() { return this._physicsManager; }, startAnimation: function() { this.invalid = false; this._lastUpdate = performance.now(); }, stopAnimation: function() { this.invalid = true; }, mainLoop: function() { if (this._purgeDirectorInNextLoop) { this._purgeDirectorInNextLoop = false; this.purgeDirector(); } else if (!this.invalid) { this.calculateDeltaTime(); 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.emit(cc.Director.EVENT_AFTER_DRAW); eventManager.frameUpdateListeners(); this._totalFrames++; } }, __fastOn: function(type, callback, target) { this.add(type, callback, target); }, __fastOff: function(type, callback, target) { this.remove(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 = new cc.Director(); module.exports = cc.director; }), { "./CCGame": 29, "./CCScheduler": 33, "./component-scheduler": 62, "./event-manager": 101, "./event/event-target": 103, "./load-pipeline/auto-release-utils": 116, "./node-activator": 132, "./platform/CCObject": 167, "./renderer": 202 } ], 29: [ (function(require, module, exports) { var EventTarget = require("./event/event-target"); require("../audio/CCAudioEngine"); var debug = require("./CCDebug"); var renderer = require("./renderer/index.js"); var inputManager = require("./platform/CCInputManager"); 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, _sceneInfos: [], frame: null, container: null, canvas: null, renderType: -1, config: null, onStart: null, setFrameRate: function(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() { return this.config.frameRate; }, step: function() { cc.director.mainLoop(); }, pause: function() { if (this._paused) return; this._paused = true; cc.audioEngine && cc.audioEngine._break(); cc.director.stopAnimation(); this._intervalId && window.cancelAnimFrame(this._intervalId); this._intervalId = 0; }, resume: function() { if (!this._paused) return; this._paused = false; cc.audioEngine && cc.audioEngine._restore(); cc.director.startAnimation(); this._runMainLoop(); }, isPaused: function() { return this._paused; }, restart: function() { 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.director.purgeDirector(); cc.audioEngine && cc.audioEngine.uncacheAll(); cc.director.reset(); game.onStart(); game.emit(game.EVENT_RESTART); })); }, end: function() { close(); }, _initEngine: function() { if (this._rendererInitialized) return; this._initRenderer(); true; this._initEvents(); this.emit(this.EVENT_ENGINE_INITED); }, _prepareFinished: function(cb) { false; this._prepared = true; this._initEngine(); console.log("SYGame Creator v" + cc.ENGINE_VERSION); this._setAnimFrame(); this._runMainLoop(); this.emit(this.EVENT_GAME_INITED); cb && cb(); }, eventTargetOn: EventTarget.prototype.on, eventTargetOnce: EventTarget.prototype.once, on: function(type, callback, target) { this._prepared && type === this.EVENT_ENGINE_INITED || !this._pause && type === this.EVENT_GAME_INITED ? callback.call(target) : this.eventTargetOn(type, callback, target); }, once: function(type, callback, target) { this._prepared && type === this.EVENT_ENGINE_INITED || !this._pause && type === this.EVENT_GAME_INITED ? callback.call(target) : this.eventTargetOnce(type, callback, target); }, prepare: function(cb) { if (this._prepared) { cb && cb(); return; } var jsList = this.config.jsList; if (jsList && jsList.length > 0) { var self = this; cc.loader.load(jsList, (function(err) { if (err) throw new Error(JSON.stringify(err)); self._prepareFinished(cb); })); } else this._prepareFinished(cb); }, run: function(config, onStart) { this._initConfig(config); this.onStart = onStart; this.prepare(game.onStart && game.onStart.bind(game)); }, addPersistRootNode: function(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; } }, removePersistRootNode: function(node) { var id = node.uuid || ""; if (node === this._persistRootNodes[id]) { delete this._persistRootNodes[id]; node._persistNode = false; } }, isPersistRootNode: function(node) { return node._persistNode; }, _setAnimFrame: function() { this._lastTime = new Date(); var frameRate = game.config.frameRate; this._frameTime = 1e3 / frameRate; true; jsb.setPreferredFramesPerSecond(frameRate); window.requestAnimFrame = window.requestAnimationFrame; window.cancelAnimFrame = window.cancelAnimationFrame; }, _stTime: function(callback) { var currTime = new Date().getTime(); 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(id) { window.clearTimeout(id); }, _runMainLoop: function() { var self = this, callback, config = self.config, director = cc.director, skip = true, frameRate = config.frameRate; debug.setDisplayStats(config.showFPS); callback = function() { if (!self._paused) { self._intervalId = window.requestAnimFrame(callback); false; director.mainLoop(); } }; self._intervalId = window.requestAnimFrame(callback); self._paused = false; }, _initConfig: function(config) { "number" !== (__typeofVal = typeof config.debugMode, "object" === __typeofVal ? __realTypeOfObj(config.debugMode) : __typeofVal) && (config.debugMode = 0); config.exposeClassName = !!config.exposeClassName; "number" !== (__typeofVal = typeof config.frameRate, "object" === __typeofVal ? __realTypeOfObj(config.frameRate) : __typeofVal) && (config.frameRate = 60); var renderMode = config.renderMode; ("number" !== (__typeofVal = typeof renderMode, "object" === __typeofVal ? __realTypeOfObj(renderMode) : __typeofVal) || renderMode > 2 || renderMode < 0) && (config.renderMode = 0); "boolean" !== (__typeofVal = typeof config.registerSystemEvent, "object" === __typeofVal ? __realTypeOfObj(config.registerSystemEvent) : __typeofVal) && (config.registerSystemEvent = true); config.showFPS = !!config.showFPS; this._sceneInfos = config.scenes || []; this.collisionMatrix = config.collisionMatrix || []; this.groupList = config.groupList || []; debug._resetDebugSetting(config.debugMode); this.config = config; this._configLoaded = true; }, _determineRenderType: function() { 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() { if (this._rendererInitialized) return; var el = this.config.id, width = void 0, height = void 0, localCanvas = void 0, localContainer = void 0; if ((false, true) || false) { this.container = localContainer = document.createElement("DIV"); this.frame = localContainer.parentNode === document.body ? document.documentElement : localContainer.parentNode; if (cc.sys.browserType === cc.sys.BROWSER_TYPE_WECHAT_GAME_SUB) localCanvas = window.sharedCanvas || wx.getSharedCanvas(); else { true; localCanvas = window.__canvas; } this.canvas = localCanvas; } else { false; { 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; function addClass(element, name) { var hasClass = (" " + element.className + " ").indexOf(" " + name + " ") > -1; if (!hasClass) { element.className && (element.className += " "); element.className += name; } } 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 }; false, false; 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() { var win = window, hiddenPropName; this.config.registerSystemEvent && inputManager.registerSystemEvent(this.canvas); "undefined" !== (__typeofVal = typeof document.hidden, "object" === __typeofVal ? __realTypeOfObj(document.hidden) : __typeofVal) ? hiddenPropName = "hidden" : "undefined" !== (__typeofVal = typeof document.mozHidden, "object" === __typeofVal ? __realTypeOfObj(document.mozHidden) : __typeofVal) ? hiddenPropName = "mozHidden" : "undefined" !== (__typeofVal = typeof document.msHidden, "object" === __typeofVal ? __realTypeOfObj(document.msHidden) : __typeofVal) ? hiddenPropName = "msHidden" : "undefined" !== (__typeofVal = typeof document.webkitHidden, "object" === __typeofVal ? __realTypeOfObj(document.webkitHidden) : __typeofVal) && (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); false; 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": 22, "../core/renderer/utils/dynamic-atlas/manager": 206, "./CCDebug": 27, "./event/event-target": 103, "./platform/BKInputManager": 159, "./platform/CCInputManager": 165, "./renderer/index.js": 202 } ], 30: [ (function(require, module, exports) { "use strict"; var BaseNode = require("./utils/base-node"); var PrefabHelper = require("./utils/prefab-helper"); var mathPools = require("./utils/math-pools"); var math = require("./renderer/render-engine").math; var AffineTrans = require("./utils/affine-transform"); var eventManager = require("./event-manager"); var macro = require("./platform/CCMacro"); var misc = require("./utils/misc"); 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() {}; var _vec2a = cc.v2(); var _vec2b = cc.v2(); var _mat4_temp = math.mat4.create(); var _vec3_temp = math.vec3.create(); var _quat_temp = math.quat.create(); var _cachedArray = new Array(16); _cachedArray.length = 0; 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 BuiltinGroupIndex = cc.Enum({ DEBUG: 31 }); var LocalDirtyFlag = cc.Enum({ POSITION: 1, SCALE: 2, ROTATION: 4, SKEW: 8, RT: 7, 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" }); 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 _currentHovered = null; var _touchStartHandler = function(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(touch, event) { var node = this.owner; event.type = EventType.TOUCH_MOVE; event.touch = touch; event.bubbles = true; node.dispatchEvent(event); }; var _touchEndHandler = function(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(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(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(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(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(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 _searchMaskInParent(node) { var Mask = cc.Mask; if (Mask) { var index = 0; for (var curr = node; curr && cc.Node.isNode(curr); curr = curr._parent, ++index) if (curr.getComponent(Mask)) return { index: index, node: curr }; } return null; } function _checkListeners(node, events) { if (!(node._objFlags & Destroying)) { var i = 0; if (node._bubblingListeners) for (;i < events.length; ++i) if (node._bubblingListeners.hasEventListener(events[i])) return true; if (node._capturingListeners) for (;i < events.length; ++i) if (node._capturingListeners.hasEventListener(events[i])) return true; return false; } return true; } function _doDispatchEvent(owner, event) { 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; for (var i = 0; i < node._children.length; i++) _updateCullingMask(node._children[i]); } var Node = cc.Class({ name: "cc.Node", extends: BaseNode, properties: { _opacity: 255, _color: cc.Color.WHITE, _contentSize: cc.Size, _anchorPoint: cc.v2(.5, .5), _position: cc.Vec3, _scaleX: { default: void 0, type: cc.Float }, _scaleY: { default: void 0, type: cc.Float }, _scale: cc.Vec3, _rotationX: 0, _rotationY: 0, _quat: cc.Quat, _skewX: 0, _skewY: 0, _zIndex: { default: void 0, type: cc.Integer }, _localZOrder: { default: 0, serializable: false }, groupIndex: { default: 0, type: cc.Integer }, group: { get: function() { return cc.game.groupList[this.groupIndex] || ""; }, set: function(value) { this.groupIndex = cc.game.groupList.indexOf(value); _updateCullingMask(this); this.emit(EventType.GROUP_CHANGED, this); } }, x: { get: function() { return this._position.x; }, set: function(value) { var localPosition = this._position; if (value !== localPosition.x) { true; var oldValue; false; localPosition.x = value; this.setLocalDirty(LocalDirtyFlag.POSITION); this._renderFlag |= RenderFlow.FLAG_WORLD_TRANSFORM; if (this._eventMask & POSITION_ON) { false; this.emit(EventType.POSITION_CHANGED); } } } }, y: { get: function() { return this._position.y; }, set: function(value) { var localPosition = this._position; if (value !== localPosition.y) { true; var oldValue; false; localPosition.y = value; this.setLocalDirty(LocalDirtyFlag.POSITION); this._renderFlag |= RenderFlow.FLAG_WORLD_TRANSFORM; if (this._eventMask & POSITION_ON) { false; this.emit(EventType.POSITION_CHANGED); } } } }, z: { get: function() { return this._position.z; }, set: function(value) { var localPosition = this._position; if (value !== localPosition.z) { true; localPosition.z = value; this.setLocalDirty(LocalDirtyFlag.POSITION); this._renderFlag |= RenderFlow.FLAG_WORLD_TRANSFORM; this._eventMask & POSITION_ON && this.emit(EventType.POSITION_CHANGED); } } }, rotation: { get: function() { return this._rotationX; }, set: function(value) { if (this._rotationX !== value || this._rotationY !== value) { this._rotationX = this._rotationY = value; math.quat.fromEuler(this._quat, 0, 0, -value); this.setLocalDirty(LocalDirtyFlag.ROTATION); this._renderFlag |= RenderFlow.FLAG_TRANSFORM; this._eventMask & ROTATION_ON && this.emit(EventType.ROTATION_CHANGED); } } }, rotationX: { get: function() { return this._rotationX; }, set: function(value) { if (this._rotationX !== value) { this._rotationX = value; this._rotationX === this._rotationY ? math.quat.fromEuler(this._quat, 0, 0, -value) : math.quat.fromEuler(this._quat, value, this._rotationY, 0); this.setLocalDirty(LocalDirtyFlag.ROTATION); this._renderFlag |= RenderFlow.FLAG_TRANSFORM; this._eventMask & ROTATION_ON && this.emit(EventType.ROTATION_CHANGED); } } }, rotationY: { get: function() { return this._rotationY; }, set: function(value) { if (this._rotationY !== value) { this._rotationY = value; this._rotationX === this._rotationY ? math.quat.fromEuler(this._quat, 0, 0, -value) : math.quat.fromEuler(this._quat, this._rotationX, value, 0); this.setLocalDirty(LocalDirtyFlag.ROTATION); this._renderFlag |= RenderFlow.FLAG_TRANSFORM; this._eventMask & ROTATION_ON && this.emit(EventType.ROTATION_CHANGED); } } }, scaleX: { get: function() { return this._scale.x; }, set: function(value) { if (this._scale.x !== value) { this._scale.x = value; this.setLocalDirty(LocalDirtyFlag.SCALE); this._renderFlag |= RenderFlow.FLAG_TRANSFORM; this._eventMask & SCALE_ON && this.emit(EventType.SCALE_CHANGED); } } }, scaleY: { get: function() { return this._scale.y; }, set: function(value) { if (this._scale.y !== value) { this._scale.y = value; this.setLocalDirty(LocalDirtyFlag.SCALE); this._renderFlag |= RenderFlow.FLAG_TRANSFORM; this._eventMask & SCALE_ON && this.emit(EventType.SCALE_CHANGED); } } }, skewX: { get: function() { return this._skewX; }, set: function(value) { this._skewX = value; this.setLocalDirty(LocalDirtyFlag.SKEW); this._renderFlag |= RenderFlow.FLAG_TRANSFORM; } }, skewY: { get: function() { return this._skewY; }, set: function(value) { this._skewY = value; this.setLocalDirty(LocalDirtyFlag.SKEW); this._renderFlag |= RenderFlow.FLAG_TRANSFORM; } }, opacity: { get: function() { return this._opacity; }, set: function(value) { if (this._opacity !== value) { this._opacity = value; this._renderFlag |= RenderFlow.FLAG_OPACITY | RenderFlow.FLAG_COLOR; } }, range: [ 0, 255 ] }, color: { get: function() { return this._color.clone(); }, set: function(value) { if (!this._color.equals(value)) { this._color.set(value); false; this._renderComponent && (this._renderFlag |= RenderFlow.FLAG_COLOR); this._eventMask & COLOR_ON && this.emit(EventType.COLOR_CHANGED, value); } } }, anchorX: { get: function() { return this._anchorPoint.x; }, set: function(value) { var anchorPoint = this._anchorPoint; if (anchorPoint.x !== value) { anchorPoint.x = value; this._eventMask & ANCHOR_ON && this.emit(EventType.ANCHOR_CHANGED); } } }, anchorY: { get: function() { return this._anchorPoint.y; }, set: function(value) { var anchorPoint = this._anchorPoint; if (anchorPoint.y !== value) { anchorPoint.y = value; this._eventMask & ANCHOR_ON && this.emit(EventType.ANCHOR_CHANGED); } } }, width: { get: function() { return this._contentSize.width; }, set: function(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() { return this._contentSize.height; }, set: function(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() { return this._localZOrder >> 16; }, set: function(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._parent && this._onSiblingIndexChanged(); } } } }, ctor: function() { this._reorderChildDirty = false; this._widget = null; this._renderComponent = null; this._capturingListeners = null; this._bubblingListeners = null; this._touchListener = null; this._mouseListener = null; this._scale.x = 1; this._scale.y = 1; this._scale.z = 1; this._matrix = mathPools.mat4.get(); this._worldMatrix = mathPools.mat4.get(); this._localMatDirty = LocalDirtyFlag.ALL; this._worldMatDirty = true; this._eventMask = 0; this._cullingMask = 1; this._childArrivalOrder = 1; }, statics: { EventType: EventType, _LocalDirtyFlag: LocalDirtyFlag, isNode: function(obj) { return obj instanceof Node && (obj.constructor === Node || !(obj instanceof cc.Scene)); }, BuiltinGroupIndex: BuiltinGroupIndex }, _onSiblingIndexChanged: function() { var parent = this._parent; var siblings = parent._children; var i = 0, len = siblings.length, sibling; for (;i < len; i++) { sibling = siblings[i]; sibling._updateOrderOfArrival(); eventManager._setDirtyForNode(sibling); } parent._delaySort(); }, _onPreDestroy: function() { var destroyByParent = this._onPreDestroyBase(); ActionManagerExist && cc.director.getActionManager().removeAllActionsFromTarget(this); _currentHovered === this && (_currentHovered = null); 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; } } mathPools.mat4.put(this._matrix); mathPools.mat4.put(this._worldMatrix); this._matrix = this._worldMatrix = null; this._reorderChildDirty && cc.director.__fastOff(cc.Director.EVENT_AFTER_UPDATE, this.sortAllChildren, this); destroyByParent || false; }, _onPostActivated: function(active) { var actionManager = ActionManagerExist ? cc.director.getActionManager() : null; if (active) { this._renderFlag |= RenderFlow.FLAG_WORLD_TRANSFORM; actionManager && actionManager.resumeTarget(this); eventManager.resumeTarget(this); if (this._touchListener) { var mask = this._touchListener.mask = _searchMaskInParent(this); this._mouseListener && (this._mouseListener.mask = mask); } else this._mouseListener && (this._mouseListener.mask = _searchMaskInParent(this)); } else { actionManager && actionManager.pauseTarget(this); eventManager.pauseTarget(this); } }, _onHierarchyChanged: function(oldParent) { this._updateOrderOfArrival(); _updateCullingMask(this); this._parent && this._parent._delaySort(); this._renderFlag |= RenderFlow.FLAG_WORLD_TRANSFORM; this._onHierarchyChangedBase(oldParent); cc._widgetManager && (cc._widgetManager._nodesOrderDirty = true); }, _upgrade_1x_to_2x: function() { if (void 0 !== this._scaleX) { this._scale.x = this._scaleX; this._scaleX = void 0; } if (void 0 !== this._scaleY) { this._scale.y = this._scaleY; this._scaleY = void 0; } if (void 0 !== this._zIndex) { this._localZOrder = this._zIndex << 16; this._zIndex = void 0; } if (0 !== this._rotationX || 0 !== this._rotationY) this._rotationX === this._rotationY ? math.quat.fromEuler(this._quat, 0, 0, -this._rotationX) : math.quat.fromEuler(this._quat, this._rotationX, this._rotationY, 0); else { var rotx = this._quat.getRoll(); var roty = this._quat.getPitch(); if (0 === rotx && 0 === roty) this._rotationX = this._rotationY = -this._quat.getYaw(); else { this._rotationX = rotx; this._rotationY = roty; } } if (this._color.a < 255 && 255 === this._opacity) { this._opacity = this._color.a; this._color.a = 255; } }, _onBatchCreated: function() { this._upgrade_1x_to_2x(); this._updateOrderOfArrival(); this._cullingMask = 1 << _getActualGroupIndex(this); var prefabInfo = this._prefab; if (prefabInfo && prefabInfo.sync && prefabInfo.root === this) { false; PrefabHelper.syncWithPrefab(this); } 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++) children[i]._onBatchCreated(); children.length > 0 && (this._renderFlag |= RenderFlow.FLAG_CHILDREN); }, _onBatchRestored: function() { this._upgrade_1x_to_2x(); this._cullingMask = 1 << _getActualGroupIndex(this); 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++) children[i]._onBatchRestored(); children.length > 0 && (this._renderFlag |= RenderFlow.FLAG_CHILDREN); }, _checknSetupSysEvent: function(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: _searchMaskInParent(this), 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: _searchMaskInParent(this), 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(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(type, callback, target, useCapture) { var _this = this; var forDispatch = this._checknSetupSysEvent(type); var eventType_hasOnceListener = "__ONCE_FLAG:" + type; var listeners = null; listeners = forDispatch && useCapture ? this._capturingListeners = this._capturingListeners || new EventTarget() : this._bubblingListeners = this._bubblingListeners || new EventTarget(); var hasOnceListener = listeners.hasEventListener(eventType_hasOnceListener, callback, target); hasOnceListener || (function() { var self = _this; var onceWrapper = function(arg1, arg2, arg3, arg4, arg5) { self.off(type, onceWrapper, target); listeners.remove(eventType_hasOnceListener, callback, target); callback.call(this, arg1, arg2, arg3, arg4, arg5); }; _this.on(type, onceWrapper, target); listeners.add(eventType_hasOnceListener, callback, target); })(); }, _onDispatch: function(type, callback, target, useCapture) { if ("boolean" === (__typeofVal = typeof target, "object" === __typeofVal ? __realTypeOfObj(target) : __typeofVal)) { 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.add(type, callback, target); target && target.__eventTargets && target.__eventTargets.push(this); } return callback; }, off: function(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(type, callback, target, useCapture) { if ("boolean" === (__typeofVal = typeof target, "object" === __typeofVal ? __realTypeOfObj(target) : __typeofVal)) { useCapture = target; target = void 0; } else useCapture = !!useCapture; if (callback) { var listeners = useCapture ? this._capturingListeners : this._bubblingListeners; if (listeners) { listeners.remove(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(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); 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(type) { var has = false; this._bubblingListeners && (has = this._bubblingListeners.hasEventListener(type)); !has && this._capturingListeners && (has = this._capturingListeners.hasEventListener(type)); return has; }, emit: function(type, arg1, arg2, arg3, arg4, arg5) { this._bubblingListeners && this._bubblingListeners.emit(type, arg1, arg2, arg3, arg4, arg5); }, dispatchEvent: function(event) { _doDispatchEvent(this, event); _cachedArray.length = 0; }, pauseSystemEvents: function(recursive) { eventManager.pauseTarget(this, recursive); }, resumeSystemEvents: function(recursive) { eventManager.resumeTarget(this, recursive); }, _hitTest: function(point, listener) { var w = this._contentSize.width, h = this._contentSize.height, cameraPt = _vec2a, testPt = _vec2b; var camera = cc.Camera.findCamera(this); camera ? camera.getCameraToWorldPoint(point, cameraPt) : cameraPt.set(point); this._updateWorldMatrix(); math.mat4.invert(_mat4_temp, this._worldMatrix); math.vec2.transformMat4(testPt, cameraPt, _mat4_temp); testPt.x += this._anchorPoint.x * w; testPt.y += this._anchorPoint.y * h; if (testPt.x >= 0 && testPt.y >= 0 && testPt.x <= w && testPt.y <= h) { if (listener && listener.mask) { var mask = listener.mask; var parent = this; for (var i = 0; parent && i < mask.index; ++i, parent = parent.parent) ; if (parent === mask.node) { var comp = parent.getComponent(cc.Mask); return !comp || !comp.enabledInHierarchy || comp._hitTest(cameraPt); } listener.mask = null; return true; } return true; } return false; }, _getCapturingTargets: function(type, array) { var parent = this.parent; while (parent) { parent._capturingListeners && parent._capturingListeners.hasEventListener(type) && array.push(parent); parent = parent.parent; } }, _getBubblingTargets: function(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); cc.director.getActionManager().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() { return new cc.Vec2(this._position); }, setPosition: function(newPosOrX, y) { var x; if (void 0 === y) { x = newPosOrX.x; y = newPosOrX.y; } else x = newPosOrX; var locPosition = this._position; if (locPosition.x === x && locPosition.y === y) return; var oldPosition; false; true; locPosition.x = x; true; locPosition.y = y; this.setLocalDirty(LocalDirtyFlag.POSITION); this._renderFlag |= RenderFlow.FLAG_WORLD_TRANSFORM; if (this._eventMask & POSITION_ON) { false; this.emit(EventType.POSITION_CHANGED); } }, getScale: function() { this._scale.x !== this._scale.y && cc.logID(1603); return this._scale.x; }, setScale: function(x, y) { if (x && "number" !== (__typeofVal = typeof x, "object" === __typeofVal ? __realTypeOfObj(x) : __typeofVal)) { y = x.y; x = x.x; } else void 0 === y && (y = x); if (this._scale.x !== x || this._scale.y !== y) { this._scale.x = x; this._scale.y = y; this.setLocalDirty(LocalDirtyFlag.SCALE); this._renderFlag |= RenderFlow.FLAG_TRANSFORM; this._eventMask & SCALE_ON && this.emit(EventType.SCALE_CHANGED); } }, getContentSize: function() { return cc.size(this._contentSize.width, this._contentSize.height); }, setContentSize: function(size, height) { var locContentSize = this._contentSize; var clone; if (void 0 === height) { if (size.width === locContentSize.width && size.height === locContentSize.height) return; false; locContentSize.width = size.width; locContentSize.height = size.height; } else { if (size === locContentSize.width && height === locContentSize.height) return; false; locContentSize.width = size; locContentSize.height = height; } if (this._eventMask & SIZE_ON) { false; this.emit(EventType.SIZE_CHANGED); } }, getAnchorPoint: function() { return cc.v2(this._anchorPoint); }, setAnchorPoint: function(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.POSITION); this._eventMask & ANCHOR_ON && this.emit(EventType.ANCHOR_CHANGED); }, _invTransformPoint: function(out, pos) { this._parent ? this._parent._invTransformPoint(out, pos) : math.vec3.copy(out, pos); math.vec3.sub(out, out, this._position); math.quat.conjugate(_quat_temp, this._quat); math.vec3.transformQuat(out, out, _quat_temp); math.vec3.inverseSafe(_vec3_temp, this._scale); math.vec3.mul(out, out, _vec3_temp); return out; }, getWorldPos: function(out) { math.vec3.copy(out, this._position); var curr = this._parent; while (curr) { math.vec3.mul(out, out, curr._scale); math.vec3.transformQuat(out, out, curr._quat); math.vec3.add(out, out, curr._position); curr = curr._parent; } return out; }, setWorldPos: function(pos) { var oldPosition; false; this._parent ? this._parent._invTransformPoint(this._position, pos) : math.vec3.copy(this._position, pos); this.setLocalDirty(LocalDirtyFlag.POSITION); if (this._eventMask & POSITION_ON) { false; this.emit(EventType.POSITION_CHANGED); } }, getWorldRot: function(out) { math.quat.copy(out, this._quat); var curr = this._parent; while (curr) { math.quat.mul(out, curr._quat, out); curr = curr._parent; } return out; }, setWorldRot: function(quat) { if (this._parent) { this._parent.getWorldRot(this._quat); math.quat.conjugate(this._quat, this._quat); math.quat.mul(this._quat, this._quat, quat); } else math.quat.copy(this._quat, quat); this.setLocalDirty(LocalDirtyFlag.ROTATION); }, getWorldRT: function(out) { var opos = _vec3_temp; var orot = _quat_temp; math.vec3.copy(opos, this._position); math.quat.copy(orot, this._quat); var curr = this._parent; while (curr) { math.vec3.mul(opos, opos, curr._scale); math.vec3.transformQuat(opos, opos, curr._quat); math.vec3.add(opos, opos, curr._position); math.quat.mul(orot, curr._quat, orot); curr = curr._parent; } math.mat4.fromRT(out, orot, opos); return out; }, lookAt: function(pos, up) { this.getWorldPos(_vec3_temp); math.vec3.sub(_vec3_temp, _vec3_temp, pos); math.vec3.normalize(_vec3_temp, _vec3_temp); math.quat.fromViewUp(_quat_temp, _vec3_temp, up); this.setWorldRot(_quat_temp); }, _updateLocalMatrix: function() { var dirtyFlag = this._localMatDirty; if (!dirtyFlag) return; var t = this._matrix; if (dirtyFlag & (LocalDirtyFlag.RT | LocalDirtyFlag.SKEW)) { var hasRotation = this._rotationX || this._rotationY; var hasSkew = this._skewX || this._skewY; var sx = this._scale.x, sy = this._scale.y; if (hasRotation || hasSkew) { var a = 1, b = 0, c = 0, d = 1; if (hasRotation) { var rotationRadiansX = this._rotationX * ONE_DEGREE; c = Math.sin(rotationRadiansX); d = Math.cos(rotationRadiansX); if (this._rotationY === this._rotationX) { a = d; b = -c; } else { var rotationRadiansY = this._rotationY * ONE_DEGREE; a = Math.cos(rotationRadiansY); b = -Math.sin(rotationRadiansY); } } t.m00 = a *= sx; t.m01 = b *= sx; t.m04 = c *= sy; t.m05 = d *= sy; if (hasSkew) { var _a = t.m00, _b = t.m01, _c = t.m04, _d = t.m05; var skx = Math.tan(this._skewX * ONE_DEGREE); var sky = Math.tan(this._skewY * ONE_DEGREE); Infinity === skx && (skx = 99999999); Infinity === sky && (sky = 99999999); t.m00 = _a + _c * sky; t.m01 = _b + _d * sky; t.m04 = _c + _a * skx; t.m05 = _d + _b * skx; } } else { t.m00 = sx; t.m01 = 0; t.m04 = 0; t.m05 = sy; } } t.m12 = this._position.x; t.m13 = this._position.y; this._localMatDirty = 0; this._worldMatDirty = true; }, _calculWorldMatrix: function() { this._localMatDirty && this._updateLocalMatrix(); var parent = this._parent; if (parent) { var pt = parent._worldMatrix; var t = this._matrix; var wt = this._worldMatrix; var aa = t.m00, ab = t.m01, ac = t.m04, ad = t.m05, atx = t.m12, aty = t.m13; var ba = pt.m00, bb = pt.m01, bc = pt.m04, bd = pt.m05, btx = pt.m12, bty = pt.m13; if (0 !== bb || 0 !== bc) { wt.m00 = aa * ba + ab * bc; wt.m01 = aa * bb + ab * bd; wt.m04 = ac * ba + ad * bc; wt.m05 = ac * bb + ad * bd; wt.m12 = ba * atx + bc * aty + btx; wt.m13 = bb * atx + bd * aty + bty; } else { wt.m00 = aa * ba; wt.m01 = ab * bd; wt.m04 = ac * ba; wt.m05 = ad * bd; wt.m12 = ba * atx + btx; wt.m13 = bd * aty + bty; } } else math.mat4.copy(this._worldMatrix, this._matrix); this._worldMatDirty = false; }, _updateWorldMatrix: function() { 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(flag) { this._localMatDirty = this._localMatDirty | flag; this._worldMatDirty = true; }, setWorldDirty: function() { this._worldMatDirty = true; }, getLocalMatrix: function(out) { this._updateLocalMatrix(); return math.mat4.copy(out, this._matrix); }, getWorldMatrix: function(out) { this._updateWorldMatrix(); return math.mat4.copy(out, this._worldMatrix); }, convertToNodeSpace: function(worldPoint) { this._updateWorldMatrix(); math.mat4.invert(_mat4_temp, this._worldMatrix); var out = new cc.Vec2(); math.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(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 math.vec2.transformMat4(out, out, this._worldMatrix); }, convertToNodeSpaceAR: function(worldPoint) { this._updateWorldMatrix(); math.mat4.invert(_mat4_temp, this._worldMatrix); var out = new cc.Vec2(); return math.vec2.transformMat4(out, worldPoint, _mat4_temp); }, convertToWorldSpaceAR: function(nodePoint) { this._updateWorldMatrix(); var out = new cc.Vec2(); return math.vec2.transformMat4(out, nodePoint, this._worldMatrix); }, getNodeToParentTransform: function(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; math.mat4.copy(_mat4_temp, this._matrix); math.mat4.translate(_mat4_temp, _mat4_temp, _vec3_temp); return AffineTrans.fromMat4(out, _mat4_temp); }, getNodeToParentTransformAR: function(out) { out || (out = AffineTrans.identity()); this._updateLocalMatrix(); return AffineTrans.fromMat4(out, this._matrix); }, getNodeToWorldTransform: function(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; math.mat4.copy(_mat4_temp, this._worldMatrix); math.mat4.translate(_mat4_temp, _mat4_temp, _vec3_temp); return AffineTrans.fromMat4(out, _mat4_temp); }, getNodeToWorldTransformAR: function(out) { out || (out = AffineTrans.identity()); this._updateWorldMatrix(); return AffineTrans.fromMat4(out, this._worldMatrix); }, getParentToNodeTransform: function(out) { out || (out = AffineTrans.identity()); this._updateLocalMatrix(); math.mat4.invert(_mat4_temp, this._matrix); return AffineTrans.fromMat4(out, _mat4_temp); }, getWorldToNodeTransform: function(out) { out || (out = AffineTrans.identity()); this._updateWorldMatrix(); math.mat4.invert(_mat4_temp, this._worldMatrix); return AffineTrans.fromMat4(out, _mat4_temp); }, convertTouchToNodeSpace: function(touch) { return this.convertToNodeSpace(touch.getLocation()); }, convertTouchToNodeSpaceAR: function(touch) { return this.convertToNodeSpaceAR(touch.getLocation()); }, getBoundingBox: function() { 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() { if (this._parent) { this._parent._updateWorldMatrix(); return this._getBoundingBoxTo(this._parent._worldMatrix); } return this.getBoundingBox(); }, _getBoundingBoxTo: function(parentMat) { 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); var parentMat = math.mat4.mul(this._worldMatrix, parentMat, this._matrix); rect.transformMat4(rect, parentMat); 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(parentMat); childRect && rect.union(rect, childRect); } } return rect; }, _updateOrderOfArrival: function() { var arrivalOrder = this._parent ? ++this._parent._childArrivalOrder : 0; this._localZOrder = 4294901760 & this._localZOrder | arrivalOrder; if (65535 === arrivalOrder) { var siblings = this._parent._children; siblings.forEach((function(node, index) { node._localZOrder = 4294901760 & node._localZOrder | index + 1; })); this._parent._childArrivalOrder = siblings.length; } }, addChild: function(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() { 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() { if (this._reorderChildDirty) { this._reorderChildDirty = false; var _children = this._children; if (_children.length > 1) { var len = _children.length, i, j, child; for (i = 1; i < len; i++) { child = _children[i]; j = i - 1; while (j >= 0) { if (!(child._localZOrder < _children[j]._localZOrder)) break; _children[j + 1] = _children[j]; j--; } _children[j + 1] = child; } this.emit(EventType.CHILD_REORDER, this); } cc.director.__fastOff(cc.Director.EVENT_AFTER_UPDATE, this.sortAllChildren, this); } }, _delaySort: function() { if (!this._reorderChildDirty) { this._reorderChildDirty = true; cc.director.__fastOn(cc.Director.EVENT_AFTER_UPDATE, this.sortAllChildren, this); } }, _restoreProperties: false, onRestore: false }); var SameNameGetSets = [ "position", "scale", "rotation" ]; misc.propertyDefine(Node, SameNameGetSets); cc.Node = module.exports = Node; }), { "./event-manager": 101, "./event/event": 104, "./event/event-target": 103, "./platform/CCMacro": 166, "./platform/js": 181, "./renderer/render-engine": 203, "./renderer/render-flow": 204, "./utils/affine-transform": 235, "./utils/base-node": 236, "./utils/math-pools": 242, "./utils/misc": 243, "./utils/prefab-helper": 246 } ], 31: [ (function(require, module, exports) { "use strict"; var Node = require("./CCNode"); var RenderFlow = require("./renderer/render-flow"); var math = require("./renderer/render-engine").math; var LocalDirtyFlag = Node._LocalDirtyFlag; var POSITION_ON = 1; var _vec3_temp = math.vec3.create(); var PrivateNode = cc.Class({ name: "cc.PrivateNode", extends: Node, properties: { x: { get: function() { return this._originPos.x; }, set: function(value) { var localPosition = this._originPos; if (value !== localPosition.x) { localPosition.x = value; this._posDirty(true); } }, override: true }, y: { get: function() { return this._originPos.y; }, set: function(value) { var localPosition = this._originPos; if (value !== localPosition.y) { localPosition.y = value; this._posDirty(true); } }, override: true }, zIndex: { get: function() { return cc.macro.MIN_ZINDEX; }, set: function() { cc.warnID(1638); }, override: true } }, ctor: function(name) { this._localZOrder = cc.macro.MIN_ZINDEX << 16; this._originPos = cc.v2(); }, _posDirty: function(sendEvent) { this.setLocalDirty(LocalDirtyFlag.POSITION); this._renderFlag |= RenderFlow.FLAG_TRANSFORM; true === sendEvent && this._eventMask & POSITION_ON && this.emit(Node.EventType.POSITION_CHANGED); }, _updateLocalMatrix: function() { if (!this._localMatDirty) return; var parent = this.parent; if (parent) { this._position.x = this._originPos.x - (parent._anchorPoint.x - .5) * parent._contentSize.width; this._position.y = this._originPos.y - (parent._anchorPoint.y - .5) * parent._contentSize.height; } this._super(); }, getPosition: function() { return new cc.Vec2(this._originPos); }, setPosition: function(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(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() {} }); cc.js.getset(PrivateNode.prototype, "parent", PrivateNode.prototype.getParent, PrivateNode.prototype.setParent); cc.js.getset(PrivateNode.prototype, "position", PrivateNode.prototype.getPosition, PrivateNode.prototype.setPosition); cc.PrivateNode = module.exports = PrivateNode; }), { "./CCNode": 30, "./renderer/render-engine": 203, "./renderer/render-flow": 204 } ], 32: [ (function(require, module, exports) { var NIL = function() {}; cc.Scene = cc.Class({ name: "cc.Scene", extends: require("./CCNode"), properties: { autoReleaseAssets: { default: void 0, type: cc.Boolean } }, ctor: function() { this._anchorPoint.x = 0; this._anchorPoint.y = 0; this._activeInHierarchy = false; this._inited = !cc.game._isCloning; false; this.dependAssets = null; }, destroy: function() { 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() { if (!this._inited) { false; false; this._onBatchCreated(); this._inited = true; } }, _activate: function(active) { active = false !== active; false, false; cc.director._nodeActivator.activateNode(this, active); } }); module.exports = cc.Scene; }), { "./CCNode": 30 } ], 33: [ (function(require, module, exports) { var js = require("./platform/js"); var IdGenerater = require("./platform/id-generater"); var MAX_POOL_SIZE = 20; var idGenerater = new IdGenerater("Scheduler"); var ListEntry = function(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(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(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(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(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(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(ppList, listElement) { ppList.push(listElement); }, enableForTarget: function(target) { target._id || (target.__instanceId ? cc.warnID(1513) : target._id = idGenerater.getNewId()); }, setTimeScale: function(timeScale) { this._timeScale = timeScale; }, getTimeScale: function() { return this._timeScale; }, update: function(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(callback, target, interval, repeat, delay, paused) { "use strict"; if ("function" !== (__typeofVal = typeof callback, "object" === __typeofVal ? __realTypeOfObj(callback) : __typeofVal)) { 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(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(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(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(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() { this.unscheduleAllWithMinPriority(cc.Scheduler.PRIORITY_SYSTEM); }, unscheduleAllWithMinPriority: function(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(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() { return this.pauseAllTargetsWithMinPriority(cc.Scheduler.PRIORITY_SYSTEM); }, pauseAllTargetsWithMinPriority: function(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(targetsToResume) { if (!targetsToResume) return; for (var i = 0; i < targetsToResume.length; i++) this.resumeTarget(targetsToResume[i]); }, pauseTarget: function(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(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(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": 177, "./platform/js": 181 } ], 34: [ (function(require, module, exports) { var RawAsset = require("./CCRawAsset"); cc.Asset = cc.Class({ name: "cc.Asset", extends: RawAsset, ctor: function() { this.loaded = true; }, properties: { nativeUrl: { get: function() { if (this._native) { var name = this._native; if (47 === name.charCodeAt(0)) return name.slice(1); if (cc.AssetLibrary) { var base = cc.AssetLibrary.getLibUrlNoExt(this._uuid, true); return 46 === name.charCodeAt(0) ? base + name : base + "/" + name; } cc.errorID(6400); } return ""; }, visible: false }, _native: "", _nativeAsset: { get: function() {}, set: function(obj) {} } }, statics: { deserialize: false, preventDeferredLoadDependents: false, preventPreloadNativeObject: false }, toString: function() { return this.nativeUrl; }, serialize: false, createNode: null, _setRawAsset: function(filename, inLibrary) { this._native = false !== inLibrary ? filename || void 0 : "/" + filename; } }); module.exports = cc.Asset; }), { "./CCRawAsset": 42 } ], 35: [ (function(require, module, exports) { 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() { this.loaded = false; this._audio = null; }, properties: { loadMode: { default: LoadMode.WEB_AUDIO, type: LoadMode }, _nativeAsset: { get: function() { return this._audio; }, set: function(value) { value instanceof cc.AudioClip ? this._audio = value._nativeAsset : this._audio = value; if (this._audio) { this.loaded = true; this.emit("load"); } }, override: true } }, statics: { LoadMode: LoadMode, _loadByUrl: function(url, callback) { var item = cc.loader.getItem(url) || cc.loader.getItem(url + "?useDom=1"); item && item.complete ? item._owner instanceof AudioClip ? callback(null, item._owner) : callback(null, item.content) : cc.loader.load(url, (function(error, downloadUrl) { if (error) return callback(error); item = cc.loader.getItem(url) || cc.loader.getItem(url + "?useDom=1"); callback(null, item.content); })); } }, destroy: function() { cc.audioEngine.uncache(this); this._super(); } }); cc.AudioClip = AudioClip; module.exports = AudioClip; }), { "../event/event-target": 103, "./CCAsset": 34 } ], 36: [ (function(require, module, exports) { var BitmapFont = cc.Class({ name: "cc.BitmapFont", extends: cc.Font, properties: { fntDataStr: { default: "" }, spriteFrame: { default: null, type: cc.SpriteFrame }, fontSize: { default: -1 }, _fntConfig: null } }); cc.BitmapFont = BitmapFont; module.exports = BitmapFont; }), {} ], 37: [ (function(require, module, exports) { var BufferAsset = cc.Class({ name: "cc.BufferAsset", extends: cc.Asset, ctor: function() { this._buffer = null; }, properties: { _nativeAsset: { get: function() { return this._buffer; }, set: function(bin) { this._buffer = bin.buffer || bin; }, override: true } } }); cc.BufferAsset = module.exports = BufferAsset; }), {} ], 38: [ (function(require, module, exports) { var Font = cc.Class({ name: "cc.Font", extends: cc.Asset }); cc.Font = module.exports = Font; }), {} ], 39: [ (function(require, module, exports) { var JsonAsset = cc.Class({ name: "cc.JsonAsset", extends: cc.Asset, properties: { json: null } }); module.exports = cc.JsonAsset = JsonAsset; }), {} ], 40: [ (function(require, module, exports) { var LabelAtlas = cc.Class({ name: "cc.LabelAtlas", extends: cc.BitmapFont }); cc.LabelAtlas = LabelAtlas; module.exports = LabelAtlas; }), {} ], 41: [ (function(require, module, exports) { var OptimizationPolicy = cc.Enum({ AUTO: 0, SINGLE_INSTANCE: 1, MULTI_INSTANCE: 2 }); var Prefab = cc.Class({ name: "cc.Prefab", extends: cc.Asset, ctor: function() { this._createFunction = null; this._instantiatedTimes = 0; }, properties: { data: null, optimizationPolicy: OptimizationPolicy.AUTO, asyncLoadAssets: false }, statics: { OptimizationPolicy: OptimizationPolicy, OptimizationPolicyThreshold: 3 }, createNode: false, compileCreateFunction: function() { var jit = require("../platform/instantiate-jit"); this._createFunction = jit.compile(this.data); }, _doInstantiate: function(rootToRedirect) { this.data._prefab ? this.data._prefab._synced = true : cc.warnID(3700); this._createFunction || this.compileCreateFunction(); return this._createFunction(rootToRedirect); }, _instantiate: function() { var node, useJit = false; true; useJit = true; if (useJit) { node = this._doInstantiate(); this.data._instantiate(node); } else { this.data._prefab._synced = true; node = this.data._instantiate(); } ++this._instantiatedTimes; var PrefabUtils; false, false; return node; } }); cc.Prefab = module.exports = Prefab; cc.js.obsolete(cc, "cc._Prefab", "Prefab"); }), { "../platform/instantiate-jit": 179 } ], 42: [ (function(require, module, exports) { var CCObject = require("../platform/CCObject"); var js = require("../platform/js"); cc.RawAsset = cc.Class({ name: "cc.RawAsset", extends: CCObject, ctor: function() { Object.defineProperty(this, "_uuid", { value: "", writable: true }); } }); js.value(cc.RawAsset, "isRawAssetType", (function(ctor) { return js.isChildClassOf(ctor, cc.RawAsset) && !js.isChildClassOf(ctor, cc.Asset); })); js.value(cc.RawAsset, "wasRawAssetType", (function(ctor) { return ctor === cc.Texture2D || ctor === cc.AudioClip || ctor === cc.ParticleAsset || ctor === cc.Asset; })); module.exports = cc.RawAsset; }), { "../platform/CCObject": 167, "../platform/js": 181 } ], 43: [ (function(require, module, exports) { var renderer = require("../renderer"); var renderEngine = require("../renderer/render-engine"); var gfx = renderEngine.gfx; var Texture2D = require("./CCTexture2D"); var RenderTexture = cc.Class({ name: "cc.RenderTexture", extends: Texture2D, ctor: function() { this._framebuffer = null; }, initWithSize: function(width, height, depthStencilFormat) { this.width = Math.floor(width || cc.visibleRect.width); this.height = Math.floor(height || cc.visibleRect.height); var opts = {}; opts.format = this._format; opts.width = width; opts.height = height; opts.images = void 0; opts.wrapS = this._wrapS; opts.wrapT = this._wrapT; opts.premultiplyAlpha = this._premultiplyAlpha; opts.minFilter = Texture2D._FilterIndex[this._minFilter]; opts.magFilter = Texture2D._FilterIndex[this._magFilter]; this._texture ? this._texture.update(opts) : this._texture = new renderer.Texture2D(renderer.device, opts); opts = { colors: [ this._texture ] }; if (depthStencilFormat) { var depthStencilBuffer = new gfx.RenderBuffer(renderer.device, depthStencilFormat, width, height); depthStencilFormat === gfx.RB_FMT_D24S8 ? opts.depth = opts.stencil = depthStencilBuffer : depthStencilFormat === gfx.RB_FMT_S8 ? opts.stencil = depthStencilBuffer : depthStencilFormat === gl.RB_FMT_D16 && (opts.depth = depthStencilBuffer); } this._framebuffer && this._framebuffer.destroy(); this._framebuffer = new renderEngine.gfx.FrameBuffer(renderer.device, width, height, opts); this.loaded = true; this.emit("load"); }, drawTextureAt: function(texture, x, y) { if (!texture._image) 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(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 = renderer._forward._device._gl; var oldFBO = gl.getParameter(gl.FRAMEBUFFER_BINDING); gl.bindFramebuffer(gl.FRAMEBUFFER, this._framebuffer._glID); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this._texture._glID, 0); gl.readPixels(x, y, width, height, gl.RGBA, gl.UNSIGNED_BYTE, data); gl.bindFramebuffer(gl.FRAMEBUFFER, oldFBO); return data; }, destroy: function() { this._super(); this._framebuffer && this._framebuffer.destroy(); } }); cc.RenderTexture = module.exports = RenderTexture; }), { "../renderer": 202, "../renderer/render-engine": 203, "./CCTexture2D": 50 } ], 44: [ (function(require, module, exports) { var Scene = cc.Class({ name: "cc.SceneAsset", extends: cc.Asset, properties: { scene: null, asyncLoadAssets: void 0 } }); cc.SceneAsset = Scene; module.exports = Scene; }), {} ], 45: [ (function(require, module, exports) { 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 CoffeeScript = cc.Class({ name: "cc.CoffeeScript", extends: Script }); cc._CoffeeScript = CoffeeScript; var TypeScript = cc.Class({ name: "cc.TypeScript", extends: Script }); cc._TypeScript = TypeScript; }), {} ], 46: [ (function(require, module, exports) { var SpriteAtlas = cc.Class({ name: "cc.SpriteAtlas", extends: cc.Asset, properties: { _spriteFrames: { default: {} } }, getTexture: function() { 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(key) { var sf = this._spriteFrames[key]; if (!sf) return null; sf.name || (sf.name = key); return sf; }, getSpriteFrames: function() { var frames = []; var spriteFrames = this._spriteFrames; for (var key in spriteFrames) frames.push(this.getSpriteFrame(key)); return frames; } }); cc.SpriteAtlas = SpriteAtlas; module.exports = SpriteAtlas; }), {} ], 47: [ (function(require, module, exports) { var EventTarget = require("../event/event-target"); var textureUtil = require("../utils/texture-util"); 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(texture) { if (texture) { false; this._texture !== texture && this._refreshTexture(texture); this._textureFilename = texture.url; } } }, insetTop: { get: function() { return this._capInsets[INSET_TOP]; }, set: function(value) { this._capInsets[INSET_TOP] = value; this._texture && this._calculateSlicedUV(); } }, insetBottom: { get: function() { return this._capInsets[INSET_BOTTOM]; }, set: function(value) { this._capInsets[INSET_BOTTOM] = value; this._texture && this._calculateSlicedUV(); } }, insetLeft: { get: function() { return this._capInsets[INSET_LEFT]; }, set: function(value) { this._capInsets[INSET_LEFT] = value; this._texture && this._calculateSlicedUV(); } }, insetRight: { get: function() { return this._capInsets[INSET_RIGHT]; }, set: function(value) { this._capInsets[INSET_RIGHT] = value; this._texture && this._calculateSlicedUV(); } } }, ctor: function() { 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.vertices = null; this._capInsets = [ 0, 0, 0, 0 ]; this.uvSliced = []; this._textureFilename = ""; false; void 0 !== filename && this.setTexture(filename, rect, rotated, offset, originalSize); }, textureLoaded: function() { return this._texture && this._texture.loaded; }, isRotated: function() { return this._rotated; }, setRotated: function(bRotated) { this._rotated = bRotated; this._texture && this._calculateUV(); }, getRect: function() { return cc.rect(this._rect); }, setRect: function(rect) { this._rect = rect; this._texture && this._calculateUV(); }, getOriginalSize: function() { return cc.size(this._originalSize); }, setOriginalSize: function(size) { if (this._originalSize) { this._originalSize.width = size.width; this._originalSize.height = size.height; } else this._originalSize = cc.size(size); }, getTexture: function() { return this._texture; }, _textureLoadedCallback: function() { var self = this; var texture = this._texture; if (!texture) return; var w = texture.width, h = texture.height; if (self._rotated && cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) { self._rotated = false; w = self._texture.width; h = self._texture.height; self._rect = cc.rect(0, 0, w, h); } 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(texture) { this._texture = texture; texture.loaded ? this._textureLoadedCallback() : texture.once("load", this._textureLoadedCallback, this); }, getOffset: function() { return cc.v2(this._offset); }, setOffset: function(offsets) { this._offset = cc.v2(offsets); }, clone: function() { return new SpriteFrame(this._texture || this._textureFilename, this._rect, this._rotated, this._offset, this._originalSize); }, setTexture: function(textureOrTextureFile, rect, rotated, offset, originalSize) { this._rect = rect || null; offset ? this.setOffset(offset) : this._offset = null; originalSize ? this.setOriginalSize(originalSize) : this._originalSize = null; this._rotated = rotated || false; var texture = textureOrTextureFile; if ("string" === (__typeofVal = typeof texture, "object" === __typeofVal ? __realTypeOfObj(texture) : __typeofVal) && texture) { this._textureFilename = texture; this._loadTexture(); } texture instanceof cc.Texture2D && this._texture !== texture && this._refreshTexture(texture); return true; }, _loadTexture: function() { if (this._textureFilename) { var texture = textureUtil.loadImage(this._textureFilename); this._refreshTexture(texture); } }, ensureLoadTexture: function() { if (this._texture) { if (!this._texture.loaded) { this._refreshTexture(this._texture); textureUtil.postLoadTexture(this._texture); } } else this._textureFilename && this._loadTexture(); }, clearTexture: function() { this._texture = null; }, _checkRect: function(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.url + "/" + this.name, maxX, texture.width); maxY > texture.height && cc.errorID(3400, texture.url + "/" + this.name, maxY, texture.height); }, _calculateSlicedUV: function() { 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; 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; 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(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() { 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(); }, _calculateUV: function() { 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; } 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, _deserialize: function(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 = data.texture; textureUuid && handle.result.push(this, "_textureSetter", textureUuid); } }); var proto = SpriteFrame.prototype; proto.copyWithZone = proto.clone; proto.copy = proto.clone; proto.initWithTexture = proto.setTexture; cc.SpriteFrame = SpriteFrame; module.exports = SpriteFrame; }), { "../assets/CCAsset": 34, "../event/event-target": 103, "../utils/texture-util": 251 } ], 48: [ (function(require, module, exports) { var Font = require("./CCFont"); var TTFFont = cc.Class({ name: "cc.TTFFont", extends: Font, properties: { _fontFamily: null, _nativeAsset: { type: cc.String, get: function() { return this._fontFamily; }, set: function(value) { this._fontFamily = value || "Arial"; }, override: true } } }); cc.TTFFont = module.exports = TTFFont; }), { "./CCFont": 38 } ], 49: [ (function(require, module, exports) { var TextAsset = cc.Class({ name: "cc.TextAsset", extends: cc.Asset, properties: { text: "" }, toString: function() { return this.text; } }); module.exports = cc.TextAsset = TextAsset; }), {} ], 50: [ (function(require, module, exports) { var EventTarget = require("../event/event-target"); var renderEngine = require("../renderer/render-engine"); var renderer = require("../renderer"); require("../platform/CCClass"); var gfx = renderEngine.gfx; var GL_NEAREST = 9728; var GL_LINEAR = 9729; var GL_REPEAT = 10497; var GL_CLAMP_TO_EDGE = 33071; var GL_MIRRORED_REPEAT = 33648; var CHAR_CODE_0 = 48; var CHAR_CODE_1 = 49; var idGenerater = new (require("../platform/id-generater"))("Tex"); var PixelFormat = cc.Enum({ RGB565: gfx.TEXTURE_FMT_R5_G6_B5, RGB5A1: gfx.TEXTURE_FMT_R5_G5_B5_A1, RGBA4444: gfx.TEXTURE_FMT_R4_G4_B4_A4, RGB888: gfx.TEXTURE_FMT_RGB8, RGBA8888: gfx.TEXTURE_FMT_RGBA8, A8: gfx.TEXTURE_FMT_A8, I8: gfx.TEXTURE_FMT_L8, AI8: gfx.TEXTURE_FMT_L8_A8 }); 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, mipmap: 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; _sharedOpts.flipY = false; return _sharedOpts; } var Texture2D = cc.Class({ name: "cc.Texture2D", extends: require("../assets/CCAsset"), mixins: [ EventTarget ], properties: { _nativeAsset: { get: function() { return this._image; }, set: function(image) { this.initWithElement(image); }, override: true }, _hasMipmap: false, _format: PixelFormat.RGBA8888, _premultiplyAlpha: false, _flipY: false, _minFilter: Filter.LINEAR, _magFilter: Filter.LINEAR, _wrapS: WrapMode.CLAMP_TO_EDGE, _wrapT: WrapMode.CLAMP_TO_EDGE }, statics: { PixelFormat: PixelFormat, WrapMode: WrapMode, Filter: Filter, _FilterIndex: FilterIndex, extnames: [ ".png", ".jpg", ".jpeg", ".bmp", ".webp" ] }, ctor: function() { this._id = idGenerater.getNewId(); this.url = ""; this.loaded = false; this.width = 0; this.height = 0; this._hashDirty = true; this._hash = 0; this._texture = null; }, getImpl: function() { return this._texture; }, getId: function() { return this._id; }, toString: function() { return this.url || ""; }, update: function(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]; } 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.mipmap && (this._hasMipmap = options.mipmap); 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); } options.images && options.images.length > 0 && this._texture.update(options); this._hashDirty = true; } }, initWithElement: function(element) { if (!element) return; this._image = element; if ((false, false) || element.complete || element instanceof HTMLCanvasElement) this.handleLoadedTexture(); else { var self = this; element.addEventListener("load", (function() { self.handleLoadedTexture(); })); element.addEventListener("error", (function(err) { cc.warnID(3119, err.message); })); } }, initWithData: function(data, pixelFormat, pixelsWidth, pixelsHeight) { var opts = _getSharedOptions(); opts.image = data; opts.images = [ opts.image ]; opts.hasMipmap = this._hasMipmap; 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 = pixelFormat; opts.width = pixelsWidth; opts.height = pixelsHeight; this._texture ? this.update(opts) : this._texture = new renderer.Texture2D(renderer.device, opts); this.width = pixelsWidth; this.height = pixelsHeight; this.loaded = true; this.emit("load"); return true; }, getHtmlElementObj: function() { return this._image; }, destroy: function() { this._image = null; this._texture && this._texture.destroy(); this._super(); }, getPixelFormat: function() { return this._format; }, hasPremultipliedAlpha: function() { return this._premultiplyAlpha || false; }, hasMipmap: function() { return this._hasMipmap || false; }, handleLoadedTexture: function() { 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.hasMipmap = this._hasMipmap; opts.format = 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.loaded = true; this.emit("load"); cc.macro.CLEANUP_IMAGE_CACHE && this._image instanceof HTMLImageElement && this._clearImage(); }, description: function() { return ""; }, releaseTexture: function() { this._image = null; this._texture && this._texture.destroy(); }, setWrapMode: function(wrapS, wrapT) { if (this._wrapS !== wrapS || this._wrapT !== wrapT) { var opts = _getSharedOptions(); opts.wrapS = wrapS; opts.wrapT = wrapT; this.update(opts); } }, setFilters: function(minFilter, magFilter) { if (this._minFilter !== minFilter || this._magFilter !== magFilter) { var opts = _getSharedOptions(); opts.minFilter = minFilter; opts.magFilter = magFilter; this.update(opts); } }, setFlipY: function(flipY) { if (this._flipY !== flipY) { var opts = _getSharedOptions(); opts.flipY = flipY; this.update(opts); } }, setPremultiplyAlpha: function(premultiply) { if (this._premultiplyAlpha !== premultiply) { var opts = _getSharedOptions(); opts.premultiplyAlpha = premultiply; this.update(opts); } }, setMipmap: function(mipmap) { if (this._hasMipmap !== mipmap) { var opts = _getSharedOptions(); opts.hasMipmap = mipmap; this.update(opts); } }, _serialize: (false, false) && function() { var extId = ""; if (this._native) { var ext = cc.path.extname(this._native); if (ext) { extId = Texture2D.extnames.indexOf(ext); extId < 0 && (extId = ext); } } var asset = extId + "," + this._minFilter + "," + this._magFilter + "," + this._wrapS + "," + this._wrapT + "," + (this._premultiplyAlpha ? 1 : 0); return asset; }, _deserialize: function(data, handle) { var fields = data.split(","); var extIdStr = fields[0]; if (extIdStr) { var extId = extIdStr.charCodeAt(0) - CHAR_CODE_0; var ext = Texture2D.extnames[extId]; this._setRawAsset(ext || extIdStr); var loadingItem = handle.customEnv; var uuid = loadingItem && loadingItem.uuid; if (uuid) { this._uuid = uuid; var url = this.nativeUrl; this.url = url; } } if (6 === 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; } }, _getHash: function() { if (!this._hashDirty) return this._hash; var hasMipmap = this._hasMipmap ? 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; this._hash = parseInt("" + minFilter + magFilter + pixelFormat + wrapS + wrapT + hasMipmap + premultiplyAlpha + flipY); this._hashDirty = false; return this._hash; }, _clearImage: function() { this._image.src = ""; cc.loader.removeItem(this._image.id); } }); cc.Texture2D = module.exports = Texture2D; }), { "../assets/CCAsset": 34, "../event/event-target": 103, "../platform/CCClass": 161, "../platform/id-generater": 177, "../renderer": 202, "../renderer/render-engine": 203 } ], 51: [ (function(require, module, exports) { require("./CCRawAsset"); require("./CCAsset"); require("./CCFont"); require("./CCPrefab"); require("./CCAudioClip"); require("./CCScripts"); require("./CCSceneAsset"); require("./CCSpriteFrame"); require("./CCTexture2D"); require("./CCRenderTexture"); require("./CCTTFFont"); require("./CCSpriteAtlas"); require("./CCBitmapFont"); require("./CCLabelAtlas"); require("./CCTextAsset"); require("./CCJsonAsset"); require("./CCBufferAsset"); }), { "./CCAsset": 34, "./CCAudioClip": 35, "./CCBitmapFont": 36, "./CCBufferAsset": 37, "./CCFont": 38, "./CCJsonAsset": 39, "./CCLabelAtlas": 40, "./CCPrefab": 41, "./CCRawAsset": 42, "./CCRenderTexture": 43, "./CCSceneAsset": 44, "./CCScripts": 45, "./CCSpriteAtlas": 46, "./CCSpriteFrame": 47, "./CCTTFFont": 48, "./CCTextAsset": 49, "./CCTexture2D": 50 } ], 52: [ (function(require, module, exports) { var 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._scale.x; var scaleY = widgetNode._parent._scale.y; var translateX = 0; var translateY = 0; for (var node = widgetNode._parent; ;) { var pos = node._position; translateX += pos.x; translateY += pos.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._scale.x; var sy = node._scale.y; 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._position.x, y = node._position.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._scale.x; 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._scale.y; 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 ? widget.enabled = false : 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(director) { director.on(cc.Director.EVENT_AFTER_UPDATE, refreshScene); false; cc.sys.isMobile ? window.addEventListener("resize", this.onResized.bind(this)) : cc.view.on("canvas-resize", this.onResized, this); }, add: function(widget) { widget.node._widget = widget; this._nodesOrderDirty = true; false; }, remove: function(widget) { widget.node._widget = null; this._activeWidgetsIterator.remove(widget); false; }, onResized: function() { var scene = cc.director.getScene(); scene && this.refreshWidgetOnResized(scene); }, refreshWidgetOnResized: function(node) { var widget = cc.Node.isNode(node) && node.getComponent(cc.Widget); widget && widget.alignMode === AlignMode.ON_WINDOW_RESIZE && (widget.enabled = true); var children = node._children; for (var i = 0; i < children.length; i++) { var child = children[i]; this.refreshWidgetOnResized(child); } }, updateAlignment: updateAlignment, AlignMode: AlignMode }; false; }), { "../CCNode": 30 } ], 53: [ (function(require, module, exports) { var AffineTrans = require("../utils/affine-transform"); var renderEngine = require("../renderer/render-engine"); var renderer = require("../renderer/index"); var RenderFlow = require("../renderer/render-flow"); var game = require("../CCGame"); var mat4 = cc.vmath.mat4; var vec2 = cc.vmath.vec2; var vec3 = cc.vmath.vec3; var _mat4_temp_1 = mat4.create(); var _mat4_temp_2 = mat4.create(); var _vec3_temp_1 = vec3.create(); var _cameras = []; var _debugCamera = null; function repositionDebugCamera() { if (!_debugCamera) return; var node = _debugCamera._node; var visibleRect = cc.visibleRect; node.z = visibleRect.height / 1.1566; node.x = _vec3_temp_1.x = visibleRect.width / 2; node.y = _vec3_temp_1.y = visibleRect.height / 2; _vec3_temp_1.z = 0; node.lookAt(_vec3_temp_1); } var ClearFlags = cc.Enum({ COLOR: 1, DEPTH: 2, STENCIL: 4 }); var Camera = cc.Class({ name: "cc.Camera", extends: cc.Component, ctor: function() { if (game.renderType !== game.RENDER_TYPE_CANVAS) { var camera = new renderEngine.Camera(); camera.setStages([ "transparent" ]); this._fov = 60 * Math.PI / 180; camera.setFov(this._fov); camera.setNear(.1); camera.setFar(4096); var view = new renderEngine.View(); camera.view = view; camera.dirty = true; this._matrixDirty = 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, zoomRatio: { get: function() { return this._zoomRatio; }, set: function(value) { this._zoomRatio = value; this._matrixDirty = true; } }, cullingMask: { get: function() { return this._cullingMask; }, set: function(value) { this._cullingMask = value; this._updateCameraMask(); } }, clearFlags: { get: function() { return this._clearFlags; }, set: function(value) { this._clearFlags = value; this._camera && this._camera.setClearFlags(value); } }, backgroundColor: { get: function() { return this._backgroundColor; }, set: function(value) { this._backgroundColor = value; this._updateBackgroundColor(); } }, depth: { get: function() { return this._depth; }, set: function(value) { this._depth = value; this._camera && this._camera.setDepth(value); } }, targetTexture: { get: function() { return this._targetTexture; }, set: function(value) { this._targetTexture = value; this._updateTargetTexture(); } } }, statics: { main: null, cameras: _cameras, ClearFlags: ClearFlags, findCamera: function(node) { for (var i = 0, l = _cameras.length; i < l; i++) { var camera = _cameras[i]; if (camera.containsNode(node)) return camera; } return null; }, _setupDebugCamera: function() { if (_debugCamera) return; if (game.renderType === game.RENDER_TYPE_CANVAS) return; var camera = new renderEngine.Camera(); _debugCamera = camera; camera.setStages([ "transparent" ]); camera.setFov(60 * Math.PI / 180); camera.setNear(.1); camera.setFar(4096); var view = new renderEngine.View(); camera.view = view; camera.dirty = true; camera._cullingMask = camera.view._cullingMask = 1 << cc.Node.BuiltinGroupIndex.DEBUG; camera.setDepth(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() { if (this._camera) { var mask = this._cullingMask & ~(1 << cc.Node.BuiltinGroupIndex.DEBUG); this._camera._cullingMask = mask; this._camera.view._cullingMask = mask; } }, _updateBackgroundColor: function() { if (this._camera) { var color = this._backgroundColor; this._camera.setColor(color.r / 255, color.g / 255, color.b / 255, color.a / 255); } }, _updateTargetTexture: function() { var texture = this._targetTexture; this._camera && (this._camera._framebuffer = texture ? texture._framebuffer : null); }, _onMatrixDirty: function() { this._matrixDirty = true; }, _init: function() { if (this._inited) return; this._inited = true; if (this._camera) { this._camera.setNode(this.node); this._camera.setClearFlags(this._clearFlags); this._camera.setDepth(this._depth); this._updateBackgroundColor(); this._updateCameraMask(); this._updateTargetTexture(); } }, onLoad: function() { this._init(); }, onEnable: function() { this._matrixDirty = true; if (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); }, onDisable: function() { if (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.remove(_cameras, this); }, getNodeToCameraTransform: function(node) { var out = AffineTrans.identity(); node.getWorldMatrix(_mat4_temp_2); if (this.containsNode(node)) { this.getWorldToCameraMatrix(_mat4_temp_1); mat4.mul(_mat4_temp_2, _mat4_temp_2, _mat4_temp_1); } AffineTrans.fromMat4(out, _mat4_temp_2); return out; }, getCameraToWorldPoint: function(point, out) { out = out || cc.v2(); this.getCameraToWorldMatrix(_mat4_temp_1); vec2.transformMat4(out, point, _mat4_temp_1); return out; }, getWorldToCameraPoint: function(point, out) { out = out || cc.v2(); this.getWorldToCameraMatrix(_mat4_temp_1); vec2.transformMat4(out, point, _mat4_temp_1); return out; }, getCameraToWorldMatrix: function(out) { this.getWorldToCameraMatrix(out); mat4.invert(out, out); return out; }, getWorldToCameraMatrix: function(out) { this.node.getWorldRT(_mat4_temp_1); var zoomRatio = this.zoomRatio; _mat4_temp_1.m00 *= zoomRatio; _mat4_temp_1.m01 *= zoomRatio; _mat4_temp_1.m04 *= zoomRatio; _mat4_temp_1.m05 *= zoomRatio; var m12 = _mat4_temp_1.m12; var m13 = _mat4_temp_1.m13; var center = cc.visibleRect.center; _mat4_temp_1.m12 = center.x - (_mat4_temp_1.m00 * m12 + _mat4_temp_1.m04 * m13); _mat4_temp_1.m13 = center.y - (_mat4_temp_1.m01 * m12 + _mat4_temp_1.m05 * m13); out !== _mat4_temp_1 && mat4.copy(out, _mat4_temp_1); return out; }, containsNode: function(node) { return node._cullingMask & this.cullingMask; }, render: function(root) { root = root || cc.director.getScene(); if (!root) return null; this.node.getWorldMatrix(_mat4_temp_1); this.beforeDraw(); RenderFlow.visit(root); renderer._forward.renderCamera(this._camera, renderer.scene); }, beforeDraw: function() { var node = this.node; if (!this._matrixDirty && !node._worldMatDirty) return; var camera = this._camera; var fov = 2 * Math.atan(Math.tan(this._fov / 2) / this.zoomRatio); camera.setFov(fov); var height = cc.game.canvas.height / cc.view._scaleY; var targetTexture = this._targetTexture; targetTexture && (height = targetTexture.height); node._updateWorldMatrix(); _vec3_temp_1.x = node._worldMatrix.m12; _vec3_temp_1.y = node._worldMatrix.m13; _vec3_temp_1.z = 0; node.z = height / (2 * Math.tan(this._fov / 2)); node.lookAt(_vec3_temp_1); this._matrixDirty = false; camera.dirty = true; } }); module.exports = cc.Camera = Camera; }), { "../CCGame": 29, "../renderer/index": 202, "../renderer/render-engine": 203, "../renderer/render-flow": 204, "../utils/affine-transform": 235 } ], 54: [ (function(require, module, exports) { cc.Collider.Box = cc.Class({ properties: { _offset: cc.v2(0, 0), _size: cc.size(100, 100), offset: { tooltip: false, get: function() { return this._offset; }, set: function(value) { this._offset = value; }, type: cc.Vec2 }, size: { tooltip: false, get: function() { return this._size; }, set: function(value) { this._size.width = value.width < 0 ? 0 : value.width; this._size.height = value.height < 0 ? 0 : value.height; }, type: cc.Size } }, resetInEditor: false }); var BoxCollider = cc.Class({ name: "cc.BoxCollider", extends: cc.Collider, mixins: [ cc.Collider.Box ], editor: false }); cc.BoxCollider = module.exports = BoxCollider; }), {} ], 55: [ (function(require, module, exports) { cc.Collider.Circle = cc.Class({ properties: { _offset: cc.v2(0, 0), _radius: 50, offset: { get: function() { return this._offset; }, set: function(value) { this._offset = value; }, type: cc.Vec2 }, radius: { tooltip: false, get: function() { return this._radius; }, set: function(value) { this._radius = value < 0 ? 0 : value; } } }, resetInEditor: false }); var CircleCollider = cc.Class({ name: "cc.CircleCollider", extends: cc.Collider, mixins: [ cc.Collider.Circle ], editor: false }); cc.CircleCollider = module.exports = CircleCollider; }), {} ], 56: [ (function(require, module, exports) { var Collider = cc.Class({ name: "cc.Collider", extends: cc.Component, properties: { editing: { default: false, serializable: false, tooltip: false }, tag: { tooltip: false, default: 0, range: [ 0, 1e7 ], type: cc.Integer } }, onDisable: function() { cc.director.getCollisionManager().removeCollider(this); }, onEnable: function() { cc.director.getCollisionManager().addCollider(this); } }); cc.Collider = module.exports = Collider; }), {} ], 57: [ (function(require, module, exports) { var Contact = require("./CCContact"); var CollisionType = Contact.CollisionType; var NodeEvent = require("../CCNode").EventType; var math = cc.vmath; var _vec2 = cc.v2(); function obbApplyMatrix(rect, mat4, out_bl, out_tl, out_tr, out_br) { var x = rect.x; var y = rect.y; var width = rect.width; var height = rect.height; var m00 = mat4.m00, m01 = mat4.m01, m04 = mat4.m04, m05 = mat4.m05; var m12 = mat4.m12, m13 = mat4.m13; var tx = m00 * x + m04 * y + m12; var ty = m01 * x + m05 * y + m13; var xa = m00 * width; var xb = m01 * width; var yc = m04 * height; var yd = m05 * 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; } var CollisionManager = cc.Class({ mixins: [ cc.EventTarget ], properties: { enabled: false, enabledDrawBoundingBox: false }, ctor: function() { this._contacts = []; this._colliders = []; this._debugDrawer = null; this._enabledDebugDraw = false; cc.director._scheduler && cc.director._scheduler.enableForTarget(this); }, update: function(dt) { if (!this.enabled) return; var i = void 0, l = void 0; var colliders = this._colliders; for (i = 0, l = colliders.length; i < l; i++) this.updateCollider(colliders[i]); var contacts = this._contacts; var results = []; for (i = 0, l = contacts.length; i < l; i++) { var collisionType = contacts[i].updateState(); if (collisionType === CollisionType.None) continue; results.push([ collisionType, contacts[i] ]); } for (i = 0, l = results.length; i < l; i++) { var result = results[i]; this._doCollide(result[0], result[1]); } this.drawColliders(); }, _doCollide: function(collisionType, contact) { var contactFunc = void 0; switch (collisionType) { case CollisionType.CollisionEnter: contactFunc = "onCollisionEnter"; break; case CollisionType.CollisionStay: contactFunc = "onCollisionStay"; break; case CollisionType.CollisionExit: contactFunc = "onCollisionExit"; } var collider1 = contact.collider1; var collider2 = contact.collider2; var comps1 = collider1.node._components; var comps2 = collider2.node._components; var i = void 0, l = void 0, comp = void 0; for (i = 0, l = comps1.length; i < l; i++) { comp = comps1[i]; comp[contactFunc] && comp[contactFunc](collider2, collider1); } for (i = 0, l = comps2.length; i < l; i++) { comp = comps2[i]; comp[contactFunc] && comp[contactFunc](collider1, collider2); } }, shouldCollide: function(c1, c2) { var node1 = c1.node, node2 = c2.node; var collisionMatrix = cc.game.collisionMatrix; return node1 !== node2 && collisionMatrix[node1.groupIndex][node2.groupIndex]; }, initCollider: function(collider) { if (!collider.world) { var world = collider.world = {}; world.aabb = cc.rect(); world.preAabb = cc.rect(); world.matrix = math.mat4.create(); world.radius = 0; if (collider instanceof cc.BoxCollider) { world.position = null; world.points = [ cc.v2(), cc.v2(), cc.v2(), cc.v2() ]; } else if (collider instanceof cc.PolygonCollider) { world.position = null; world.points = collider.points.map((function(p) { return cc.v2(p.x, p.y); })); } else if (collider instanceof cc.CircleCollider) { world.position = cc.v2(); world.points = null; } } }, updateCollider: function(collider) { var offset = collider.offset; var world = collider.world; var aabb = world.aabb; var m = world.matrix; collider.node.getWorldMatrix(m); var preAabb = world.preAabb; preAabb.x = aabb.x; preAabb.y = aabb.y; preAabb.width = aabb.width; preAabb.height = aabb.height; if (collider instanceof cc.BoxCollider) { var size = collider.size; aabb.x = offset.x - size.width / 2; aabb.y = offset.y - size.height / 2; aabb.width = size.width; aabb.height = size.height; var wps = world.points; var wp0 = wps[0], wp1 = wps[1], wp2 = wps[2], wp3 = wps[3]; obbApplyMatrix(aabb, m, wp0, wp1, wp2, wp3); var minx = Math.min(wp0.x, wp1.x, wp2.x, wp3.x); var miny = Math.min(wp0.y, wp1.y, wp2.y, wp3.y); var maxx = Math.max(wp0.x, wp1.x, wp2.x, wp3.x); var maxy = Math.max(wp0.y, wp1.y, wp2.y, wp3.y); aabb.x = minx; aabb.y = miny; aabb.width = maxx - minx; aabb.height = maxy - miny; } else if (collider instanceof cc.CircleCollider) { math.vec2.transformMat4(_vec2, collider.offset, m); world.position.x = _vec2.x; world.position.y = _vec2.y; var tempx = m.m12, tempy = m.m13; m.m12 = m.m13 = 0; _vec2.x = collider.radius; _vec2.y = 0; math.vec2.transformMat4(_vec2, _vec2, m); var d = Math.sqrt(_vec2.x * _vec2.x + _vec2.y * _vec2.y); world.radius = d; aabb.x = world.position.x - d; aabb.y = world.position.y - d; aabb.width = 2 * d; aabb.height = 2 * d; m.m12 = tempx; m.m13 = tempy; } else if (collider instanceof cc.PolygonCollider) { var points = collider.points; var worldPoints = world.points; worldPoints.length = points.length; var _minx = 1e6, _miny = 1e6, _maxx = -1e6, _maxy = -1e6; for (var i = 0, l = points.length; i < l; i++) { worldPoints[i] || (worldPoints[i] = cc.v2()); _vec2.x = points[i].x + offset.x; _vec2.y = points[i].y + offset.y; math.vec2.transformMat4(_vec2, _vec2, m); var x = _vec2.x; var y = _vec2.y; worldPoints[i].x = x; worldPoints[i].y = y; x > _maxx && (_maxx = x); x < _minx && (_minx = x); y > _maxy && (_maxy = y); y < _miny && (_miny = y); } aabb.x = _minx; aabb.y = _miny; aabb.width = _maxx - _minx; aabb.height = _maxy - _miny; } }, addCollider: function(collider) { var colliders = this._colliders; var index = colliders.indexOf(collider); if (-1 === index) { for (var i = 0, l = colliders.length; i < l; i++) { var other = colliders[i]; if (this.shouldCollide(collider, other)) { var contact = new Contact(collider, other); this._contacts.push(contact); } } colliders.push(collider); this.initCollider(collider); } collider.node.on(NodeEvent.GROUP_CHANGED, this.onNodeGroupChanged, this); }, removeCollider: function(collider) { var colliders = this._colliders; var index = colliders.indexOf(collider); if (index >= 0) { colliders.splice(index, 1); var contacts = this._contacts; for (var i = contacts.length - 1; i >= 0; i--) { var contact = contacts[i]; if (contact.collider1 === collider || contact.collider2 === collider) { contact.touching && this._doCollide(CollisionType.CollisionExit, contact); contacts.splice(i, 1); } } collider.node.off(NodeEvent.GROUP_CHANGED, this.onNodeGroupChanged, this); } else cc.errorID(6600); }, onNodeGroupChanged: function(node) { var colliders = node.getComponents(cc.Collider); for (var i = 0, l = colliders.length; i < l; i++) { this.removeCollider(colliders[i]); this.addCollider(colliders[i]); } }, drawColliders: function() { if (!this._enabledDebugDraw) return; this._checkDebugDrawValid(); var debugDrawer = this._debugDrawer; debugDrawer.clear(); var colliders = this._colliders; for (var i = 0, l = colliders.length; i < l; i++) { var collider = colliders[i]; debugDrawer.strokeColor = cc.Color.WHITE; if (collider instanceof cc.BoxCollider || collider instanceof cc.PolygonCollider) { var ps = collider.world.points; if (ps.length > 0) { debugDrawer.moveTo(ps[0].x, ps[0].y); for (var j = 1; j < ps.length; j++) debugDrawer.lineTo(ps[j].x, ps[j].y); debugDrawer.close(); debugDrawer.stroke(); } } else if (collider instanceof cc.CircleCollider) { debugDrawer.circle(collider.world.position.x, collider.world.position.y, collider.world.radius); debugDrawer.stroke(); } if (this.enabledDrawBoundingBox) { var aabb = collider.world.aabb; debugDrawer.strokeColor = cc.Color.BLUE; debugDrawer.moveTo(aabb.xMin, aabb.yMin); debugDrawer.lineTo(aabb.xMin, aabb.yMax); debugDrawer.lineTo(aabb.xMax, aabb.yMax); debugDrawer.lineTo(aabb.xMax, aabb.yMin); debugDrawer.close(); debugDrawer.stroke(); } } }, _checkDebugDrawValid: function() { if (!this._debugDrawer || !this._debugDrawer.isValid) { var node = new cc.Node("COLLISION_MANAGER_DEBUG_DRAW"); node.zIndex = cc.macro.MAX_ZINDEX; cc.game.addPersistRootNode(node); this._debugDrawer = node.addComponent(cc.Graphics); } } }); cc.js.getset(CollisionManager.prototype, "enabledDebugDraw", (function() { return this._enabledDebugDraw; }), (function(value) { if (value && !this._enabledDebugDraw) { this._checkDebugDrawValid(); this._debugDrawer.node.active = true; } else if (!value && this._enabledDebugDraw) { this._debugDrawer.clear(true); this._debugDrawer.node.active = false; } this._enabledDebugDraw = value; })); cc.CollisionManager = module.exports = CollisionManager; }), { "../CCNode": 30, "./CCContact": 58 } ], 58: [ (function(require, module, exports) { var Intersection = require("./CCIntersection"); var CollisionType = cc.Enum({ None: 0, CollisionEnter: 1, CollisionStay: 2, CollisionExit: 3 }); function Contact(collider1, collider2) { this.collider1 = collider1; this.collider2 = collider2; this.touching = false; var isCollider1Polygon = collider1 instanceof cc.BoxCollider || collider1 instanceof cc.PolygonCollider; var isCollider2Polygon = collider2 instanceof cc.BoxCollider || collider2 instanceof cc.PolygonCollider; var isCollider1Circle = collider1 instanceof cc.CircleCollider; var isCollider2Circle = collider2 instanceof cc.CircleCollider; if (isCollider1Polygon && isCollider2Polygon) this.testFunc = Intersection.polygonPolygon; else if (isCollider1Circle && isCollider2Circle) this.testFunc = Intersection.circleCircle; else if (isCollider1Polygon && isCollider2Circle) this.testFunc = Intersection.polygonCircle; else if (isCollider1Circle && isCollider2Polygon) { this.testFunc = Intersection.polygonCircle; this.collider1 = collider2; this.collider2 = collider1; } else cc.errorID(6601, cc.js.getClassName(collider1), cc.js.getClassName(collider2)); } Contact.prototype.test = function() { var world1 = this.collider1.world; var world2 = this.collider2.world; if (!world1.aabb.intersects(world2.aabb)) return false; if (this.testFunc === Intersection.polygonPolygon) return this.testFunc(world1.points, world2.points); if (this.testFunc === Intersection.circleCircle) return this.testFunc(world1, world2); if (this.testFunc === Intersection.polygonCircle) return this.testFunc(world1.points, world2); return false; }; Contact.prototype.updateState = function() { var result = this.test(); var type = CollisionType.None; if (result && !this.touching) { this.touching = true; type = CollisionType.CollisionEnter; } else if (result && this.touching) type = CollisionType.CollisionStay; else if (!result && this.touching) { this.touching = false; type = CollisionType.CollisionExit; } return type; }; Contact.CollisionType = CollisionType; module.exports = Contact; }), { "./CCIntersection": 59 } ], 59: [ (function(require, module, exports) { var Intersection = {}; function lineLine(a1, a2, b1, b2) { var ua_t = (b2.x - b1.x) * (a1.y - b1.y) - (b2.y - b1.y) * (a1.x - b1.x); var ub_t = (a2.x - a1.x) * (a1.y - b1.y) - (a2.y - a1.y) * (a1.x - b1.x); var u_b = (b2.y - b1.y) * (a2.x - a1.x) - (b2.x - b1.x) * (a2.y - a1.y); if (0 !== u_b) { var ua = ua_t / u_b; var ub = ub_t / u_b; if (0 <= ua && ua <= 1 && 0 <= ub && ub <= 1) return true; } return false; } Intersection.lineLine = lineLine; function lineRect(a1, a2, b) { var r0 = new cc.Vec2(b.x, b.y); var r1 = new cc.Vec2(b.x, b.yMax); var r2 = new cc.Vec2(b.xMax, b.yMax); var r3 = new cc.Vec2(b.xMax, b.y); if (lineLine(a1, a2, r0, r1)) return true; if (lineLine(a1, a2, r1, r2)) return true; if (lineLine(a1, a2, r2, r3)) return true; if (lineLine(a1, a2, r3, r0)) return true; return false; } Intersection.lineRect = lineRect; function linePolygon(a1, a2, b) { var length = b.length; for (var i = 0; i < length; ++i) { var b1 = b[i]; var b2 = b[(i + 1) % length]; if (lineLine(a1, a2, b1, b2)) return true; } return false; } Intersection.linePolygon = linePolygon; function rectRect(a, b) { var a_min_x = a.x; var a_min_y = a.y; var a_max_x = a.x + a.width; var a_max_y = a.y + a.height; var b_min_x = b.x; var b_min_y = b.y; var b_max_x = b.x + b.width; var b_max_y = b.y + b.height; return a_min_x <= b_max_x && a_max_x >= b_min_x && a_min_y <= b_max_y && a_max_y >= b_min_y; } Intersection.rectRect = rectRect; function rectPolygon(a, b) { var i, l; var r0 = new cc.Vec2(a.x, a.y); var r1 = new cc.Vec2(a.x, a.yMax); var r2 = new cc.Vec2(a.xMax, a.yMax); var r3 = new cc.Vec2(a.xMax, a.y); if (linePolygon(r0, r1, b)) return true; if (linePolygon(r1, r2, b)) return true; if (linePolygon(r2, r3, b)) return true; if (linePolygon(r3, r0, b)) return true; for (i = 0, l = b.length; i < l; ++i) if (pointInPolygon(b[i], a)) return true; if (pointInPolygon(r0, b)) return true; if (pointInPolygon(r1, b)) return true; if (pointInPolygon(r2, b)) return true; if (pointInPolygon(r3, b)) return true; return false; } Intersection.rectPolygon = rectPolygon; function polygonPolygon(a, b) { var i, l; for (i = 0, l = a.length; i < l; ++i) { var a1 = a[i]; var a2 = a[(i + 1) % l]; if (linePolygon(a1, a2, b)) return true; } for (i = 0, l = b.length; i < l; ++i) if (pointInPolygon(b[i], a)) return true; for (i = 0, l = a.length; i < l; ++i) if (pointInPolygon(a[i], b)) return true; return false; } Intersection.polygonPolygon = polygonPolygon; function circleCircle(a, b) { var distance = a.position.sub(b.position).mag(); return distance < a.radius + b.radius; } Intersection.circleCircle = circleCircle; function polygonCircle(polygon, circle) { var position = circle.position; if (pointInPolygon(position, polygon)) return true; for (var i = 0, l = polygon.length; i < l; i++) { var start = 0 === i ? polygon[polygon.length - 1] : polygon[i - 1]; var end = polygon[i]; if (pointLineDistance(position, start, end, true) < circle.radius) return true; } return false; } Intersection.polygonCircle = polygonCircle; function pointInPolygon(point, polygon) { var inside = false; var x = point.x; var y = point.y; var length = polygon.length; for (var i = 0, j = length - 1; i < length; j = i++) { var xi = polygon[i].x, yi = polygon[i].y, xj = polygon[j].x, yj = polygon[j].y, intersect = yi > y !== yj > y && x < (xj - xi) * (y - yi) / (yj - yi) + xi; intersect && (inside = !inside); } return inside; } Intersection.pointInPolygon = pointInPolygon; function pointLineDistance(point, start, end, isSegment) { var dx = end.x - start.x; var dy = end.y - start.y; var d = dx * dx + dy * dy; var t = ((point.x - start.x) * dx + (point.y - start.y) * dy) / d; var p; p = isSegment ? d ? t < 0 ? start : t > 1 ? end : cc.v2(start.x + t * dx, start.y + t * dy) : start : cc.v2(start.x + t * dx, start.y + t * dy); dx = point.x - p.x; dy = point.y - p.y; return Math.sqrt(dx * dx + dy * dy); } Intersection.pointLineDistance = pointLineDistance; cc.Intersection = module.exports = Intersection; }), {} ], 60: [ (function(require, module, exports) { cc.Collider.Polygon = cc.Class({ properties: { threshold: { default: 1, serializable: false, visible: false }, _offset: cc.v2(0, 0), offset: { get: function() { return this._offset; }, set: function(value) { this._offset = value; }, type: cc.Vec2 }, points: { tooltip: false, default: function() { return [ cc.v2(-50, -50), cc.v2(50, -50), cc.v2(50, 50), cc.v2(-50, 50) ]; }, type: [ cc.Vec2 ] } }, resetPointsByContour: false }); var PolygonCollider = cc.Class({ name: "cc.PolygonCollider", extends: cc.Collider, mixins: [ cc.Collider.Polygon ], editor: false }); cc.PolygonCollider = module.exports = PolygonCollider; }), {} ], 61: [ (function(require, module, exports) { require("./CCCollisionManager"); require("./CCCollider"); require("./CCBoxCollider"); require("./CCCircleCollider"); require("./CCPolygonCollider"); }), { "./CCBoxCollider": 54, "./CCCircleCollider": 55, "./CCCollider": 56, "./CCCollisionManager": 57, "./CCPolygonCollider": 60 } ], 62: [ (function(require, module, exports) { 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 callStartInTryCatch = false; var callUpdateInTryCatch = false; var callLateUpdateInTryCatch = false; var callOnDisableInTryCatch = false; var callStart = "c.start();c._objFlags|=" + IsStartCalled; var callUpdate = "c.update(dt)"; var callLateUpdate = "c.lateUpdate(dt)"; 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._activeInHierarchy) ++next; else { iterator.removeAt(next); flagToClear && (comp._objFlags &= ~flagToClear); } } } var LifeCycleInvoker = cc.Class({ __ctor__: function(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(comp) { var order = comp.constructor._executionOrder; (0 === order ? this._zero : order < 0 ? this._neg : this._pos).array.push(comp); }, remove: function(comp) { var order = comp.constructor._executionOrder; (0 === order ? this._zero : order < 0 ? this._neg : this._pos).fastRemove(comp); }, cancelInactive: function(flagToClear) { stableRemoveInactive(this._zero, flagToClear); stableRemoveInactive(this._neg, flagToClear); stableRemoveInactive(this._pos, flagToClear); }, invoke: function() { 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(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(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(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(funcOrCode, useDt) { if ("function" === (__typeofVal = typeof funcOrCode, "object" === __typeofVal ? __realTypeOfObj(funcOrCode) : __typeofVal)) return useDt ? function(iterator, dt) { var array = iterator.array; for (iterator.i = 0; iterator.i < array.length; ++iterator.i) { var comp = array[iterator.i]; funcOrCode(comp, dt); } } : function(iterator) { var array = iterator.array; for (iterator.i = 0; iterator.i < array.length; ++iterator.i) { var comp = array[iterator.i]; funcOrCode(comp); } }; var body = "var a=it.array;for(it.i=0;it.i= 0) { jsArray.fastRemoveAt(this.scheduleInNextFrame, 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(comp) { !comp.start || comp._objFlags & IsStartCalled || this.startInvoker.add(comp); comp.update && this.updateInvoker.add(comp); comp.lateUpdate && this.lateUpdateInvoker.add(comp); }, _deferredSchedule: function() { var comps = this.scheduleInNextFrame; for (var i = 0, len = comps.length; i < len; i++) { var comp = comps[i]; this._scheduleImmediate(comp); } comps.length = 0; }, startPhase: function() { this._updating = true; this.scheduleInNextFrame.length > 0 && this._deferredSchedule(); this.startInvoker.invoke(); }, updatePhase: function(dt) { this.updateInvoker.invoke(dt); }, lateUpdatePhase: function(dt) { this.lateUpdateInvoker.invoke(dt); this._updating = false; } }); module.exports = ComponentScheduler; }), { "./platform/CCClass": 161, "./platform/CCObject": 167, "./platform/js": 181, "./utils/misc": 243 } ], 63: [ (function(require, module, exports) { var AnimationAnimator = require("../../animation/animation-animator"); var AnimationClip = require("../../animation/animation-clip"); var EventTarget = require("../event/event-target"); var js = require("../platform/js"); function equalClips(clip1, clip2) { if (clip1 === clip2) return true; return clip1 && clip2 && (clip1.name === clip2.name || clip1._uuid === clip2._uuid); } 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() { 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() { return this._defaultClip; }, set: function(value) { true; return; var clips; var i, l; }, tooltip: false }, currentClip: { get: function() { return this._currentClip; }, set: function(value) { this._currentClip = value; }, type: AnimationClip, visible: false }, _clips: { default: [], type: [ AnimationClip ], tooltip: false, visible: true }, playOnLoad: { default: false, tooltip: false } }, start: function() { 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() { this._animator && this._animator.resume(); }, onDisable: function() { this._animator && this._animator.pause(); }, onDestroy: function() { this.stop(); }, getClips: function() { return this._clips; }, play: function(name, startTime) { var state = this.playAdditive(name, startTime); this._animator.stopStatesExcept(state); return state; }, playAdditive: function(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(name) { if (!this._didInit) return; if (name) { var state = this._nameToState[name]; state && this._animator.stopState(state); } else this._animator.stop(); }, pause: function(name) { if (!this._didInit) return; if (name) { var state = this._nameToState[name]; state && this._animator.pauseState(state); } else this.enabled = false; }, resume: function(name) { if (!this._didInit) return; if (name) { var state = this._nameToState[name]; state && this._animator.resumeState(state); } else this.enabled = true; }, setCurrentTime: function(time, name) { this._init(); if (name) { var state = this._nameToState[name]; state && this._animator.setStateTime(state, time); } else this._animator.setStateTime(time); }, getAnimationState: function(name) { this._init(); var state = this._nameToState[name]; false; state && !state.curveLoaded && this._animator._reloadClip(state); return state || null; }, addClip: function(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(clip, force) { if (!clip) { cc.warnID(3901); return; } this._init(); var state = void 0; for (var name in this._nameToState) { state = this._nameToState[name]; var stateClip = state.clip; if (stateClip === 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 item !== clip; })); state && delete this._nameToState[state.name]; }, sample: function(name) { this._init(); if (name) { var state = this._nameToState[name]; state && state.sample(); } else this._animator.sample(); }, on: function(type, callback, target, useCapture) { this._init(); var ret = this._EventTargetOn(type, callback, target, useCapture); if ("lastframe" === type) { var array = this._animator._anims.array; for (var i = 0; i < array.length; ++i) { var state = array[i]; state._lastframeEventOn = true; } } return ret; }, off: function(type, callback, target, useCapture) { this._init(); if ("lastframe" === type) { var nameToState = this._nameToState; for (var name in nameToState) { var state = nameToState[name]; state._lastframeEventOn = false; } } this._EventTargetOff(type, callback, target, useCapture); }, _init: function() { if (this._didInit) return; this._didInit = true; this._animator = new AnimationAnimator(this.node, this); this._createStates(); }, _createStates: function() { 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": 103, "../platform/js": 181, "./CCComponent": 68 } ], 64: [ (function(require, module, exports) { var misc = require("../utils/misc"); var Component = require("./CCComponent"); var AudioClip = require("../assets/CCAudioClip"); var AudioSource = cc.Class({ name: "cc.AudioSource", extends: Component, editor: false, ctor: function() { this.audio = new cc.Audio(); }, properties: { _clip: { default: null, type: AudioClip }, _volume: 1, _mute: false, _loop: false, _pausedFlag: { default: false, serializable: false }, isPlaying: { get: function() { var state = this.audio.getState(); return state === cc.Audio.State.PLAYING; }, visible: false }, clip: { get: function() { return this._clip; }, set: function(value) { var _this = this; if ("string" === (__typeofVal = typeof value, "object" === __typeofVal ? __realTypeOfObj(value) : __typeofVal)) { var _ret = (function() { cc.warnID(8401, "cc.AudioSource", "cc.AudioClip", "AudioClip", "cc.AudioClip", "audio"); var self = _this; AudioClip._loadByUrl(value, (function(err, clip) { clip && (self.clip = clip); })); return { v: void 0 }; })(); if ("object" === (__typeofVal = typeof _ret, "object" === __typeofVal ? __realTypeOfObj(_ret) : __typeofVal)) return _ret.v; } if (value === this._clip) return; this._clip = value; this.audio.stop(); this.preload && (this.audio.src = this._clip); }, type: AudioClip, tooltip: false, animatable: false }, volume: { get: function() { return this._volume; }, set: function(value) { value = misc.clamp01(value); this._volume = value; this._mute || this.audio.setVolume(value); return value; }, tooltip: false }, mute: { get: function() { return this._mute; }, set: function(value) { this._mute = value; this.audio.setVolume(value ? 0 : this._volume); return value; }, animatable: false, tooltip: false }, loop: { get: function() { return this._loop; }, set: function(value) { this._loop = value; this.audio.setLoop(value); return value; }, animatable: false, tooltip: false }, playOnLoad: { default: false, tooltip: false, animatable: false }, preload: { default: false, animatable: false } }, _ensureDataLoaded: function() { this.audio.src !== this._clip && (this.audio.src = this._clip); }, _pausedCallback: function() { var state = this.audio.getState(); if (state === cc.Audio.State.PLAYING) { this.audio.pause(); this._pausedFlag = true; } }, _restoreCallback: function() { this._pausedFlag && this.audio.resume(); this._pausedFlag = false; }, onLoad: function() { this.audio.setVolume(this._mute ? 0 : this._volume); this.audio.setLoop(this._loop); }, onEnable: function() { this.preload && (this.audio.src = this._clip); this.playOnLoad && this.play(); cc.game.on(cc.game.EVENT_HIDE, this._pausedCallback, this); cc.game.on(cc.game.EVENT_SHOW, this._restoreCallback, this); }, onDisable: function() { this.stop(); cc.game.off(cc.game.EVENT_HIDE, this._pausedCallback, this); cc.game.off(cc.game.EVENT_SHOW, this._restoreCallback, this); }, onDestroy: function() { this.stop(); this.audio.destroy(); cc.audioEngine.uncache(this._clip); }, play: function() { if (!this._clip) return; var audio = this.audio; this._clip.loaded && audio.stop(); this._ensureDataLoaded(); audio.setCurrentTime(0); audio.play(); }, stop: function() { this.audio.stop(); }, pause: function() { this.audio.pause(); }, resume: function() { this._ensureDataLoaded(); this.audio.resume(); }, rewind: function() { this.audio.setCurrentTime(0); }, getCurrentTime: function() { return this.audio.getCurrentTime(); }, setCurrentTime: function(time) { this.audio.setCurrentTime(time); return time; }, getDuration: function() { return this.audio.getDuration(); } }); cc.AudioSource = module.exports = AudioSource; }), { "../assets/CCAudioClip": 35, "../utils/misc": 243, "./CCComponent": 68 } ], 65: [ (function(require, module, exports) { 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() { for (var i = 0; i < BlockEvents.length; i++) this.node.on(BlockEvents[i], stopPropagation, this); }, onDisable: function() { for (var i = 0; i < BlockEvents.length; i++) this.node.off(BlockEvents[i], stopPropagation, this); } }); cc.BlockInputEvents = module.exports = BlockInputEvents; }), { "./CCComponent": 68 } ], 66: [ (function(require, module, exports) { var Component = require("./CCComponent"); 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, ctor: function() { 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._sprite = null; }, editor: false, properties: { interactable: { default: true, tooltip: false, notify: function() { this._updateState(); this.interactable || this._resetState(); }, animatable: false }, _resizeToTarget: { animatable: false, set: function(value) { value && this._resizeNodeToTargetNode(); } }, enableAutoGrayEffect: { default: false, tooltip: false, notify: function() { this._updateDisabledState(); } }, transition: { default: Transition.NONE, tooltip: false, type: Transition, animatable: false, notify: function(oldValue) { this._updateTransition(oldValue); }, formerlySerializedAs: "transition" }, normalColor: { default: cc.color(214, 214, 214), displayName: "Normal", tooltip: false, notify: function() { 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() { 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() { 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() { 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() { this._updateState(); } }, pressedSprite: { default: null, type: cc.SpriteFrame, displayName: "Pressed", tooltip: false, formerlySerializedAs: "pressedSprite", notify: function() { this._updateState(); } }, hoverSprite: { default: null, type: cc.SpriteFrame, displayName: "Hover", tooltip: false, formerlySerializedAs: "hoverSprite", notify: function() { this._updateState(); } }, disabledSprite: { default: null, type: cc.SpriteFrame, displayName: "Disabled", tooltip: false, notify: function() { this._updateState(); } }, target: { default: null, type: cc.Node, tooltip: false, notify: function(oldValue) { this._applyTarget(); this.target !== oldValue && this._unregisterTargetEvent(oldValue); } }, clickEvents: { default: [], type: cc.Component.EventHandler, tooltip: false } }, statics: { Transition: Transition }, __preload: function() { this._applyTarget(); this._updateState(); }, _resetState: function() { 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() { this.normalSprite && this.normalSprite.ensureLoadTexture(); this.hoverSprite && this.hoverSprite.ensureLoadTexture(); this.pressedSprite && this.pressedSprite.ensureLoadTexture(); this.disabledSprite && this.disabledSprite.ensureLoadTexture(); true; this._registerNodeEvent(); }, onDisable: function() { this._resetState(); true; this._unregisterNodeEvent(); }, _getTarget: function() { return this.target ? this.target : this.node; }, _onTargetSpriteFrameChanged: function(comp) { this.transition === Transition.SPRITE && this._setCurrentStateSprite(comp.spriteFrame); }, _onTargetColorChanged: function(color) { this.transition === Transition.COLOR && this._setCurrentStateColor(color); }, _onTargetScaleChanged: function() { 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(color) { var target = this._getTarget(); target.color = color; target.opacity = color.a; }, _getStateColor: function(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(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(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(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(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() { 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() { 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(target) { false; target.on(cc.Node.EventType.SCALE_CHANGED, this._onTargetScaleChanged, this); }, _unregisterTargetEvent: function(target) { if (!target) return; false; target.off(cc.Node.EventType.SCALE_CHANGED, this._onTargetScaleChanged, this); }, _getTargetSprite: function(target) { var sprite = null; target && (sprite = target.getComponent(cc.Sprite)); return sprite; }, _applyTarget: function() { 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(event) { if (!this.interactable || !this.enabledInHierarchy) return; this._pressed = true; this._updateState(); event.stopPropagation(); }, _onTouchMove: function(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 = void 0; state = hit ? State.PRESSED : State.NORMAL; this._applyTransition(state); } event.stopPropagation(); }, _onTouchEnded: function(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() { if (!this.interactable || !this.enabledInHierarchy) return; this._pressed = false; this._updateState(); }, _onMouseMoveIn: function() { 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() { if (this._hovered) { this._hovered = false; this._updateState(); } }, _updateState: function() { var state = this._getButtonState(); this._applyTransition(state); this._updateDisabledState(); }, _getButtonState: function() { var state = void 0; state = this.interactable ? this._pressed ? State.PRESSED : this._hovered ? State.HOVER : State.NORMAL : State.DISABLED; return state; }, _updateColorTransitionImmediately: function(state) { var color = this._getStateColor(state); this._setTargetColor(color); }, _updateColorTransition: function(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(state) { var sprite = this._getStateSprite(state); this._sprite && sprite && (this._sprite.spriteFrame = sprite); }, _updateScaleTransition: function(state) { state === State.PRESSED ? this._zoomUp() : this._zoomBack(); }, _zoomUp: function() { 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() { 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(oldTransition) { oldTransition === Transition.COLOR ? this._updateColorTransitionImmediately(State.NORMAL) : oldTransition === Transition.SPRITE && this._updateSpriteTransition(State.NORMAL); this._updateState(); }, _applyTransition: function(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() { if (this._sprite) { if (this.enableAutoGrayEffect && !(this.transition === Transition.SPRITE && this.disabledSprite) && !this.interactable) { this._sprite.setState(cc.Sprite.State.GRAY); return; } this._sprite.setState(cc.Sprite.State.NORMAL); } } }); cc.Button = module.exports = Button; }), { "./CCComponent": 68 } ], 67: [ (function(require, module, exports) { var Camera = require("../camera/CCCamera"); var Component = require("./CCComponent"); 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() { return cc.size(this._designResolution); }, set: function(value) { this._designResolution.width = value.width; this._designResolution.height = value.height; this.applySettings(); this.alignWithScreen(); }, tooltip: false }, _fitWidth: false, _fitHeight: true, fitHeight: { get: function() { return this._fitHeight; }, set: function(value) { if (this._fitHeight !== value) { this._fitHeight = value; this.applySettings(); this.alignWithScreen(); } }, tooltip: false }, fitWidth: { get: function() { return this._fitWidth; }, set: function(value) { if (this._fitWidth !== value) { this._fitWidth = value; this.applySettings(); this.alignWithScreen(); } }, tooltip: false } }, ctor: function() { this._thisOnResized = this.alignWithScreen.bind(this); }, __preload: function() { var Flags; false; if (Canvas.instance) return cc.errorID(6700, this.node.name, Canvas.instance.node.name); Canvas.instance = this; false; cc.sys.isMobile ? window.addEventListener("resize", this._thisOnResized) : cc.view.on("canvas-resize", this._thisOnResized); this.applySettings(); this.alignWithScreen(); var cameraNode = cc.find("Main Camera", this.node); if (!cameraNode) { cameraNode = new cc.Node("Main Camera"); cameraNode.parent = this.node; cameraNode.setSiblingIndex(0); } var camera = cameraNode.getComponent(Camera); if (!camera) { camera = cameraNode.addComponent(Camera); var ClearFlags = Camera.ClearFlags; camera.clearFlags = ClearFlags.COLOR | ClearFlags.DEPTH | ClearFlags.STENCIL; camera.depth = -1; } Camera.main = camera; }, onDestroy: function() { false; cc.sys.isMobile ? window.removeEventListener("resize", this._thisOnResized) : cc.view.off("canvas-resize", this._thisOnResized); Canvas.instance === this && (Canvas.instance = null); }, alignWithScreen: function() { var designSize, nodeSize; false; var canvasSize = nodeSize = cc.visibleRect; designSize = cc.view.getDesignResolutionSize(); var clipTopRight = !this.fitHeight && !this.fitWidth; var offsetX = 0; var offsetY = 0; if (clipTopRight) { offsetX = .5 * (designSize.width - canvasSize.width); offsetY = .5 * (designSize.height - canvasSize.height); } this.node.setPosition(.5 * canvasSize.width + offsetX, .5 * canvasSize.height + offsetY); this.node.width = nodeSize.width; this.node.height = nodeSize.height; }, applySettings: function() { 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": 53, "./CCComponent": 68 } ], 68: [ (function(require, module, exports) { 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 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() { 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(value) { this._name = value; }, visible: false }, uuid: { get: function() { return this._id; }, visible: false }, __scriptAsset: false, _enabled: true, enabled: { get: function() { return this._enabled; }, set: function(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() { return this._enabled && this.node._activeInHierarchy; }, visible: false }, _isOnLoadCalled: { get: function() { 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(typeOrClassName) { return this.node.addComponent(typeOrClassName); }, getComponent: function(typeOrClassName) { return this.node.getComponent(typeOrClassName); }, getComponents: function(typeOrClassName) { return this.node.getComponents(typeOrClassName); }, getComponentInChildren: function(typeOrClassName) { return this.node.getComponentInChildren(typeOrClassName); }, getComponentsInChildren: function(typeOrClassName) { return this.node.getComponentsInChildren(typeOrClassName); }, _getLocalBounds: null, onRestore: null, destroy: function() { var depend; false; this._super() && this._enabled && this.node._activeInHierarchy && cc.director._compScheduler.disableComp(this); }, _onPreDestroy: function() { this.unscheduleAllCallbacks(); var eventTargets = this.__eventTargets; for (var i = 0, l = eventTargets.length; i < l; ++i) { var target = eventTargets[i]; target && target.targetOff(this); } eventTargets.length = 0; false; cc.director._nodeActivator.destroyComp(this); this.node._removeComponent(this); }, _instantiate: function(cloned) { cloned || (cloned = cc.instantiate._clone(this, this)); cloned.node = null; return cloned; }, schedule: function(callback, interval, repeat, delay) { cc.assertID(callback, 1619); cc.assertID(interval >= 0, 1620); interval = interval || 0; 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(callback, delay) { this.schedule(callback, 0, 0, delay); }, unschedule: function(callback_fn) { if (!callback_fn) return; cc.director.getScheduler().unschedule(callback_fn, this); }, unscheduleAllCallbacks: function() { cc.director.getScheduler().unscheduleAllForTarget(this); } }); Component._requireComponent = null; Component._executionOrder = 0; false, false; js.value(Component, "_registerEditorProps", (function(cls, props) { var reqComp = props.requireComponent; reqComp && (cls._requireComponent = reqComp); var order = props.executionOrder; order && "number" === (__typeofVal = typeof order, "object" === __typeofVal ? __realTypeOfObj(order) : __typeofVal) && (cls._executionOrder = order); var name; var key; var val; var willExecuteInEditMode; false, false; })); Component.prototype.__scriptUuid = ""; cc.Component = module.exports = Component; }), { "../platform/CCObject": 167, "../platform/id-generater": 177, "../platform/js": 181 } ], 69: [ (function(require, module, exports) { cc.Component.EventHandler = cc.Class({ name: "cc.ClickEvent", properties: { target: { default: null, type: cc.Node }, component: "", _componentId: "", _componentName: { get: function() { this._genCompIdIfNeeded(); return this._compId2Name(this._componentId); }, set: function(value) { this._componentId = this._compName2Id(value); } }, handler: { default: "" }, customEventData: { default: "" } }, statics: { emitEvents: function(events) { "use strict"; var args = void 0; 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(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" !== (__typeofVal = typeof handler, "object" === __typeofVal ? __realTypeOfObj(handler) : __typeofVal)) return; if (null != this.customEventData && "" !== this.customEventData) { params = params.slice(); params.push(this.customEventData); } handler.apply(comp, params); }, _compName2Id: function(compName) { var comp = cc.js.getClassByName(compName); return cc.js._getClassId(comp); }, _compId2Name: function(compId) { var comp = cc.js._getClassById(compId); return cc.js.getClassName(comp); }, _genCompIdIfNeeded: function() { if (!this._componentId) { this._componentName = this.component; this.component = ""; } } }); }), {} ], 70: [ (function(require, module, exports) { var macro = require("../platform/CCMacro"); var RenderComponent = require("./CCRenderComponent"); var renderEngine = require("../renderer/render-engine"); var RenderFlow = require("../renderer/render-flow"); var SpriteMaterial = renderEngine.SpriteMaterial; var dynamicAtlasManager = require("../renderer/utils/dynamic-atlas/manager"); var LabelFrame = require("../renderer/utils/label/label-frame"); 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 Label = cc.Class({ name: "cc.Label", extends: RenderComponent, ctor: function() { false; this._actualFontSize = 0; this._assemblerData = null; this._frame = null; this._ttfTexture = null; this._letterTexture = null; }, editor: false, properties: { _useOriginalSize: true, _string: { default: "", formerlySerializedAs: "_N$string" }, string: { get: function() { return this._string; }, set: function(value) { var oldValue = this._string; this._string = value.toString(); this.string !== oldValue && this._updateRenderData(); this._checkStringEmpty(); }, multiline: true, tooltip: false }, horizontalAlign: { default: HorizontalAlign.LEFT, type: HorizontalAlign, tooltip: false, notify: function(oldValue) { if (this.horizontalAlign === oldValue) return; this._updateRenderData(); }, animatable: false }, verticalAlign: { default: VerticalAlign.TOP, type: VerticalAlign, tooltip: false, notify: function(oldValue) { this._updateRenderData(); }, animatable: false }, actualFontSize: { displayName: "Actual Font Size", animatable: false, readonly: true, get: function() { return this._actualFontSize; } }, _fontSize: 40, fontSize: { get: function() { return this._fontSize; }, set: function(value) { if (this._fontSize === value) return; this._fontSize = value; this._updateRenderData(); }, range: [ 0, 512 ], tooltip: false }, fontFamily: { default: "Arial", tooltip: false, notify: function(oldValue) { if (this.fontFamily === oldValue) return; this._updateRenderData(); }, animatable: false }, _lineHeight: 40, lineHeight: { get: function() { return this._lineHeight; }, set: function(value) { if (this._lineHeight === value) return; this._lineHeight = value; this._updateRenderData(); }, tooltip: false }, overflow: { default: Overflow.NONE, type: Overflow, tooltip: false, notify: function(oldValue) { if (this.overflow === oldValue) return; this._updateRenderData(); }, animatable: false }, _enableWrapText: true, enableWrapText: { get: function() { return this._enableWrapText; }, set: function(value) { if (this._enableWrapText === value) return; this._enableWrapText = value; this._updateRenderData(); }, animatable: false, tooltip: false }, _N$file: null, font: { get: function() { return this._N$file; }, set: function(value) { if (this.font === value) return; value || (this._isSystemFontUsed = true); false; this._N$file = value; value && this._isSystemFontUsed && (this._isSystemFontUsed = false); "string" === (__typeofVal = typeof value, "object" === __typeofVal ? __realTypeOfObj(value) : __typeofVal) && cc.warnID(4e3); if (this._renderData) { this.destroyRenderData(this._renderData); this._renderData = null; } this._fontAtlas = null; this._updateAssembler(); this._applyFontTexture(true); this._updateRenderData(); }, type: cc.Font, tooltip: false, animatable: false }, _isSystemFontUsed: true, useSystemFont: { get: function() { return this._isSystemFontUsed; }, set: function(value) { if (this._isSystemFontUsed === value) return; this.destroyRenderData(this._renderData); this._renderData = null; false; this._isSystemFontUsed = !!value; if (value) { this.font = null; this._updateAssembler(); this._updateRenderData(); this._checkStringEmpty(); } else this._userDefinedFont || this.disableRender(); }, animatable: false, tooltip: false }, _bmFontOriginalSize: { displayName: "BMFont Original Size", get: function() { return this._N$file instanceof cc.BitmapFont ? this._N$file.fontSize : -1; }, visible: true, animatable: false }, _spacingX: 0, spacingX: { get: function() { return this._spacingX; }, set: function(value) { this._spacingX = value; this._updateRenderData(); } }, _batchAsBitmap: false, cacheMode: { default: CacheMode.NONE, type: CacheMode, tooltip: false, notify: function(oldValue) { if (this.cacheMode === oldValue) return; oldValue !== CacheMode.BITMAP || this.font instanceof cc.BitmapFont || this._frame._resetDynamicAtlasFrame(); oldValue === CacheMode.CHAR && (this._ttfTexture = null); this._updateRenderData(true); }, animatable: false }, _isBold: { default: false, serializable: false }, _isItalic: { default: false, serializable: false }, _isUnderline: { default: false, serializable: false } }, statics: { HorizontalAlign: HorizontalAlign, VerticalAlign: VerticalAlign, Overflow: Overflow, CacheMode: CacheMode }, onLoad: function() { if (this._batchAsBitmap && this.cacheMode === CacheMode.NONE) { this.cacheMode = CacheMode.BITMAP; this._batchAsBitmap = false; } }, onEnable: function() { this._super(); this.font || this._isSystemFontUsed || (this.useSystemFont = true); this.useSystemFont && !this.fontFamily && (this.fontFamily = "Arial"); this.node.on(cc.Node.EventType.SIZE_CHANGED, this._updateRenderData, this); this.node.on(cc.Node.EventType.ANCHOR_CHANGED, this._updateRenderData, this); this._checkStringEmpty(); this._updateRenderData(true); }, onDisable: function() { this._super(); this.node.off(cc.Node.EventType.SIZE_CHANGED, this._updateRenderData, this); this.node.off(cc.Node.EventType.ANCHOR_CHANGED, this._updateRenderData, this); }, onDestroy: function() { this._assembler && this._assembler._resetAssemblerData && this._assembler._resetAssemblerData(this._assemblerData); this._assemblerData = null; this._letterTexture = null; if (this._ttfTexture) { this._ttfTexture.destroy(); this._ttfTexture = null; } this._super(); }, _canRender: function() { var result = this._super(); var font = this.font; if (font instanceof cc.BitmapFont) { var spriteFrame = font.spriteFrame; spriteFrame && spriteFrame.textureLoaded() || (result = false); } return result; }, _checkStringEmpty: function() { this.markForRender(!!this.string); }, _updateAssembler: function() { var assembler = Label._assembler.getAssembler(this); if (this._assembler !== assembler) { this._assembler = assembler; this._renderData = null; this._frame = null; } this._renderData || (this._renderData = this._assembler.createData(this)); }, _applyFontTexture: function(force) { var _this = this; var font = this.font; if (font instanceof cc.BitmapFont) (function() { var spriteFrame = font.spriteFrame; _this._frame = spriteFrame; var self = _this; var onBMFontTextureLoaded = function() { self._frame._texture = spriteFrame._texture; self._activateMaterial(force); force && self._assembler && self._assembler.updateRenderData(self); }; if (spriteFrame && spriteFrame.textureLoaded()) onBMFontTextureLoaded(); else { _this.disableRender(); if (spriteFrame) { spriteFrame.once("load", onBMFontTextureLoaded, _this); spriteFrame.ensureLoadTexture(); } } })(); else { this._frame || (this._frame = new LabelFrame()); if (this.cacheMode === CacheMode.CHAR && cc.sys.browserType !== cc.sys.BROWSER_TYPE_WECHAT_GAME_SUB) { 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); } this.cacheMode !== CacheMode.CHAR && this._frame._refreshTexture(this._ttfTexture); this._activateMaterial(force); force && this._assembler && this._assembler.updateRenderData(this); } }, _updateColor: function() { var font = this.font; if (font instanceof cc.BitmapFont) this._super(); else { this._updateRenderData(); this.node._renderFlag &= ~RenderFlow.FLAG_COLOR; } }, _activateMaterial: function(force) { var material = this._material; if (material && !force) return; if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) this._frame._texture.url = this.uuid + "_texture"; else { material || (material = new SpriteMaterial()); material.texture = this._frame._texture; material.useColor = false; this._updateMaterial(material); } this.markForUpdateRenderData(true); this.markForRender(true); }, _updateRenderData: function(force) { var renderData = this._renderData; if (renderData) { renderData.vertDirty = true; renderData.uvDirty = true; this.markForUpdateRenderData(true); } if (true === force) { this._updateAssembler(); this._applyFontTexture(force); } }, _calDynamicAtlas: function() { if (!dynamicAtlasManager) return; if (!this._frame._original) { var frame = dynamicAtlasManager.insertSpriteFrame(this._frame); frame && this._frame._setDynamicAtlasFrame(frame); } this._material._texture !== this._frame._texture && this._activateMaterial(true); }, _enableBold: function(enabled) { this._isBold = !!enabled; }, _enableItalics: function(enabled) { this._isItalic = !!enabled; }, _enableUnderline: function(enabled) { this._isUnderline = !!enabled; } }); cc.Label = module.exports = Label; }), { "../platform/CCMacro": 166, "../renderer/render-engine": 203, "../renderer/render-flow": 204, "../renderer/utils/dynamic-atlas/manager": 206, "../renderer/utils/label/label-frame": 208, "./CCRenderComponent": 78 } ], 71: [ (function(require, module, exports) { var LabelOutline = cc.Class({ name: "cc.LabelOutline", extends: require("./CCComponent"), editor: false, properties: { _color: cc.color(255, 255, 255, 255), _width: 1, color: { get: function() { return this._color; }, set: function(value) { this._color = cc.color(value); this._updateRenderData(); } }, width: { get: function() { return this._width; }, set: function(value) { this._width = value; this._updateRenderData(); } } }, onEnable: function() { this._updateRenderData(); }, onDisable: function() { this._updateRenderData(); }, _updateRenderData: function() { var label = this.node.getComponent(cc.Label); label && label._updateRenderData(true); } }); cc.LabelOutline = module.exports = LabelOutline; }), { "./CCComponent": 68 } ], 72: [ (function(require, module, exports) { 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() { return this._N$layoutType; }, set: function(value) { this._N$layoutType = value; var reLayouted; false; this._doLayoutDirty(); }, tooltip: false, animatable: false }, resizeMode: { type: ResizeMode, tooltip: false, animatable: false, get: function() { return this._resize; }, set: function(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() { this._doLayoutDirty(); } }, startAxis: { default: AxisDirection.HORIZONTAL, tooltip: false, type: AxisDirection, notify: function() { var reLayouted; false; this._doLayoutDirty(); }, animatable: false }, _N$padding: { default: 0 }, paddingLeft: { default: 0, tooltip: false, notify: function() { this._doLayoutDirty(); } }, paddingRight: { default: 0, tooltip: false, notify: function() { this._doLayoutDirty(); } }, paddingTop: { default: 0, tooltip: false, notify: function() { this._doLayoutDirty(); } }, paddingBottom: { default: 0, tooltip: false, notify: function() { this._doLayoutDirty(); } }, spacingX: { default: 0, notify: function() { this._doLayoutDirty(); }, tooltip: false }, spacingY: { default: 0, notify: function() { this._doLayoutDirty(); }, tooltip: false }, verticalDirection: { default: VerticalDirection.TOP_TO_BOTTOM, type: VerticalDirection, notify: function() { this._doLayoutDirty(); }, tooltip: false, animatable: false }, horizontalDirection: { default: HorizontalDirection.LEFT_TO_RIGHT, type: HorizontalDirection, notify: function() { this._doLayoutDirty(); }, tooltip: false, animatable: false }, affectedByScale: { default: false, notify: function() { this._doLayoutDirty(); }, animatable: false, tooltip: false } }, statics: { Type: Type, VerticalDirection: VerticalDirection, HorizontalDirection: HorizontalDirection, ResizeMode: ResizeMode, AxisDirection: AxisDirection }, _migratePaddingData: function() { this.paddingLeft = this._N$padding; this.paddingRight = this._N$padding; this.paddingTop = this._N$padding; this.paddingBottom = this._N$padding; this._N$padding = 0; }, onEnable: function() { this._addEventListeners(); this.node.getContentSize().equals(cc.size(0, 0)) && this.node.setContentSize(this._layoutSize); 0 !== this._N$padding && this._migratePaddingData(); this._doLayoutDirty(); }, onDisable: function() { this._removeEventListeners(); }, _doLayoutDirty: function() { this._layoutDirty = true; }, _doScaleDirty: function() { this._layoutDirty = this._layoutDirty || this.affectedByScale; }, _addEventListeners: function() { 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() { 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() { 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() { 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(child) { child.on(NodeEvent.SCALE_CHANGED, this._doScaleDirty, this); child.on(NodeEvent.SIZE_CHANGED, this._doLayoutDirty, this); child.on(NodeEvent.POSITION_CHANGED, this._doLayoutDirty, this); child.on(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this); child.on("active-in-hierarchy-changed", this._doLayoutDirty, this); this._doLayoutDirty(); }, _childRemoved: function(child) { 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() { this._layoutSize = this.node.getContentSize(); this._doLayoutDirty(); }, _doLayoutHorizontally: function(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(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(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() { 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 leftBottomInParentSpace = this.node.parent.convertToNodeSpaceAR(cc.v2(allChildrenBoundingBox.x, allChildrenBoundingBox.y)); leftBottomInParentSpace = cc.v2(leftBottomInParentSpace.x - this.paddingLeft, leftBottomInParentSpace.y - this.paddingBottom); var rightTopInParentSpace = this.node.parent.convertToNodeSpaceAR(cc.v2(allChildrenBoundingBox.x + allChildrenBoundingBox.width, allChildrenBoundingBox.y + allChildrenBoundingBox.height)); rightTopInParentSpace = cc.v2(rightTopInParentSpace.x + this.paddingRight, rightTopInParentSpace.y + this.paddingTop); var newSize = cc.size(parseFloat((rightTopInParentSpace.x - leftBottomInParentSpace.x).toFixed(2)), parseFloat((rightTopInParentSpace.y - leftBottomInParentSpace.y).toFixed(2))); var layoutPosition = this.node.getPosition(); if (0 !== newSize.width) { var newAnchorX = (layoutPosition.x - leftBottomInParentSpace.x) / newSize.width; this.node.anchorX = parseFloat(newAnchorX.toFixed(2)); } if (0 !== newSize.height) { var newAnchorY = (layoutPosition.y - leftBottomInParentSpace.y) / newSize.height; this.node.anchorY = parseFloat(newAnchorY.toFixed(2)); } this.node.setContentSize(newSize); } }, _doLayoutGridAxisHorizontal: function(layoutAnchor, layoutSize) { var baseWidth = layoutSize.width; 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(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() { 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(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() { if (this.type === Type.HORIZONTAL) { var newWidth = this._getHorizontalBaseWidth(this.node.children); var fnPositionY = function(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(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(value) { return this.affectedByScale ? Math.abs(value) : 1; }, updateLayout: function() { if (this._layoutDirty && this.node.children.length > 0) { this._doLayout(); this._layoutDirty = false; } } }); Object.defineProperty(Layout.prototype, "padding", { get: function() { cc.warnID(4100); return this.paddingLeft; }, set: function(value) { this._N$padding = value; this._migratePaddingData(); this._doLayoutDirty(); } }); cc.Layout = module.exports = Layout; }), { "../CCNode": 30, "./CCComponent": 68 } ], 73: [ (function(require, module, exports) { var misc = require("../utils/misc"); var renderEngine = require("../renderer/render-engine"); var math = renderEngine.math; var StencilMaterial = renderEngine.StencilMaterial; var RenderComponent = require("./CCRenderComponent"); var RenderFlow = require("../renderer/render-flow"); var Graphics = require("../graphics/graphics"); var Node = require("../CCNode"); var dynamicAtlasManager = require("../renderer/utils/dynamic-atlas/manager"); var _vec2_temp = cc.v2(); var _mat4_temp = math.mat4.create(); 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() { this._graphics = null; this._clearGraphics = null; }, properties: { _spriteFrame: { default: null, type: cc.SpriteFrame }, _type: MaskType.RECT, type: { get: function() { return this._type; }, set: function(value) { this._type = value; if (this._type !== MaskType.IMAGE_STENCIL) { this.spriteFrame = null; this.alphaThreshold = 0; this._updateGraphics(); } if (this._renderData) { this.destroyRenderData(this._renderData); this._renderData = null; } this._activateMaterial(); }, type: MaskType, tooltip: false }, spriteFrame: { type: cc.SpriteFrame, tooltip: false, get: function() { return this._spriteFrame; }, set: function(value) { var lastSprite = this._spriteFrame; false; if (lastSprite === value) return; this._spriteFrame = value; this._applySpriteFrame(lastSprite); } }, alphaThreshold: { default: 0, type: cc.Float, range: [ 0, 1, .1 ], slide: true, tooltip: false, notify: function() { if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) { cc.warnID(4201); return; } if (this._material) { this._material.alphaThreshold = this.alphaThreshold; this._material.updateHash(); } } }, inverted: { default: false, type: cc.Boolean, tooltip: false, notify: function() { if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) { cc.warnID(4202); return; } } }, _segments: 64, segements: { get: function() { return this._segments; }, set: function(value) { this._segments = misc.clampf(value, SEGEMENTS_MIN, SEGEMENTS_MAX); this._updateGraphics(); }, type: cc.Integer, tooltip: false }, _resizeToTarget: { animatable: false, set: function(value) { value && this._resizeNodeToTargetNode(); } } }, statics: { Type: MaskType }, onLoad: function() { this._createGraphics(); }, onRestore: function() { this._createGraphics(); this._type !== MaskType.IMAGE_STENCIL ? this._updateGraphics() : this._applySpriteFrame(); }, onEnable: function() { this._super(); if (this._type === MaskType.IMAGE_STENCIL) { if (!this._spriteFrame || !this._spriteFrame.textureLoaded()) { this.markForRender(false); if (this._spriteFrame) { this.markForUpdateRenderData(false); this._spriteFrame.once("load", this._onTextureLoaded, this); this._spriteFrame.ensureLoadTexture(); } } } else this._updateGraphics(); this.node.on(cc.Node.EventType.POSITION_CHANGED, this._updateGraphics, this); this.node.on(cc.Node.EventType.ROTATION_CHANGED, this._updateGraphics, this); this.node.on(cc.Node.EventType.SCALE_CHANGED, this._updateGraphics, this); this.node.on(cc.Node.EventType.SIZE_CHANGED, this._updateGraphics, this); this.node.on(cc.Node.EventType.ANCHOR_CHANGED, this._updateGraphics, this); this.node._renderFlag |= RenderFlow.FLAG_POST_RENDER; this._activateMaterial(); }, onDisable: function() { 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() { this._super(); this._removeGraphics(); }, _resizeNodeToTargetNode: false, _onTextureLoaded: function() { if (this._renderData) { this._renderData.uvDirty = true; this._renderData.vertDirty = true; this.markForUpdateRenderData(true); } this.enabledInHierarchy && this._activateMaterial(); }, _applySpriteFrame: function(oldFrame) { oldFrame && oldFrame.off && oldFrame.off("load", this._onTextureLoaded, this); var spriteFrame = this._spriteFrame; if (spriteFrame) if (spriteFrame.textureLoaded()) this._onTextureLoaded(null); else { spriteFrame.once("load", this._onTextureLoaded, this); spriteFrame.ensureLoadTexture(); } else this.disableRender(); }, _activateMaterial: function() { if (this._type === MaskType.IMAGE_STENCIL && (!this.spriteFrame || !this.spriteFrame.textureLoaded())) { this.markForRender(false); return; } if (cc.game.renderType !== cc.game.RENDER_TYPE_CANVAS) { this._material || (this._material = new StencilMaterial()); if (this._type === MaskType.IMAGE_STENCIL) { var texture = this.spriteFrame.getTexture(); this._material.useModel = false; this._material.useTexture = true; this._material.useColor = true; this._material.texture = texture; this._material.alphaThreshold = this.alphaThreshold; } else { this._material.useModel = true; this._material.useTexture = false; this._material.useColor = false; } } this.markForRender(true); }, _createGraphics: function() { if (!this._graphics) { this._graphics = new Graphics(); this._graphics.node = this.node; this._graphics.lineWidth = 0; this._graphics.strokeColor = cc.color(0, 0, 0, 0); } if (!this._clearGraphics) { this._clearGraphics = new Graphics(); this._clearGraphics.node = new Node(); this._clearGraphics._activateMaterial(); this._clearGraphics.lineWidth = 0; this._clearGraphics.rect(0, 0, cc.visibleRect.width, cc.visibleRect.height); this._clearGraphics.fill(); } }, _updateGraphics: function() { 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(); }, _removeGraphics: function() { this._graphics && this._graphics.destroy(); this._clearGraphics && this._clearGraphics.destroy(); }, _hitTest: function(cameraPt) { var node = this.node; var size = node.getContentSize(), w = size.width, h = size.height, testPt = _vec2_temp; node._updateWorldMatrix(); math.mat4.invert(_mat4_temp, node._worldMatrix); math.vec2.transformMat4(testPt, cameraPt, _mat4_temp); testPt.x += node._anchorPoint.x * w; testPt.y += node._anchorPoint.y * h; 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; }, markForUpdateRenderData: function(enable) { enable && this.enabledInHierarchy ? this.node._renderFlag |= RenderFlow.FLAG_UPDATE_RENDER_DATA : enable || (this.node._renderFlag &= ~RenderFlow.FLAG_UPDATE_RENDER_DATA); }, markForRender: function(enable) { enable && this.enabledInHierarchy ? this.node._renderFlag |= RenderFlow.FLAG_RENDER | RenderFlow.FLAG_UPDATE_RENDER_DATA | RenderFlow.FLAG_POST_RENDER : enable || (this.node._renderFlag &= ~(RenderFlow.FLAG_RENDER | RenderFlow.FLAG_POST_RENDER)); }, disableRender: function() { this.node._renderFlag &= ~(RenderFlow.FLAG_RENDER | RenderFlow.FLAG_UPDATE_RENDER_DATA | RenderFlow.FLAG_POST_RENDER); }, _calDynamicAtlas: function() { if (!this._spriteFrame) return; if (!this._spriteFrame._original && dynamicAtlasManager) { var frame = dynamicAtlasManager.insertSpriteFrame(this._spriteFrame); frame && this._spriteFrame._setDynamicAtlasFrame(frame); } this._material._texture !== this._spriteFrame._texture && this._activateMaterial(); } }); cc.Mask = module.exports = Mask; }), { "../CCNode": 30, "../graphics/graphics": 107, "../renderer/render-engine": 203, "../renderer/render-flow": 204, "../renderer/utils/dynamic-atlas/manager": 206, "../utils/misc": 243, "./CCRenderComponent": 78 } ], 74: [ (function(require, module, exports) { var RenderComponent = require("../components/CCRenderComponent"); var SpriteMaterial = require("../renderer/render-engine").SpriteMaterial; var textureUtil = require("../utils/texture-util"); var MotionStreak = cc.Class({ name: "cc.MotionStreak", extends: RenderComponent, editor: false, ctor: function() { this._points = []; }, properties: { preview: { default: false, editorOnly: true, notify: false, animatable: false }, _fadeTime: 1, fadeTime: { get: function() { return this._fadeTime; }, set: function(value) { this._fadeTime = value; this.reset(); }, animatable: false, tooltip: false }, _minSeg: 1, minSeg: { get: function() { return this._minSeg; }, set: function(value) { this._minSeg = value; }, animatable: false, tooltip: false }, _stroke: 64, stroke: { get: function() { return this._stroke; }, set: function(value) { this._stroke = value; }, animatable: false, tooltip: false }, _texture: { default: null, type: cc.Texture2D }, texture: { get: function() { return this._texture; }, set: function(value) { if (this._texture === value) return; this._texture = value; if (value && value.loaded) this._activateMaterial(); else { this.disableRender(); this._ensureLoadTexture(); } }, type: cc.Texture2D, animatable: false, tooltip: false }, _color: cc.Color.WHITE, color: { get: function() { return this._color; }, set: function(value) { this._color = value; }, type: cc.Color, tooltip: false }, _fastMode: false, fastMode: { get: function() { return this._fastMode; }, set: function(value) { this._fastMode = value; }, animatable: false, tooltip: false } }, onEnable: function() { this._super(); if (this._texture && this._texture.loaded) this._activateMaterial(); else { this.disableRender(); this._ensureLoadTexture(); } this.reset(); }, _ensureLoadTexture: function() { var _this = this; this._texture && !this._texture.loaded && (function() { var self = _this; textureUtil.postLoadTexture(_this._texture, (function() { self._activateMaterial(); })); })(); }, _activateMaterial: function() { var material = this._material; if (!material) { material = this._material = new SpriteMaterial(); material.useColor = false; } if (this._texture && this._texture.loaded) { material.texture = this._texture; this._updateMaterial(material); this.markForRender(true); this.markForUpdateRenderData(true); } }, onFocusInEditor: false, onLostFocusInEditor: false, reset: function() { this._points.length = 0; var renderData = this._renderData; if (renderData) { renderData.dataLength = 0; renderData.vertexCount = 0; renderData.indiceCount = 0; } false; } }); cc.MotionStreak = module.exports = MotionStreak; }), { "../components/CCRenderComponent": 78, "../renderer/render-engine": 203, "../utils/texture-util": 251 } ], 75: [ (function(require, module, exports) { var SizeMode = cc.Enum({ Unified: 0, Free: 1 }); var Direction = cc.Enum({ Horizontal: 0, Vertical: 1 }); var EventType = cc.Enum({ PAGE_TURNING: 0 }); var PageView = cc.Class({ name: "cc.PageView", extends: cc.ScrollView, editor: false, ctor: function() { this._curPageIdx = 0; this._lastPageIdx = 0; this._pages = []; this._scrollCenterOffsetX = []; this._scrollCenterOffsetY = []; }, properties: { sizeMode: { default: SizeMode.Unified, type: SizeMode, tooltip: false, notify: function() { this._syncSizeMode(); } }, direction: { default: Direction.Horizontal, type: Direction, tooltip: false, notify: function() { this._syncScrollDirection(); } }, scrollThreshold: { default: .5, type: cc.Float, slide: true, range: [ 0, 1, .01 ], tooltip: false }, autoPageTurningThreshold: { default: 100, type: cc.Float, tooltip: false }, pageTurningEventTiming: { default: .1, type: cc.Float, range: [ 0, 1, .01 ], tooltip: false }, indicator: { default: null, type: cc.PageViewIndicator, tooltip: false, notify: function() { this.indicator && this.indicator.setPageView(this); } }, pageTurningSpeed: { default: .3, type: cc.Float, tooltip: false }, pageEvents: { default: [], type: cc.Component.EventHandler, tooltip: false } }, statics: { SizeMode: SizeMode, Direction: Direction, EventType: EventType }, __preload: function() { this.node.on(cc.Node.EventType.SIZE_CHANGED, this._updateAllPagesSize, this); }, onEnable: function() { this._super(); true; this.node.on("scroll-ended-with-threshold", this._dispatchPageTurningEvent, this); }, onDisable: function() { this._super(); true; this.node.off("scroll-ended-with-threshold", this._dispatchPageTurningEvent, this); }, onLoad: function() { this._initPages(); this.indicator && this.indicator.setPageView(this); }, onDestroy: function() { this.node.off(cc.Node.EventType.SIZE_CHANGED, this._updateAllPagesSize, this); }, getCurrentPageIndex: function() { return this._curPageIdx; }, setCurrentPageIndex: function(index) { this.scrollToPage(index, true); }, getPages: function() { return this._pages; }, addPage: function(page) { if (!page || -1 !== this._pages.indexOf(page) || !this.content) return; this.content.addChild(page); this._pages.push(page); this._updatePageView(); }, insertPage: function(page, index) { if (index < 0 || !page || -1 !== this._pages.indexOf(page) || !this.content) return; var pageCount = this._pages.length; if (index >= pageCount) this.addPage(page); else { this._pages.splice(index, 0, page); this.content.addChild(page); this._updatePageView(); } }, removePage: function(page) { if (!page || !this.content) return; var index = this._pages.indexOf(page); if (-1 === index) { cc.warnID(4300, page.name); return; } this.removePageAtIndex(index); }, removePageAtIndex: function(index) { var pageList = this._pages; if (index < 0 || index >= pageList.length) return; var page = pageList[index]; if (!page) return; this.content.removeChild(page); pageList.splice(index, 1); this._updatePageView(); }, removeAllPages: function() { if (!this.content) return; var locPages = this._pages; for (var i = 0, len = locPages.length; i < len; i++) this.content.removeChild(locPages[i]); this._pages.length = 0; this._updatePageView(); }, scrollToPage: function(idx, timeInSecond) { if (idx < 0 || idx >= this._pages.length) return; timeInSecond = void 0 !== timeInSecond ? timeInSecond : .3; this._curPageIdx = idx; this.scrollToOffset(this._moveOffsetValue(idx), timeInSecond, true); this.indicator && this.indicator._changedState(); }, getScrollEndedEventTiming: function() { return this.pageTurningEventTiming; }, _syncScrollDirection: function() { this.horizontal = this.direction === Direction.Horizontal; this.vertical = this.direction === Direction.Vertical; }, _syncSizeMode: function() { if (!this.content) return; var layout = this.content.getComponent(cc.Layout); if (layout) { if (0 === this._pages.length) layout.padding = 0; else { var lastPage = this._pages[this._pages.length - 1]; if (this.sizeMode === SizeMode.Free) if (this.direction === Direction.Horizontal) { layout.paddingLeft = (this._view.width - this._pages[0].width) / 2; layout.paddingRight = (this._view.width - lastPage.width) / 2; } else if (this.direction === Direction.Vertical) { layout.paddingTop = (this._view.height - this._pages[0].height) / 2; layout.paddingBottom = (this._view.height - lastPage.height) / 2; } } layout.updateLayout(); } }, _updatePageView: function() { var pageCount = this._pages.length; if (this._curPageIdx >= pageCount) { this._curPageIdx = 0 === pageCount ? 0 : pageCount - 1; this._lastPageIdx = this._curPageIdx; } for (var i = 0; i < pageCount; ++i) { this._pages[i].setSiblingIndex(i); this.direction === Direction.Horizontal ? this._scrollCenterOffsetX[i] = Math.abs(this.content.x + this._pages[i].x) : this._scrollCenterOffsetY[i] = Math.abs(this.content.y + this._pages[i].y); } var layout = this.content.getComponent(cc.Layout); layout && layout.enabled && layout.updateLayout(); this.indicator && this.indicator._refresh(); }, _updateAllPagesSize: function() { if (this.sizeMode !== SizeMode.Unified) return; var locPages = this._pages; var selfSize = this._view.getContentSize(); for (var i = 0, len = locPages.length; i < len; i++) locPages[i].setContentSize(selfSize); }, _initPages: function() { if (!this.content) return; var children = this.content.children; for (var i = 0; i < children.length; ++i) { var page = children[i]; if (this._pages.indexOf(page) >= 0) continue; this._pages.push(page); } this._syncScrollDirection(); this._syncSizeMode(); this._updatePageView(); }, _dispatchPageTurningEvent: function() { if (this._lastPageIdx === this._curPageIdx) return; this._lastPageIdx = this._curPageIdx; cc.Component.EventHandler.emitEvents(this.pageEvents, this, EventType.PAGE_TURNING); this.node.emit("page-turning", this); }, _isScrollable: function(offset, index, nextIndex) { if (this.sizeMode === SizeMode.Free) { var curPageCenter, nextPageCenter; if (this.direction === Direction.Horizontal) { curPageCenter = this._scrollCenterOffsetX[index]; nextPageCenter = this._scrollCenterOffsetX[nextIndex]; return Math.abs(offset.x) >= Math.abs(curPageCenter - nextPageCenter) * this.scrollThreshold; } if (this.direction === Direction.Vertical) { curPageCenter = this._scrollCenterOffsetY[index]; nextPageCenter = this._scrollCenterOffsetY[nextIndex]; return Math.abs(offset.y) >= Math.abs(curPageCenter - nextPageCenter) * this.scrollThreshold; } } else { if (this.direction === Direction.Horizontal) return Math.abs(offset.x) >= this._view.width * this.scrollThreshold; if (this.direction === Direction.Vertical) return Math.abs(offset.y) >= this._view.height * this.scrollThreshold; } }, _isQuicklyScrollable: function(touchMoveVelocity) { if (this.direction === Direction.Horizontal) { if (Math.abs(touchMoveVelocity.x) > this.autoPageTurningThreshold) return true; } else if (this.direction === Direction.Vertical && Math.abs(touchMoveVelocity.y) > this.autoPageTurningThreshold) return true; return false; }, _moveOffsetValue: function(idx) { var offset = cc.v2(0, 0); this.sizeMode === SizeMode.Free ? this.direction === Direction.Horizontal ? offset.x = this._scrollCenterOffsetX[idx] : this.direction === Direction.Vertical && (offset.y = this._scrollCenterOffsetY[idx]) : this.direction === Direction.Horizontal ? offset.x = idx * this._view.width : this.direction === Direction.Vertical && (offset.y = idx * this._view.height); return offset; }, _getDragDirection: function(moveOffset) { if (this.direction === Direction.Horizontal) { if (0 === moveOffset.x) return 0; return moveOffset.x > 0 ? 1 : -1; } if (this.direction === Direction.Vertical) { if (0 === moveOffset.y) return 0; return moveOffset.y < 0 ? 1 : -1; } }, _handleReleaseLogic: function(touch) { this._autoScrollToPage(); if (this._scrolling) { this._scrolling = false; this._autoScrolling || this._dispatchEvent("scroll-ended"); } }, _autoScrollToPage: function() { var bounceBackStarted = this._startBounceBackIfNeeded(); var moveOffset = this._touchBeganPosition.sub(this._touchEndPosition); if (bounceBackStarted) { var dragDirection = this._getDragDirection(moveOffset); if (0 === dragDirection) return; this._curPageIdx = dragDirection > 0 ? this._pages.length - 1 : 0; this.indicator && this.indicator._changedState(); } else { var index = this._curPageIdx, nextIndex = index + this._getDragDirection(moveOffset); var timeInSecond = this.pageTurningSpeed * Math.abs(index - nextIndex); if (nextIndex < this._pages.length) { if (this._isScrollable(moveOffset, index, nextIndex)) { this.scrollToPage(nextIndex, timeInSecond); return; } var touchMoveVelocity = this._calculateTouchMoveVelocity(); if (this._isQuicklyScrollable(touchMoveVelocity)) { this.scrollToPage(nextIndex, timeInSecond); return; } } this.scrollToPage(index, timeInSecond); } }, _onTouchBegan: function(event, captureListeners) { this._touchBeganPosition = event.touch.getLocation(); this._super(event, captureListeners); }, _onTouchMoved: function(event, captureListeners) { this._super(event, captureListeners); }, _onTouchEnded: function(event, captureListeners) { this._touchEndPosition = event.touch.getLocation(); this._super(event, captureListeners); }, _onTouchCancelled: function(event, captureListeners) { this._touchEndPosition = event.touch.getLocation(); this._super(event, captureListeners); }, _onMouseWheel: function() {} }); cc.PageView = module.exports = PageView; }), {} ], 76: [ (function(require, module, exports) { var Direction = cc.Enum({ HORIZONTAL: 0, VERTICAL: 1 }); var PageViewIndicator = cc.Class({ name: "cc.PageViewIndicator", extends: require("./CCComponent"), editor: false, properties: { _layout: null, _pageView: null, _indicators: [], spriteFrame: { default: null, type: cc.SpriteFrame, tooltip: false }, direction: { default: Direction.HORIZONTAL, type: Direction, tooltip: false }, cellSize: { default: cc.size(20, 20), tooltip: false }, spacing: { default: 0, tooltip: false } }, statics: { Direction: Direction }, onLoad: function() { this._updateLayout(); }, setPageView: function(target) { this._pageView = target; this._refresh(); }, _updateLayout: function() { this._layout = this.getComponent(cc.Layout); this._layout || (this._layout = this.addComponent(cc.Layout)); if (this.direction === Direction.HORIZONTAL) { this._layout.type = cc.Layout.Type.HORIZONTAL; this._layout.spacingX = this.spacing; } else if (this.direction === Direction.VERTICAL) { this._layout.type = cc.Layout.Type.VERTICAL; this._layout.spacingY = this.spacing; } this._layout.resizeMode = cc.Layout.ResizeMode.CONTAINER; }, _createIndicator: function() { var node = new cc.Node(); var sprite = node.addComponent(cc.Sprite); sprite.spriteFrame = this.spriteFrame; node.parent = this.node; node.width = this.cellSize.width; node.height = this.cellSize.height; return node; }, _changedState: function() { var indicators = this._indicators; if (0 === indicators.length) return; var idx = this._pageView._curPageIdx; if (idx >= indicators.length) return; for (var i = 0; i < indicators.length; ++i) { var node = indicators[i]; node.opacity = 127.5; } indicators[idx].opacity = 255; }, _refresh: function() { if (!this._pageView) return; var indicators = this._indicators; var pages = this._pageView.getPages(); if (pages.length === indicators.length) return; var i = 0; if (pages.length > indicators.length) for (i = 0; i < pages.length; ++i) indicators[i] || (indicators[i] = this._createIndicator()); else { var count = indicators.length - pages.length; for (i = count; i > 0; --i) { var node = indicators[i - 1]; this.node.removeChild(node); indicators.splice(i - 1, 1); } } this._layout && this._layout.enabledInHierarchy && this._layout.updateLayout(); this._changedState(); } }); cc.PageViewIndicator = module.exports = PageViewIndicator; }), { "./CCComponent": 68 } ], 77: [ (function(require, module, exports) { var misc = require("../utils/misc"); var Component = require("./CCComponent"); var Mode = cc.Enum({ HORIZONTAL: 0, VERTICAL: 1, FILLED: 2 }); var ProgressBar = cc.Class({ name: "cc.ProgressBar", extends: Component, editor: false, _initBarSprite: function() { if (this.barSprite) { var entity = this.barSprite.node; if (!entity) return; var nodeSize = this.node.getContentSize(); var nodeAnchor = this.node.getAnchorPoint(); var entitySize = entity.getContentSize(); entity.parent === this.node && this.node.setContentSize(entitySize); this.barSprite.fillType === cc.Sprite.FillType.RADIAL && (this.mode = Mode.FILLED); var barSpriteSize = entity.getContentSize(); this.mode === Mode.HORIZONTAL ? this.totalLength = barSpriteSize.width : this.mode === Mode.VERTICAL ? this.totalLength = barSpriteSize.height : this.totalLength = this.barSprite.fillRange; if (entity.parent === this.node) { var x = -nodeSize.width * nodeAnchor.x; var y = 0; entity.setPosition(cc.v2(x, y)); } } }, _updateBarStatus: function() { if (this.barSprite) { var entity = this.barSprite.node; if (!entity) return; var entityAnchorPoint = entity.getAnchorPoint(); var entitySize = entity.getContentSize(); var entityPosition = entity.getPosition(); var anchorPoint = cc.v2(0, .5); var progress = misc.clamp01(this.progress); var actualLenth = this.totalLength * progress; var finalContentSize; var totalWidth; var totalHeight; switch (this.mode) { case Mode.HORIZONTAL: this.reverse && (anchorPoint = cc.v2(1, .5)); finalContentSize = cc.size(actualLenth, entitySize.height); totalWidth = this.totalLength; totalHeight = entitySize.height; break; case Mode.VERTICAL: anchorPoint = this.reverse ? cc.v2(.5, 1) : cc.v2(.5, 0); finalContentSize = cc.size(entitySize.width, actualLenth); totalWidth = entitySize.width; totalHeight = this.totalLength; } if (this.mode === Mode.FILLED) if (this.barSprite.type !== cc.Sprite.Type.FILLED) cc.warn("ProgressBar FILLED mode only works when barSprite's Type is FILLED!"); else { this.reverse && (actualLenth *= -1); this.barSprite.fillRange = actualLenth; } else if (this.barSprite.type !== cc.Sprite.Type.FILLED) { var anchorOffsetX = anchorPoint.x - entityAnchorPoint.x; var anchorOffsetY = anchorPoint.y - entityAnchorPoint.y; var finalPosition = cc.v2(totalWidth * anchorOffsetX, totalHeight * anchorOffsetY); entity.setPosition(entityPosition.x + finalPosition.x, entityPosition.y + finalPosition.y); entity.setAnchorPoint(anchorPoint); entity.setContentSize(finalContentSize); } else cc.warn("ProgressBar non-FILLED mode only works when barSprite's Type is non-FILLED!"); } }, properties: { barSprite: { default: null, type: cc.Sprite, tooltip: false, notify: function() { this._initBarSprite(); }, animatable: false }, mode: { default: Mode.HORIZONTAL, type: Mode, tooltip: false, notify: function() { if (this.barSprite) { var entity = this.barSprite.node; if (!entity) return; var entitySize = entity.getContentSize(); this.mode === Mode.HORIZONTAL ? this.totalLength = entitySize.width : this.mode === Mode.VERTICAL ? this.totalLength = entitySize.height : this.mode === Mode.FILLED && (this.totalLength = this.barSprite.fillRange); } }, animatable: false }, _N$totalLength: 1, totalLength: { range: [ 0, Number.MAX_VALUE ], tooltip: false, get: function() { return this._N$totalLength; }, set: function(value) { this.mode === Mode.FILLED && (value = misc.clamp01(value)); this._N$totalLength = value; this._updateBarStatus(); } }, progress: { default: 1, type: "Float", range: [ 0, 1, .1 ], slide: true, tooltip: false, notify: function() { this._updateBarStatus(); } }, reverse: { default: false, tooltip: false, notify: function() { this.barSprite && (this.barSprite.fillStart = 1 - this.barSprite.fillStart); this._updateBarStatus(); }, animatable: false } }, statics: { Mode: Mode } }); cc.ProgressBar = module.exports = ProgressBar; }), { "../utils/misc": 243, "./CCComponent": 68 } ], 78: [ (function(require, module, exports) { var Component = require("./CCComponent"); var renderEngine = require("../renderer/render-engine"); var RenderFlow = require("../renderer/render-flow"); var RenderData = renderEngine.RenderData; var RenderComponent = cc.Class({ name: "RenderComponent", extends: Component, editor: false, properties: {}, ctor: function() { this._material = null; this._renderData = null; this.__allocedDatas = []; this._vertexFormat = null; this._toPostHandle = false; this._assembler = this.constructor._assembler; this._postAssembler = this.constructor._postAssembler; }, onEnable: function() { this.node._renderComponent && (this.node._renderComponent.enabled = false); this.node._renderComponent = this; this.node._renderFlag |= RenderFlow.FLAG_RENDER | RenderFlow.FLAG_UPDATE_RENDER_DATA | RenderFlow.FLAG_COLOR; }, onDisable: function() { this.node._renderComponent = null; this.disableRender(); }, onDestroy: function() { for (var i = 0, l = this.__allocedDatas.length; i < l; i++) RenderData.free(this.__allocedDatas[i]); this.__allocedDatas.length = 0; this._material = null; this._renderData = null; }, _canRender: function() { return this._enabled && this.node._activeInHierarchy; }, markForUpdateRenderData: function(enable) { enable && this._canRender() ? this.node._renderFlag |= RenderFlow.FLAG_UPDATE_RENDER_DATA : enable || (this.node._renderFlag &= ~RenderFlow.FLAG_UPDATE_RENDER_DATA); }, markForRender: function(enable) { enable && this._canRender() ? this.node._renderFlag |= RenderFlow.FLAG_RENDER : enable || (this.node._renderFlag &= ~RenderFlow.FLAG_RENDER); }, markForCustomIARender: function(enable) { enable && this._canRender() ? this.node._renderFlag |= RenderFlow.FLAG_CUSTOM_IA_RENDER : enable || (this.node._renderFlag &= ~RenderFlow.FLAG_CUSTOM_IA_RENDER); }, disableRender: function() { this.node._renderFlag &= ~(RenderFlow.FLAG_RENDER | RenderFlow.FLAG_CUSTOM_IA_RENDER | RenderFlow.FLAG_UPDATE_RENDER_DATA | RenderFlow.FLAG_COLOR); }, requestRenderData: function() { var data = RenderData.alloc(); this.__allocedDatas.push(data); return data; }, destroyRenderData: function(data) { var index = this.__allocedDatas.indexOf(data); if (-1 !== index) { this.__allocedDatas.splice(index, 1); RenderData.free(data); } }, _updateColor: function() { var material = this._material; if (material) { if (material.useColor) { material.color = this.node.color; material.updateHash(); } this.node._renderFlag &= ~RenderFlow.FLAG_COLOR; } }, getMaterial: function() { return this._material; }, _updateMaterial: function(material) { this._material = material; material.updateHash(); } }); RenderComponent._assembler = null; RenderComponent._postAssembler = null; cc.RenderComponent = module.exports = RenderComponent; }), { "../renderer/render-engine": 203, "../renderer/render-flow": 204, "./CCComponent": 68 } ], 79: [ (function(require, module, exports) { 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"; function debounce(func, wait, immediate) { var timeout = void 0; return function() { var context = this; var later = function() { 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; if (node.getComponent(cc.LabelOutline)) return false; return true; }, 20); pool.get = function(string, richtext) { var labelNode = this._get(); labelNode || (labelNode = new cc.PrivateNode(RichTextChildName)); var labelComponent = labelNode.getComponent(cc.Label); labelComponent || (labelComponent = labelNode.addComponent(cc.Label)); labelNode.setPosition(0, 0); labelNode.setAnchorPoint(.5, .5); labelNode.setContentSize(128, 128); labelNode.skewX = 0; "string" !== (__typeofVal = typeof string, "object" === __typeofVal ? __realTypeOfObj(string) : __typeofVal) && (string = "" + string); var isAsset = richtext.font instanceof cc.Font; isAsset ? labelComponent.font = richtext.font : labelComponent.fontFamily = richtext.fontFamily; labelComponent.string = string; labelComponent.horizontalAlign = HorizontalAlign.LEFT; labelComponent.verticalAlign = VerticalAlign.TOP; labelComponent.fontSize = richtext.fontSize || 40; labelComponent.overflow = 0; labelComponent.enableWrapText = true; labelComponent.lineHeight = 40; labelComponent._enableBold(false); labelComponent._enableItalics(false); labelComponent._enableUnderline(false); return labelNode; }; var RichText = cc.Class({ name: "cc.RichText", extends: cc.Component, ctor: function() { 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() { this._updateRichTextStatus(); } }, horizontalAlign: { default: HorizontalAlign.LEFT, type: HorizontalAlign, tooltip: false, animatable: false, notify: function(oldValue) { if (this.horizontalAlign === oldValue) return; this._layoutDirty = true; this._updateRichTextStatus(); } }, fontSize: { default: 40, tooltip: false, notify: function(oldValue) { if (this.fontSize === oldValue) return; this._layoutDirty = true; this._updateRichTextStatus(); } }, _fontFamily: "Arial", fontFamily: { tooltip: false, get: function() { return this._fontFamily; }, set: function(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(oldValue) { if (this.font === oldValue) return; this._layoutDirty = true; if (this.font) { this.useSystemFont = false; this._onTTFLoaded(); } else this.useSystemFont = true; this._updateRichTextStatus(); } }, _isSystemFontUsed: true, useSystemFont: { get: function() { return this._isSystemFontUsed; }, set: function(value) { if (!value && !this.font || this._isSystemFontUsed === value) return; this._isSystemFontUsed = value; this._layoutDirty = true; this._updateRichTextStatus(); }, animatable: false, tooltip: false }, maxWidth: { default: 0, tooltip: false, notify: function(oldValue) { if (this.maxWidth === oldValue) return; this._layoutDirty = true; this._updateRichTextStatus(); } }, lineHeight: { default: 40, tooltip: false, notify: function(oldValue) { if (this.lineHeight === oldValue) return; this._layoutDirty = true; this._updateRichTextStatus(); } }, imageAtlas: { default: null, type: cc.SpriteAtlas, tooltip: false, notify: function(oldValue) { if (this.imageAtlas === oldValue) return; this._layoutDirty = true; this._updateRichTextStatus(); } }, spriteFrames: { default: [], type: cc.SpriteFrame, notify: function(oldValue) { this._layoutDirty = true; this._updateRichTextStatus(); } }, touchHandlers: { default: {} }, handleTouchEvent: { default: true, tooltip: false, notify: function(oldValue) { if (this.handleTouchEvent === oldValue) return; this.enabledInHierarchy && (this.handleTouchEvent ? this._addEventListeners() : this._removeEventListeners()); } }, emojiSkeletonData: { default: {} }, emojiSkeletons: { default: {} } }, statics: { HorizontalAlign: HorizontalAlign, VerticalAlign: VerticalAlign }, onEnable: function() { this.handleTouchEvent && this._addEventListeners(); this._updateRichText(); this._activateChildren(true); }, onDisable: function() { this.handleTouchEvent && this._removeEventListeners(); this._activateChildren(false); }, start: function() { this._onTTFLoaded(); }, addSpriteFrame: function(spriteframe) { if (!spriteframe) return; for (var sprite_i in this.spriteFrames) if (this.spriteFrames[sprite_i].name === spriteframe.name) return; this.spriteFrames.push(spriteframe); this._layoutDirty = true; this._updateRichTextStatus(); }, _onColorChanged: function(parentColor) { var children = this.node.children; children.forEach((function(childNode) { childNode.color = parentColor; })); }, _addEventListeners: function() { this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this); this.node.on(cc.Node.EventType.COLOR_CHANGED, this._onColorChanged, this); }, _removeEventListeners: function() { this.node.off(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this); this.node.off(cc.Node.EventType.COLOR_CHANGED, this._onColorChanged, this); }, _updateLabelSegmentTextAttributes: function() { this._labelSegments.forEach(function(item) { this._applyTextAttribute(item); }.bind(this)); }, _createFontLabel: function(string) { return pool.get(string, this); }, _onTTFLoaded: function() { var _this = this; if (this.font instanceof cc.TTFFont) if (this.font._nativeAsset) { this._layoutDirty = true; this._updateRichText(); } else (function() { var self = _this; cc.loader.load(_this.font.nativeUrl, (function(err, fontFamily) { self._layoutDirty = true; self._updateRichText(); })); })(); else { this._layoutDirty = true; this._updateRichText(); } }, _measureText: function(styleIndex, string) { var self = this; var func = function(string) { var label = void 0; if (0 === self._labelSegmentsCache.length) { label = self._createFontLabel(string); self._labelSegmentsCache.push(label); } else { label = self._labelSegmentsCache[0]; label.getComponent(cc.Label).string = string; } label._styleIndex = styleIndex; self._applyTextAttribute(label); var labelSize = label.getContentSize(); return labelSize.width; }; return string ? func(string) : func; }, _onTouchEnded: function(event) { var _this2 = this; var components = this.node.getComponents(cc.Component); var _loop = function(i) { var labelSegment = _this2._labelSegments[i]; var clickHandler = labelSegment._clickHandler; var clickParam = labelSegment._clickParam; if (clickHandler && _this2._containsTouchLocation(labelSegment, event.touch.getLocation())) { components.forEach((function(component) { component.enabledInHierarchy && component[clickHandler] && component[clickHandler](event, clickParam); })); event.stopPropagation(); if (_this2.touchHandlers[clickHandler]) { _this2.touchHandlers[clickHandler](event, clickParam); event.stopPropagation(); } } }; for (var i = 0; i < this._labelSegments.length; ++i) _loop(i); }, addTouchHandler: function(name, handle) { if (!name || !handle) return; this.touchHandlers[name] || (this.touchHandlers[name] = handle); }, _containsTouchLocation: function(label, point) { var myRect = label.getBoundingBoxToWorld(); return myRect.contains(point); }, _resetState: function() { 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(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(stringToken, styleIndex) { var labelSegment = void 0; if (0 === this._labelSegmentsCache.length) labelSegment = this._createFontLabel(stringToken); else { labelSegment = this._labelSegmentsCache.pop(); labelSegment.getComponent(cc.Label).string = stringToken; } labelSegment._styleIndex = styleIndex; labelSegment._lineCount = this._lineCount; labelSegment.active = this.node.active; labelSegment.setAnchorPoint(0, 0); this._applyTextAttribute(labelSegment); this.node.addChild(labelSegment); this._labelSegments.push(labelSegment); return labelSegment; }, _updateRichTextWithMaxWidth: function(labelString, labelWidth, styleIndex) { var fragmentWidth = labelWidth; var labelSegment = void 0; 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(stringToken) { return stringToken.length - 1 === stringToken.lastIndexOf("\n"); }, _updateLineInfo: function() { this._linesWidth.push(this._lineOffsetX); this._lineOffsetX = 0; this._lineCount++; }, _needsUpdateTextLayout: function(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; if (oldItem.style) { if (newItem.style) { if (!!newItem.style.outline !== !!oldItem.style.outline) return true; if (oldItem.style.size !== newItem.style.size || oldItem.style.italic !== newItem.style.italic || oldItem.style.isImage !== newItem.style.isImage) return true; if (oldItem.style.isImage === newItem.style.isImage && oldItem.style.src !== newItem.style.src) return true; } else if (oldItem.style.size || oldItem.style.italic || oldItem.style.isImage || oldItem.style.outline) return true; } else if (newItem.style && (newItem.style.size || newItem.style.italic || newItem.style.isImage || newItem.style.outline)) return true; } return false; }, _addRichTextImageElement: function(richTextElement) { var spriteFrameName = richTextElement.style.src; var spriteFrame = null; this.imageAtlas && (spriteFrame = this.imageAtlas.getSpriteFrame(spriteFrameName)); if (!spriteFrame) for (var sprite_i in this.spriteFrames) this.spriteFrames[sprite_i].name == spriteFrameName && (spriteFrame = this.spriteFrames[sprite_i]); if (spriteFrame) { var spriteNode = new cc.PrivateNode(RichTextChildImageName); var spriteComponent = spriteNode.addComponent(cc.Sprite); spriteNode.setAnchorPoint(0, 0); 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 && expectHeight < this.lineHeight) { 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); } } else cc.warnID(4400); }, addEmojiAtlas: function(emojsAtlas, emojiName) { if (!emojsAtlas || !emojiName) return; if (!this.emojiSkeletons[emojiName]) { this.emojiSkeletons[emojiName] = emojsAtlas; this._layoutDirty = true; this._updateRichTextStatus(); } }, _addRichTextEmojiElement: function(richTextElement) { var emojiName = richTextElement.style.emoji; var emojiSkeleton = this.emojiSkeletons[emojiName]; if (emojiName && emojiSkeleton) { var segmentNode = new cc.PrivateNode(RichTextChildImageName); var skeletonNd = new cc.PrivateNode("test"); var skeletonComponent = skeletonNd.addComponent(sp.Skeleton); skeletonNd.X = 15; skeletonNd.Y = 15; segmentNode.addChild(skeletonNd); segmentNode.setAnchorPoint(0, 0); this.node.addChild(segmentNode); this._labelSegments.push(segmentNode); var spriteRect = new cc.Rect(0, 0, 30, 30); var scaleFactor = 1; var spriteWidth = spriteRect.width; var spriteHeight = spriteRect.height; var expectWidth = richTextElement.style.imageWidth || 30; var expectHeight = richTextElement.style.imageHeight || 30; if (expectHeight > 0 && expectHeight < this.lineHeight) { 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); } skeletonComponent.skeletonData = emojiSkeleton; skeletonComponent.setAnimation(0, emojiSkeleton.name, true); segmentNode.setContentSize(spriteWidth, spriteHeight); segmentNode._lineCount = this._lineCount; if (richTextElement.style.event) { richTextElement.style.event.click && (segmentNode._clickHandler = richTextElement.style.event.click); richTextElement.style.event.param && (segmentNode._clickParam = richTextElement.style.event.param); } } else cc.warnID(4400); }, _updateRichText: function() { if (!this.enabled) 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 = void 0; var labelSize = void 0; 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 && !richTextElement.style.emoji && (this.imageAtlas || this.spriteFrames.length > 0)) { this._addRichTextImageElement(richTextElement); continue; } richTextElement.style && richTextElement.style.emoji && this._addRichTextEmojiElement(richTextElement); } 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 * this.lineHeight; this.node.setContentSize(this._labelWidth, this._labelHeight); this._updateRichTextPosition(); this._layoutDirty = false; }, _getFirstWordLen: function(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() { 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); } }, _convertLiteralColorValue: function(color) { var colorValue = color.toUpperCase(); if (cc.Color[colorValue]) return cc.Color[colorValue]; var out = cc.color(); return out.fromHEX(color); }, _applyTextAttribute: function(labelNode) { var labelComponent = labelNode.getComponent(cc.Label); if (!labelComponent) return; var index = labelNode._styleIndex; this._isSystemFontUsed && (labelComponent.fontFamily = this._fontFamily); labelComponent.useSystemFont = this._isSystemFontUsed; labelComponent.lineHeight = this.lineHeight; labelComponent.horizontalAlign = HorizontalAlign.LEFT; labelComponent.verticalAlign = VerticalAlign.CENTER; 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._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; labelComponent._updateRenderData(true); if (textStyle && textStyle.event) { textStyle.event.click && (labelNode._clickHandler = textStyle.event.click); textStyle.event.param && (labelNode._clickParam = textStyle.event.param); } }, onDestroy: function() { for (var i = 0; i < this._labelSegments.length; ++i) { this._labelSegments[i].removeFromParent(); pool.put(this._labelSegments[i]); } } }); cc.RichText = module.exports = RichText; }), { "../platform/CCMacro": 166, "../platform/js": 181, "../utils/html-text-parser": 240, "../utils/text-utils": 250 } ], 80: [ (function(require, module, exports) { 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() { this._onScroll(cc.v2(0, 0)); }, animatable: false }, direction: { default: Direction.HORIZONTAL, type: Direction, tooltip: false, notify: function() { 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(scrollView) { this._scrollView = scrollView; }, _convertToScrollViewSpace: function(content) { var worldSpacePos = content.convertToWorldSpace(cc.v2(0, 0)); var scrollViewSpacePos = this._scrollView.node.convertToNodeSpace(worldSpacePos); return scrollViewSpacePos; }, _setOpacity: function(opacity) { if (this.handle) { this.node.opacity = opacity; this.handle.node.opacity = opacity; } }, _onScroll: function(outOfBoundary) { if (this._scrollView) { var content = this._scrollView.content; if (content) { var contentSize = content.getContentSize(); var scrollViewSize = this._scrollView.node.getContentSize(); var handleNodeSize = this.node.getContentSize(); if (this._conditionalDisableScrollBar(contentSize, scrollViewSize)) return; if (this.enableAutoHide) { this._autoHideRemainingTime = this.autoHideTime; this._setOpacity(this._opacity); } var contentMeasure = 0; var scrollViewMeasure = 0; var outOfBoundaryValue = 0; var contentPosition = 0; var handleNodeMeasure = 0; if (this.direction === Direction.HORIZONTAL) { contentMeasure = contentSize.width; scrollViewMeasure = scrollViewSize.width; handleNodeMeasure = handleNodeSize.width; outOfBoundaryValue = outOfBoundary.x; contentPosition = -this._convertToScrollViewSpace(content).x; } else if (this.direction === Direction.VERTICAL) { contentMeasure = contentSize.height; scrollViewMeasure = scrollViewSize.height; handleNodeMeasure = handleNodeSize.height; outOfBoundaryValue = outOfBoundary.y; contentPosition = -this._convertToScrollViewSpace(content).y; } var length = this._calculateLength(contentMeasure, scrollViewMeasure, handleNodeMeasure, outOfBoundaryValue); var position = this._calculatePosition(contentMeasure, scrollViewMeasure, handleNodeMeasure, contentPosition, outOfBoundaryValue, length); this._updateLength(length); this._updateHanlderPosition(position); } } }, _updateHanlderPosition: function(position) { if (this.handle) { var oldPosition = this._fixupHandlerPosition(); this.handle.node.setPosition(position.x + oldPosition.x, position.y + oldPosition.y); } }, _fixupHandlerPosition: function() { var barSize = this.node.getContentSize(); var barAnchor = this.node.getAnchorPoint(); var handleSize = this.handle.node.getContentSize(); var handleParent = this.handle.node.parent; var leftBottomWorldPosition = this.node.convertToWorldSpaceAR(cc.v2(-barSize.width * barAnchor.x, -barSize.height * barAnchor.y)); var fixupPosition = handleParent.convertToNodeSpaceAR(leftBottomWorldPosition); 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() { if (!this.enableAutoHide) return; this._touching = true; }, _conditionalDisableScrollBar: function(contentSize, scrollViewSize) { if (contentSize.width <= scrollViewSize.width && this.direction === Direction.HORIZONTAL) return true; if (contentSize.height <= scrollViewSize.height && this.direction === Direction.VERTICAL) return true; return false; }, _onTouchEnded: function() { if (!this.enableAutoHide) return; this._touching = false; if (this.autoHideTime <= 0) return; if (this._scrollView) { var content = this._scrollView.content; if (content) { var contentSize = content.getContentSize(); var scrollViewSize = this._scrollView.node.getContentSize(); if (this._conditionalDisableScrollBar(contentSize, scrollViewSize)) return; } } this._autoHideRemainingTime = this.autoHideTime; }, _calculateLength: function(contentMeasure, scrollViewMeasure, handleNodeMeasure, outOfBoundary) { var denominatorValue = contentMeasure; outOfBoundary && (denominatorValue += (outOfBoundary > 0 ? outOfBoundary : -outOfBoundary) * GETTINGSHORTERFACTOR); var lengthRation = scrollViewMeasure / denominatorValue; return handleNodeMeasure * lengthRation; }, _calculatePosition: function(contentMeasure, scrollViewMeasure, handleNodeMeasure, contentPosition, outOfBoundary, actualLenth) { var denominatorValue = contentMeasure - scrollViewMeasure; 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(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(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() { this.enableAutoHide && this._setOpacity(0); }, hide: function() { this._autoHideRemainingTime = 0; this._setOpacity(0); }, show: function() { this._autoHideRemainingTime = this.autoHideTime; this._setOpacity(this._opacity); }, update: function(dt) { this._processAutoHide(dt); } }); cc.Scrollbar = module.exports = Scrollbar; }), { "../utils/misc": 243, "./CCComponent": 68 } ], 81: [ (function(require, module, exports) { 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 quintEaseOut = function(time) { time -= 1; return time * time * time * time * time + 1; }; var getTimeInMilliseconds = function() { 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() { 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(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: "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() { if (this.horizontalScrollBar) { this.horizontalScrollBar.setTargetScrollView(this); this._updateScrollBar(0); } }, animatable: false }, verticalScrollBar: { default: void 0, type: cc.Scrollbar, tooltip: false, notify: function() { 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() { if (this.content) return this.content.parent; } } }, statics: { EventType: EventType }, scrollToBottom: function(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(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(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(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(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(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(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(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(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() { var topDelta = this._getContentTopBoundary() - this._topBoundary; var leftDeta = this._getContentLeftBoundary() - this._leftBoundary; return cc.v2(leftDeta, topDelta); }, getMaxScrollOffset: function() { 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(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(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(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() { this._autoScrolling = false; this._autoScrollAccumulatedTime = this._autoScrollTotalTime; }, setContentPosition: function(position) { if (position.fuzzyEquals(this.getContentPosition(), EPSILON)) return; this.content.setPosition(position); this._outOfBoundaryAmountDirty = true; }, getContentPosition: function() { return this.content.getPosition(); }, isScrolling: function() { return this._scrolling; }, isAutoScrolling: function() { return this._autoScrolling; }, _registerEvent: function() { 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() { 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(event, captureListeners) { if (!this.enabledInHierarchy) return; if (this._hasNestedViewGroup(event, captureListeners)) return; var deltaMove = cc.v2(0, 0); var wheelPrecision = -.1; true; wheelPrecision = -7; 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(dt) { var currentOutOfBoundary = this._getHowMuchOutOfBoundary(); var maxElapsedTime = .1; if (!currentOutOfBoundary.fuzzyEquals(cc.v2(0, 0), EPSILON)) { this._processInertiaScroll(); this.unschedule(this._checkMouseWheel); this._stopMouseWheel = false; return; } this._mouseWheelEventElapsedTime += dt; if (this._mouseWheelEventElapsedTime > maxElapsedTime) { this._onScrollBarTouchEnded(); this.unschedule(this._checkMouseWheel); this._stopMouseWheel = false; } }, _calculateMovePercentDelta: function(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(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; this.verticalScrollBar && this.verticalScrollBar.hide(); } else this.verticalScrollBar && this.verticalScrollBar.show(); if (contentSize.width < scrollViewSize.width) { totalScrollDelta = contentSize.width - scrollViewSize.width; moveDelta.x = leftDeta; this.horizontalScrollBar && this.horizontalScrollBar.hide(); } else this.horizontalScrollBar && this.horizontalScrollBar.show(); this._moveContent(moveDelta); this._adjustContentOutOfBoundary(); }, _calculateBoundary: function() { 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(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(event) { event.eventPhase === cc.Event.AT_TARGET && event.target === this.node && event.stopPropagation(); }, _onTouchBegan: function(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(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(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(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(deltaMove) { this._scrollChildren(deltaMove); this._gatherTouchMove(deltaMove); }, _handleMoveLogic: function(touch) { var deltaMove = touch.getDelta(); this._processDeltaMove(deltaMove); }, _scrollChildren: function(deltaMove) { deltaMove = this._clampDelta(deltaMove); var realMove = deltaMove; var outOfBoundary = void 0; 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 scrollEventType = -1; if (realMove.y > 0) { var icBottomPos = this.content.y - this.content.anchorY * this.content.height; icBottomPos + realMove.y > this._bottomBoundary && (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 && (scrollEventType = "scroll-to-top"); } else if (realMove.x < 0) { var icRightPos = this.content.x - this.content.anchorX * this.content.width + this.content.width; icRightPos + realMove.x <= this._rightBoundary && (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 && (scrollEventType = "scroll-to-left"); } this._moveContent(realMove, false); if (0 !== realMove.x || 0 !== realMove.y) { if (!this._scrolling) { this._scrolling = true; this._dispatchEvent("scroll-began"); } this._dispatchEvent("scrolling"); } -1 !== scrollEventType && this._dispatchEvent(scrollEventType); }, _handlePressLogic: function() { 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(delta) { var contentSize = this.content.getContentSize(); var scrollViewSize = this.node.getContentSize(); contentSize.width < scrollViewSize.width && (delta.x = 0); contentSize.height < scrollViewSize.height && (delta.y = 0); return delta; }, _gatherTouchMove: function(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() { 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() { 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(touch) { var delta = touch.getDelta(); this._gatherTouchMove(delta); this._processInertiaScroll(); if (this._scrolling) { this._scrolling = false; this._autoScrolling || this._dispatchEvent("scroll-ended"); } }, _isOutOfBoundary: function() { var outOfBoundary = this._getHowMuchOutOfBoundary(); return !outOfBoundary.fuzzyEquals(cc.v2(0, 0), EPSILON); }, _isNecessaryAutoScrollBrake: function() { 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() { return EPSILON; }, _processAutoScrolling: function(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(touchMoveVelocity) { var inertiaTotalMovement = touchMoveVelocity.mul(MOVEMENT_FACTOR); this._startAttenuatingAutoScroll(inertiaTotalMovement, touchMoveVelocity); }, _calculateAttenuatedFactor: function(distance) { if (this.brake <= 0) return 1 - this.brake; return (1 - this.brake) * (1 / (1 + 14e-6 * distance + distance * distance * 8e-9)); }, _startAttenuatingAutoScroll: function(deltaMove, initialVelocity) { var time = this._calculateAutoScrollTimeByInitalSpeed(initialVelocity.mag()); var targetDelta = deltaMove.normalize(); var contentSize = this.content.getContentSize(); var scrollviewSize = this.node.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(initalSpeed) { return Math.sqrt(Math.sqrt(initalSpeed / 5)); }, _startAutoScroll: function(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() { 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(vector) { var result = vector; result.x = this.horizontal ? result.x : 0; result.y = this.vertical ? result.y : 0; return result; }, _moveContent: function(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() { var contentPos = this.getContentPosition(); return contentPos.x - this.content.getAnchorPoint().x * this.content.getContentSize().width; }, _getContentRightBoundary: function() { var contentSize = this.content.getContentSize(); return this._getContentLeftBoundary() + contentSize.width; }, _getContentTopBoundary: function() { var contentSize = this.content.getContentSize(); return this._getContentBottomBoundary() + contentSize.height; }, _getContentBottomBoundary: function() { var contentPos = this.getContentPosition(); return contentPos.y - this.content.getAnchorPoint().y * this.content.getContentSize().height; }, _getHowMuchOutOfBoundary: function(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; }, _updateScrollBar: function(outOfBoundary) { this.horizontalScrollBar && this.horizontalScrollBar._onScroll(outOfBoundary); this.verticalScrollBar && this.verticalScrollBar._onScroll(outOfBoundary); }, _onScrollBarTouchBegan: function() { this.horizontalScrollBar && this.horizontalScrollBar._onTouchBegan(); this.verticalScrollBar && this.verticalScrollBar._onTouchBegan(); }, _onScrollBarTouchEnded: function() { this.horizontalScrollBar && this.horizontalScrollBar._onTouchEnded(); this.verticalScrollBar && this.verticalScrollBar._onTouchEnded(); }, _dispatchEvent: function(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() { 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() { this._calculateBoundary(); this.content && cc.director.once(cc.Director.EVENT_BEFORE_DRAW, this._adjustContentOutOfBoundary, this); }, _hideScrollbar: function() { this.horizontalScrollBar && this.horizontalScrollBar.hide(); this.verticalScrollBar && this.verticalScrollBar.hide(); }, _showScrollbar: function() { this.horizontalScrollBar && this.horizontalScrollBar.show(); this.verticalScrollBar && this.verticalScrollBar.show(); }, onDisable: function() { 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() { 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._showScrollbar(); }, update: function(dt) { this._autoScrolling && this._processAutoScrolling(dt); } }); cc.ScrollView = module.exports = ScrollView; }), { "../CCNode": 30, "./CCViewGroup": 88 } ], 82: [ (function(require, module, exports) { 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() { this._offset = cc.v2(); this._touchHandle = false; this._dragging = false; }, properties: { handle: { default: null, type: cc.Button, tooltip: false, notify: function() { 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() { this._updateHandlePosition(); } }, slideEvents: { default: [], type: cc.Component.EventHandler, tooltip: false } }, statics: { Direction: Direction }, __preload: function() { this._updateHandlePosition(); }, onEnable: function() { this.node.on(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this); this.node.on(cc.Node.EventType.TOUCH_MOVE, this._onTouchMoved, this); this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this); this.node.on(cc.Node.EventType.TOUCH_CANCEL, this._onTouchCancelled, this); if (this.handle && this.handle.isValid) { this.handle.node.on(cc.Node.EventType.TOUCH_START, this._onHandleDragStart, this); this.handle.node.on(cc.Node.EventType.TOUCH_MOVE, this._onTouchMoved, this); this.handle.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this); } }, onDisable: function() { this.node.off(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this); this.node.off(cc.Node.EventType.TOUCH_MOVE, this._onTouchMoved, this); this.node.off(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this); this.node.off(cc.Node.EventType.TOUCH_CANCEL, this._onTouchCancelled, this); if (this.handle && this.handle.isValid) { this.handle.node.off(cc.Node.EventType.TOUCH_START, this._onHandleDragStart, this); this.handle.node.off(cc.Node.EventType.TOUCH_MOVE, this._onTouchMoved, this); this.handle.node.off(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this); } }, _onHandleDragStart: function(event) { this._dragging = true; this._touchHandle = true; this._offset = this.handle.node.convertToNodeSpaceAR(event.touch.getLocation()); event.stopPropagation(); }, _onTouchBegan: function(event) { if (!this.handle) return; this._dragging = true; this._touchHandle || this._handleSliderLogic(event.touch); event.stopPropagation(); }, _onTouchMoved: function(event) { if (!this._dragging) return; this._handleSliderLogic(event.touch); event.stopPropagation(); }, _onTouchEnded: function(event) { this._dragging = false; this._touchHandle = false; this._offset = cc.v2(); event.stopPropagation(); }, _onTouchCancelled: function(event) { this._dragging = false; event.stopPropagation(); }, _handleSliderLogic: function(touch) { this._updateProgress(touch); this._emitSlideEvent(); }, _emitSlideEvent: function() { cc.Component.EventHandler.emitEvents(this.slideEvents, this); this.node.emit("slide", this); }, _updateProgress: function(touch) { if (!this.handle) return; var localTouchPos = this.node.convertToNodeSpaceAR(touch.getLocation()); this.direction === Direction.Horizontal ? this.progress = misc.clamp01(.5 + (localTouchPos.x - this._offset.x) / this.node.width) : this.progress = misc.clamp01(.5 + (localTouchPos.y - this._offset.y) / this.node.height); }, _updateHandlePosition: function() { 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": 243, "./CCComponent": 68 } ], 83: [ (function(require, module, exports) { var misc = require("../utils/misc"); var NodeEvent = require("../CCNode").EventType; var RenderComponent = require("./CCRenderComponent"); var RenderFlow = require("../renderer/render-flow"); var renderEngine = require("../renderer/render-engine"); var gfx = renderEngine.gfx; var SpriteMaterial = renderEngine.SpriteMaterial; var GraySpriteMaterial = renderEngine.GraySpriteMaterial; var dynamicAtlasManager = require("../renderer/utils/dynamic-atlas/manager"); var BlendFactor = require("../platform/CCMacro").BlendFactor; 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, ctor: function() { this._assembler = null; this._graySpriteMaterial = null; this._spriteMaterial = null; }, 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, _state: 0, _atlas: { default: null, type: cc.SpriteAtlas, tooltip: false, editorOnly: true, visible: true, animatable: false }, _srcBlendFactor: BlendFactor.SRC_ALPHA, _dstBlendFactor: BlendFactor.ONE_MINUS_SRC_ALPHA, srcBlendFactor: { get: function() { return this._srcBlendFactor; }, set: function(value) { if (this._srcBlendFactor === value) return; this._srcBlendFactor = value; this._updateBlendFunc(true); }, animatable: false, type: BlendFactor, tooltip: false }, dstBlendFactor: { get: function() { return this._dstBlendFactor; }, set: function(value) { if (this._dstBlendFactor === value) return; this._dstBlendFactor = value; this._updateBlendFunc(true); }, animatable: false, type: BlendFactor, tooltip: false }, spriteFrame: { get: function() { return this._spriteFrame; }, set: function(value, force) { var lastSprite = this._spriteFrame; false; if (lastSprite === value) return; this._spriteFrame = value; this.markForUpdateRenderData(false); this._applySpriteFrame(lastSprite); false; }, type: cc.SpriteFrame }, type: { get: function() { return this._type; }, set: function(value) { if (this._type !== value) { this.destroyRenderData(this._renderData); this._renderData = null; this._type = value; this._updateAssembler(); } }, type: SpriteType, animatable: false, tooltip: false }, fillType: { get: function() { return this._fillType; }, set: function(value) { if (value !== this._fillType) { if (value === FillType.RADIAL || this._fillType === FillType.RADIAL) { this.destroyRenderData(this._renderData); this._renderData = null; } else this._renderData && this.markForUpdateRenderData(true); this._fillType = value; this._updateAssembler(); } }, type: FillType, tooltip: false }, fillCenter: { get: function() { return this._fillCenter; }, set: function(value) { this._fillCenter.x = value.x; this._fillCenter.y = value.y; this._type === SpriteType.FILLED && this._renderData && this.markForUpdateRenderData(true); }, tooltip: false }, fillStart: { get: function() { return this._fillStart; }, set: function(value) { this._fillStart = misc.clampf(value, -1, 1); this._type === SpriteType.FILLED && this._renderData && this.markForUpdateRenderData(true); }, tooltip: false }, fillRange: { get: function() { return this._fillRange; }, set: function(value) { this._fillRange = misc.clampf(value, -1, 1); this._type === SpriteType.FILLED && this._renderData && this.markForUpdateRenderData(true); }, tooltip: false }, trim: { get: function() { return this._isTrimmedMode; }, set: function(value) { if (this._isTrimmedMode !== value) { this._isTrimmedMode = value; this._type !== SpriteType.SIMPLE && this._type !== SpriteType.MESH || !this._renderData || this.markForUpdateRenderData(true); } }, animatable: false, tooltip: false }, sizeMode: { get: function() { return this._sizeMode; }, set: function(value) { this._sizeMode = value; value !== SizeMode.CUSTOM && this._applySpriteSize(); }, animatable: false, type: SizeMode, tooltip: false } }, statics: { FillType: FillType, Type: SpriteType, SizeMode: SizeMode, State: State }, setVisible: function(visible) { this.enabled = visible; }, setState: function(state) { if (this._state === state) return; this._state = state; this._activateMaterial(); }, getState: function() { return this._state; }, onEnable: function() { this._super(); if (!this._spriteFrame || !this._spriteFrame.textureLoaded()) { this.disableRender(); if (this._spriteFrame) { this._spriteFrame.once("load", this._onTextureLoaded, this); this._spriteFrame.ensureLoadTexture(); } } this._updateAssembler(); this._activateMaterial(); this.node.on(NodeEvent.SIZE_CHANGED, this._onNodeSizeDirty, this); this.node.on(NodeEvent.ANCHOR_CHANGED, this._onNodeSizeDirty, this); }, onDisable: function() { this._super(); this.node.off(NodeEvent.SIZE_CHANGED, this._onNodeSizeDirty, this); this.node.off(NodeEvent.ANCHOR_CHANGED, this._onNodeSizeDirty, this); }, _onNodeSizeDirty: function() { if (!this._renderData) return; this.markForUpdateRenderData(true); }, _updateAssembler: function() { var assembler = Sprite._assembler.getAssembler(this); if (this._assembler !== assembler) { this._assembler = assembler; this._renderData = null; } if (!this._renderData) { this._renderData = this._assembler.createData(this); this._renderData.material = this._material; this.markForUpdateRenderData(true); } }, _activateMaterial: function() { var spriteFrame = this._spriteFrame; if (cc.game.renderType !== cc.game.RENDER_TYPE_CANVAS) { var material = void 0; if (this._state === State.GRAY) { this._graySpriteMaterial || (this._graySpriteMaterial = new GraySpriteMaterial()); material = this._graySpriteMaterial; } else { this._spriteMaterial || (this._spriteMaterial = new SpriteMaterial()); material = this._spriteMaterial; } material.useColor = false; if (spriteFrame && spriteFrame.textureLoaded()) { var texture = spriteFrame.getTexture(); if (material.texture !== texture) { material.texture = texture; this._updateMaterial(material); } else material !== this._material && this._updateMaterial(material); this._renderData && (this._renderData.material = material); this.node._renderFlag |= RenderFlow.FLAG_COLOR; this.markForUpdateRenderData(true); this.markForRender(true); } else this.disableRender(); } else { this.markForUpdateRenderData(true); this.markForRender(true); } }, _updateMaterial: function(material) { this._material = material; this._updateBlendFunc(); material.updateHash(); }, _updateBlendFunc: function(updateHash) { if (this._material) { var pass = this._material._mainTech.passes[0]; pass.setBlend(gfx.BLEND_FUNC_ADD, this._srcBlendFactor, this._dstBlendFactor, gfx.BLEND_FUNC_ADD, this._srcBlendFactor, this._dstBlendFactor); updateHash && this._material.updateHash(); } }, _applyAtlas: false, _canRender: function() { if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) { if (!this._enabled) return false; } else if (!this._enabled || !this._material || !this.node._activeInHierarchy) return false; var spriteFrame = this._spriteFrame; if (!spriteFrame || !spriteFrame.textureLoaded()) return false; return true; }, markForUpdateRenderData: function(enable) { if (enable && this._canRender()) { this.node._renderFlag |= RenderFlow.FLAG_UPDATE_RENDER_DATA; var renderData = this._renderData; if (renderData) { renderData.uvDirty = true; renderData.vertDirty = true; } } else enable || (this.node._renderFlag &= ~RenderFlow.FLAG_UPDATE_RENDER_DATA); }, _applySpriteSize: function() { if (this._spriteFrame) { if (SizeMode.RAW === this._sizeMode) { var size = this._spriteFrame.getOriginalSize(); this.node.setContentSize(size); } else if (SizeMode.TRIMMED === this._sizeMode) { var rect = this._spriteFrame.getRect(); this.node.setContentSize(rect.width, rect.height); } this._activateMaterial(); } }, _onTextureLoaded: function() { if (!this.isValid) return; this._applySpriteSize(); }, _applySpriteFrame: function(oldFrame) { oldFrame && oldFrame.off && oldFrame.isValid && oldFrame.off("load", this._onTextureLoaded, this); var spriteFrame = this._spriteFrame; spriteFrame && (this._material && this._material._texture) === (spriteFrame && spriteFrame._texture) || this.markForRender(false); if (spriteFrame) if (oldFrame && spriteFrame._texture === oldFrame._texture) this._applySpriteSize(); else if (spriteFrame.textureLoaded()) this._onTextureLoaded(null); else { spriteFrame.once("load", this._onTextureLoaded, this); spriteFrame.ensureLoadTexture(); } false; }, _resized: false, _calDynamicAtlas: function() { if (!this._spriteFrame) return; if (!this._spriteFrame._original && dynamicAtlasManager) { var frame = dynamicAtlasManager.insertSpriteFrame(this._spriteFrame); frame && this._spriteFrame._setDynamicAtlasFrame(frame); } this._material._texture !== this._spriteFrame._texture && this._activateMaterial(); } }); false; cc.Sprite = module.exports = Sprite; }), { "../CCNode": 30, "../platform/CCMacro": 166, "../renderer/render-engine": 203, "../renderer/render-flow": 204, "../renderer/utils/dynamic-atlas/manager": 206, "../utils/misc": 243, "./CCRenderComponent": 78 } ], 84: [ (function(require, module, exports) { var ComponentType = cc.Enum({ NONE: 0, CHECKBOX: 1, TEXT_ATLAS: 2, SLIDER_BAR: 3, LIST_VIEW: 4, PAGE_VIEW: 5 }); var ListDirection = cc.Enum({ VERTICAL: 0, HORIZONTAL: 1 }); var VerticalAlign = cc.Enum({ TOP: 0, CENTER: 1, BOTTOM: 2 }); var HorizontalAlign = cc.Enum({ LEFT: 0, CENTER: 1, RIGHT: 2 }); var StudioComponent = cc.Class({ name: "cc.StudioComponent", extends: cc.Component, editor: false, properties: false, statics: { ComponentType: ComponentType, ListDirection: ListDirection, VerticalAlign: VerticalAlign, HorizontalAlign: HorizontalAlign } }); var PrefabHelper = require("../utils/prefab-helper"); StudioComponent.PlaceHolder = cc.Class({ name: "cc.StudioComponent.PlaceHolder", extends: cc.Component, properties: { _baseUrl: "", nestedPrefab: cc.Prefab }, onLoad: function() { if (!this.nestedPrefab) { false; return; } this._replaceWithNestedPrefab(); }, _replaceWithNestedPrefab: function() { var node = this.node; var _prefab = node._prefab; _prefab.root = node; _prefab.asset = this.nestedPrefab; PrefabHelper.syncWithPrefab(node); } }); cc.StudioComponent = module.exports = StudioComponent; var StudioWidget = cc.Class({ name: "cc.StudioWidget", extends: cc.Widget, editor: false, _validateTargetInDEV: function() {} }); cc.StudioWidget = module.exports = StudioWidget; }), { "../utils/prefab-helper": 246 } ], 85: [ (function(require, module, exports) { var Toggle = cc.Class({ name: "cc.Toggle", extends: require("./CCButton"), editor: false, properties: { _N$isChecked: true, isChecked: { get: function() { return this._N$isChecked; }, set: function(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); 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(value) { value && this._resizeNodeToTargetNode(); } } }, onEnable: function() { this._super(); true; this._registerToggleEvent(); this.toggleGroup && this.toggleGroup.enabledInHierarchy && this.toggleGroup.addToggle(this); }, onDisable: function() { this._super(); true; this._unregisterToggleEvent(); this.toggleGroup && this.toggleGroup.enabledInHierarchy && this.toggleGroup.removeToggle(this); }, _hideCheckMark: function() { this._N$isChecked = false; this._updateCheckMark(); }, toggle: function(event) { this.isChecked = !this.isChecked; }, check: function() { this.isChecked = true; }, uncheck: function() { this.isChecked = false; }, _updateCheckMark: function() { this.checkMark && (this.checkMark.node.active = !!this.isChecked); }, _updateDisabledState: function() { this._super(); this.checkMark && this.checkMark.setState(0); this.enableAutoGrayEffect && this.checkMark && !this.interactable && this.checkMark.setState(1); }, _registerToggleEvent: function() { this.node.on("click", this.toggle, this); }, _unregisterToggleEvent: function() { this.node.off("click", this.toggle, this); }, _emitToggleEvents: function() { 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": 181, "./CCButton": 66, "./CCToggleGroup": 87 } ], 86: [ (function(require, module, exports) { 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(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() { var isChecked = false; this.toggleItems.forEach((function(item) { isChecked ? item._hideCheckMark() : item.isChecked && (isChecked = true); })); return isChecked; }, _makeAtLeastOneToggleChecked: function() { var isChecked = this._allowOnlyOneToggleChecked(); if (!isChecked && !this.allowSwitchOff) { var toggleItems = this.toggleItems; toggleItems.length > 0 && toggleItems[0].check(); } }, onEnable: function() { this.node.on("child-added", this._allowOnlyOneToggleChecked, this); this.node.on("child-removed", this._makeAtLeastOneToggleChecked, this); }, onDisable: function() { this.node.off("child-added", this._allowOnlyOneToggleChecked, this); this.node.off("child-removed", this._makeAtLeastOneToggleChecked, this); }, start: function() { this._makeAtLeastOneToggleChecked(); } }); var js = require("../platform/js"); js.get(ToggleContainer.prototype, "toggleItems", (function() { return this.node.getComponentsInChildren(cc.Toggle); })); cc.ToggleContainer = module.exports = ToggleContainer; }), { "../platform/js": 181 } ], 87: [ (function(require, module, exports) { var ToggleGroup = cc.Class({ name: "cc.ToggleGroup", extends: cc.Component, ctor: function() { this._toggleItems = []; }, editor: false, properties: { allowSwitchOff: { tooltip: false, default: false }, toggleItems: { get: function() { return this._toggleItems; } } }, updateToggles: function(toggle) { if (!this.enabledInHierarchy) return; this._toggleItems.forEach((function(item) { toggle.isChecked && item !== toggle && item.isChecked && item.enabled && item._hideCheckMark(); })); }, addToggle: function(toggle) { var index = this._toggleItems.indexOf(toggle); -1 === index && this._toggleItems.push(toggle); this._allowOnlyOneToggleChecked(); }, removeToggle: function(toggle) { var index = this._toggleItems.indexOf(toggle); index > -1 && this._toggleItems.splice(index, 1); this._makeAtLeastOneToggleChecked(); }, _allowOnlyOneToggleChecked: function() { var isChecked = false; this._toggleItems.forEach((function(item) { isChecked && item.enabled && item._hideCheckMark(); item.isChecked && item.enabled && (isChecked = true); })); return isChecked; }, _makeAtLeastOneToggleChecked: function() { var isChecked = this._allowOnlyOneToggleChecked(); isChecked || this.allowSwitchOff || this._toggleItems.length > 0 && (this._toggleItems[0].isChecked = true); }, start: function() { this._makeAtLeastOneToggleChecked(); } }); var js = require("../platform/js"); var showed = false; js.get(cc, "ToggleGroup", (function() { if (!showed) { cc.logID(1405, "cc.ToggleGroup", "cc.ToggleContainer"); showed = true; } return ToggleGroup; })); module.exports = ToggleGroup; }), { "../platform/js": 181 } ], 88: [ (function(require, module, exports) { var ViewGroup = cc.Class({ name: "cc.ViewGroup", extends: require("./CCComponent") }); cc.ViewGroup = module.exports = ViewGroup; }), { "./CCComponent": 68 } ], 89: [ (function(require, module, exports) { 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() { return this._target; }, set: function(value) { this._target = value; false; }, type: cc.Node, tooltip: false }, isAlignTop: { get: function() { return (this._alignFlags & TOP) > 0; }, set: function(value) { this._setAlign(TOP, value); }, animatable: false, tooltip: false }, isAlignVerticalCenter: { get: function() { return (this._alignFlags & MID) > 0; }, set: function(value) { if (value) { this.isAlignTop = false; this.isAlignBottom = false; this._alignFlags |= MID; } else this._alignFlags &= ~MID; }, animatable: false, tooltip: false }, isAlignBottom: { get: function() { return (this._alignFlags & BOT) > 0; }, set: function(value) { this._setAlign(BOT, value); }, animatable: false, tooltip: false }, isAlignLeft: { get: function() { return (this._alignFlags & LEFT) > 0; }, set: function(value) { this._setAlign(LEFT, value); }, animatable: false, tooltip: false }, isAlignHorizontalCenter: { get: function() { return (this._alignFlags & CENTER) > 0; }, set: function(value) { if (value) { this.isAlignLeft = false; this.isAlignRight = false; this._alignFlags |= CENTER; } else this._alignFlags &= ~CENTER; }, animatable: false, tooltip: false }, isAlignRight: { get: function() { return (this._alignFlags & RIGHT) > 0; }, set: function(value) { this._setAlign(RIGHT, value); }, animatable: false, tooltip: false }, isStretchWidth: { get: function() { return (this._alignFlags & LEFT_RIGHT) === LEFT_RIGHT; }, visible: false }, isStretchHeight: { get: function() { return (this._alignFlags & TOP_BOT) === TOP_BOT; }, visible: false }, top: { get: function() { return this._top; }, set: function(value) { this._top = value; }, tooltip: false }, bottom: { get: function() { return this._bottom; }, set: function(value) { this._bottom = value; }, tooltip: false }, left: { get: function() { return this._left; }, set: function(value) { this._left = value; }, tooltip: false }, right: { get: function() { return this._right; }, set: function(value) { this._right = value; }, tooltip: false }, horizontalCenter: { get: function() { return this._horizontalCenter; }, set: function(value) { this._horizontalCenter = value; }, tooltip: false }, verticalCenter: { get: function() { return this._verticalCenter; }, set: function(value) { this._verticalCenter = value; }, tooltip: false }, isAbsoluteHorizontalCenter: { get: function() { return this._isAbsHorizontalCenter; }, set: function(value) { this._isAbsHorizontalCenter = value; }, animatable: false }, isAbsoluteVerticalCenter: { get: function() { return this._isAbsVerticalCenter; }, set: function(value) { this._isAbsVerticalCenter = value; }, animatable: false }, isAbsoluteTop: { get: function() { return this._isAbsTop; }, set: function(value) { this._isAbsTop = value; }, animatable: false }, isAbsoluteBottom: { get: function() { return this._isAbsBottom; }, set: function(value) { this._isAbsBottom = value; }, animatable: false }, isAbsoluteLeft: { get: function() { return this._isAbsLeft; }, set: function(value) { this._isAbsLeft = value; }, animatable: false }, isAbsoluteRight: { get: function() { return this._isAbsRight; }, set: function(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() { if (void 0 !== this._wasAlignOnce) { this.alignMode = this._wasAlignOnce ? AlignMode.ONCE : AlignMode.ALWAYS; this._wasAlignOnce = void 0; } }, onEnable: function() { WidgetManager.add(this); }, onDisable: function() { WidgetManager.remove(this); }, _validateTargetInDEV: false, _setAlign: function(flag, isAlign) { var current = (this._alignFlags & flag) > 0; if (isAlign === current) return; var isHorizontal = (flag & LEFT_RIGHT) > 0; if (isAlign) { this._alignFlags |= flag; if (isHorizontal) { this.isAlignHorizontalCenter = false; if (this.isStretchWidth) { 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() { WidgetManager.updateAlignment(this.node); } }); Object.defineProperty(Widget.prototype, "isAlignOnce", { get: function() { true; cc.warn("`widget.isAlignOnce` is deprecated, use `widget.alignMode === cc.Widget.AlignMode.ONCE` instead please."); return this.alignMode === AlignMode.ONCE; }, set: function(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": 52, "./CCComponent": 68 } ], 90: [ (function(require, module, exports) { var Component = require("./CCComponent"); var SwanSubContextView = void 0; var isBaiduGame = cc.sys.platform === cc.sys.BAIDU_GAME; true, SwanSubContextView = isBaiduGame ? cc.Class({ name: "cc.SwanSubContextView", extends: Component, editor: false, ctor: function() { this._sprite = null; this._tex = new cc.Texture2D(); this._context = null; }, onLoad: function() { if (swan.getOpenDataContext) { this._context = swan.getOpenDataContext(); var sharedCanvas = this._context.canvas; if (sharedCanvas) { sharedCanvas.width = this.node.width; sharedCanvas.height = this.node.height; } this._tex.setPremultiplyAlpha(true); this._tex.initWithElement(sharedCanvas); this._sprite = this.node.getComponent(cc.Sprite); if (!this._sprite) { this._sprite = this.node.addComponent(cc.Sprite); this._sprite.srcBlendFactor = cc.macro.BlendFactor.ONE; } this._sprite.spriteFrame = new cc.SpriteFrame(this._tex); } else this.enabled = false; }, onEnable: function() { this.updateSubContextViewport(); }, update: function() { if (!this._tex || !this._context) return; this._tex.initWithElement(this._context.canvas); this._sprite._activateMaterial(); }, updateSubContextViewport: function() { if (this._context) { var box = this.node.getBoundingBoxToWorld(); var sx = cc.view._scaleX; var sy = cc.view._scaleY; this._context.postMessage({ fromEngine: true, event: "viewport", x: box.x * sx + cc.view._viewportRect.x, y: box.y * sy + cc.view._viewportRect.y, width: box.width * sx, height: box.height * sy }); } } }) : cc.Class({ name: "cc.SwanSubContextView", extends: Component }); cc.SwanSubContextView = module.exports = SwanSubContextView; }), { "./CCComponent": 68 } ], 91: [ (function(require, module, exports) { var Component = require("./CCComponent"); var WXSubContextView = void 0; true, true; WXSubContextView = cc.Class({ name: "cc.WXSubContextView", extends: Component }); cc.WXSubContextView = module.exports = WXSubContextView; }), { "./CCComponent": 68 } ], 92: [ (function(require, module, exports) { var macro = require("../../platform/CCMacro"); var EditBoxImpl = require("../editbox/CCEditBoxImpl"); var Label = require("../CCLabel"); var Types = require("./types"); var InputMode = Types.InputMode; var InputFlag = Types.InputFlag; var KeyboardReturnType = Types.KeyboardReturnType; var LEFT_PADDING = 2; function capitalize(string) { return string.replace(/(?:^|\s)\S/g, (function(a) { return a.toUpperCase(); })); } function capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); } var EditBox = cc.Class({ name: "cc.EditBox", extends: cc.Component, editor: false, properties: { _useOriginalSize: true, _string: "", string: { tooltip: false, get: function() { return this._string; }, set: function(value) { this.maxLength >= 0 && value.length >= this.maxLength && (value = value.slice(0, this.maxLength)); this._string = value; this._impl && this._updateString(value); } }, backgroundImage: { tooltip: false, default: null, type: cc.SpriteFrame, notify: function() { this._createBackgroundSprite(); } }, returnType: { default: KeyboardReturnType.DEFAULT, tooltip: false, displayName: "KeyboardReturnType", type: KeyboardReturnType, notify: function() { this._impl && (this._impl.returnType = this.returnType); } }, inputFlag: { tooltip: false, default: InputFlag.DEFAULT, type: InputFlag, notify: function() { if (this._impl) { this._impl.setInputFlag(this.inputFlag); this._updateString(this._string); } } }, inputMode: { tooltip: false, default: InputMode.ANY, type: InputMode, notify: function() { this._impl && this._impl.setInputMode(this.inputMode); } }, fontSize: { tooltip: false, default: 20, notify: function() { this._textLabel && (this._textLabel.fontSize = this.fontSize); this._impl && this._impl.setFontSize(this.fontSize); } }, lineHeight: { tooltip: false, default: 40, notify: function() { this._textLabel && (this._textLabel.lineHeight = this.lineHeight); } }, fontColor: { tooltip: false, default: cc.Color.WHITE, notify: function() { if (this._textLabel) { this._textLabel.node.opacity = this.fontColor.a; this._textLabel.node.color = this.fontColor; } this._impl && this._impl.setFontColor(this.fontColor); } }, placeholder: { tooltip: false, default: "Enter text here...", notify: function() { this._placeholderLabel && (this._placeholderLabel.string = this.placeholder); this._impl && this._impl.setPlaceholderText(this.placeholder); } }, placeholderFontSize: { tooltip: false, default: 20, notify: function() { this._placeholderLabel && (this._placeholderLabel.fontSize = this.placeholderFontSize); } }, placeholderFontColor: { tooltip: false, default: cc.Color.GRAY, notify: function() { if (this._placeholderLabel) { this._placeholderLabel.node.color = this.placeholderFontColor; this._placeholderLabel.node.opacity = this.placeholderFontColor.a; } } }, maxLength: { tooltip: false, default: 20, notify: function() { this._impl && this._impl.setMaxLength(this.maxLength); } }, stayOnTop: { tooltip: false, default: false, notify: function() { this._impl && this._updateStayOnTop(); } }, _tabIndex: 0, tabIndex: { tooltip: false, get: function() { return this._tabIndex; }, set: function(value) { this._tabIndex = value; this._impl && this._impl.setTabIndex(value); } }, editingDidBegan: { default: [], type: cc.Component.EventHandler }, textChanged: { default: [], type: cc.Component.EventHandler }, editingDidEnded: { default: [], type: cc.Component.EventHandler }, editingReturn: { default: [], type: cc.Component.EventHandler } }, statics: { _EditBoxImpl: EditBoxImpl, KeyboardReturnType: KeyboardReturnType, InputFlag: InputFlag, InputMode: InputMode }, _init: function() { this._createBackgroundSprite(); this._createLabels(); this.node.on(cc.Node.EventType.SIZE_CHANGED, this._resizeChildNodes, this); var impl = this._impl = new EditBoxImpl(); impl.setDelegate(this); impl.setNode(this.node); impl.setInputMode(this.inputMode); impl.setMaxLength(this.maxLength); impl.setInputFlag(this.inputFlag); impl.setReturnType(this.returnType); impl.setTabIndex(this.tabIndex); impl.setFontColor(this.fontColor); impl.setFontSize(this.fontSize); impl.setPlaceholderText(this.placeholder); this._updateStayOnTop(); this._updateString(this.string); this._syncSize(); }, _updateStayOnTop: function() { this.stayOnTop ? this._hideLabels() : this._showLabels(); this._impl.stayOnTop(this.stayOnTop); }, _syncSize: function() { var size = this.node.getContentSize(); this._background.node.setAnchorPoint(this.node.getAnchorPoint()); this._background.node.setContentSize(size); this._updateLabelPosition(size); this._impl.setSize(size.width, size.height); }, _updateLabelPosition: function(size) { var node = this.node; var offx = -node.anchorX * node.width; var offy = -node.anchorY * node.height; var placeholderLabel = this._placeholderLabel; var textLabel = this._textLabel; textLabel.node.setContentSize(size.width - LEFT_PADDING, size.height); placeholderLabel.node.setContentSize(size.width - LEFT_PADDING, size.height); placeholderLabel.lineHeight = size.height; placeholderLabel.node.setPosition(offx + LEFT_PADDING, offy + size.height); textLabel.node.setPosition(offx + LEFT_PADDING, offy + size.height); if (this.inputMode === InputMode.ANY) { placeholderLabel.verticalAlign = macro.VerticalTextAlignment.TOP; placeholderLabel.enableWrapText = true; textLabel.verticalAlign = macro.VerticalTextAlignment.TOP; textLabel.enableWrapText = true; } else { placeholderLabel.verticalAlign = macro.VerticalTextAlignment.CENTER; placeholderLabel.enableWrapText = false; textLabel.verticalAlign = macro.VerticalTextAlignment.CENTER; textLabel.enableWrapText = false; } }, _createBackgroundSprite: function() { var background = this._background; if (!background) { var node = this.node.getChildByName("BACKGROUND_SPRITE"); node || (node = new cc.Node("BACKGROUND_SPRITE")); background = node.getComponent(cc.Sprite); background || (background = node.addComponent(cc.Sprite)); background.type = cc.Sprite.Type.SLICED; node.parent = this.node; this._background = background; } background.spriteFrame = this.backgroundImage; }, _createLabels: function() { if (!this._textLabel) { var node = this.node.getChildByName("TEXT_LABEL"); node || (node = new cc.Node("TEXT_LABEL")); node.color = this.fontColor; node.parent = this.node; node.setAnchorPoint(0, 1); var textLabel = node.getComponent(Label); textLabel || (textLabel = node.addComponent(Label)); textLabel.overflow = Label.Overflow.CLAMP; textLabel.fontSize = this.fontSize; textLabel.lineHeight = this.lineHeight; this._textLabel = textLabel; } if (!this._placeholderLabel) { var _node = this.node.getChildByName("PLACEHOLDER_LABEL"); _node || (_node = new cc.Node("PLACEHOLDER_LABEL")); _node.color = this.placeholderFontColor; _node.parent = this.node; _node.setAnchorPoint(0, 1); var placeholderLabel = _node.getComponent(Label); placeholderLabel || (placeholderLabel = _node.addComponent(Label)); placeholderLabel.overflow = Label.Overflow.CLAMP; placeholderLabel.fontSize = this.placeholderFontSize; placeholderLabel.string = this.placeholder; this._placeholderLabel = placeholderLabel; } }, _resizeChildNodes: function() { var textLabelNode = this._textLabel.node, placeholderLabelNode = this._placeholderLabel.node, backgroundNode = this._background.node; textLabelNode.x = -this.node.width / 2; textLabelNode.y = this.node.height / 2; textLabelNode.width = this.node.width; textLabelNode.height = this.node.height; placeholderLabelNode.x = -this.node.width / 2; placeholderLabelNode.y = this.node.height / 2; placeholderLabelNode.width = this.node.width; placeholderLabelNode.height = this.node.height; backgroundNode.width = this.node.width; backgroundNode.height = this.node.height; }, _showLabels: function() { var displayText = this._textLabel.string; this._textLabel.node.active = "" !== displayText; this._placeholderLabel.node.active = "" === displayText; }, _hideLabels: function() { this._textLabel.node.active = false; this._placeholderLabel.node.active = false; }, _updateString: function(text) { var textLabel = this._textLabel; if (!textLabel) return; var displayText = text; displayText && (displayText = this._updateLabelStringStyle(displayText)); textLabel.string = displayText; this._impl.setString(text); this._impl._editing || this.stayOnTop || this._showLabels(); }, _updateLabelStringStyle: function(text, ignorePassword) { var inputFlag = this.inputFlag; if (ignorePassword || inputFlag !== InputFlag.PASSWORD) inputFlag === InputFlag.INITIAL_CAPS_ALL_CHARACTERS ? text = text.toUpperCase() : inputFlag === InputFlag.INITIAL_CAPS_WORD ? text = capitalize(text) : inputFlag === InputFlag.INITIAL_CAPS_SENTENCE && (text = capitalizeFirstLetter(text)); else { var passwordString = ""; var len = text.length; for (var i = 0; i < len; ++i) passwordString += "\u25cf"; text = passwordString; } return text; }, editBoxEditingDidBegan: function() { this._hideLabels(); cc.Component.EventHandler.emitEvents(this.editingDidBegan, this); this.node.emit("editing-did-began", this); }, editBoxEditingDidEnded: function() { this.stayOnTop || this._showLabels(); cc.Component.EventHandler.emitEvents(this.editingDidEnded, this); this.node.emit("editing-did-ended", this); }, editBoxTextChanged: function(text) { text = this._updateLabelStringStyle(text, true); this.string = text; cc.Component.EventHandler.emitEvents(this.textChanged, text, this); this.node.emit("text-changed", this); }, editBoxEditingReturn: function() { cc.Component.EventHandler.emitEvents(this.editingReturn, this); this.node.emit("editing-return", this); }, onDestroy: function() { this._impl.clear(); }, onEnable: function() { this._impl && this._impl.onEnable(); }, onDisable: function() { this._impl && this._impl.onDisable(); }, __preload: function() { true; this._registerEvent(); this._init(); }, _registerEvent: function() { this.node.on(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this); this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this); }, _onTouchBegan: function(event) { this._impl && this._impl._onTouchBegan(event.touch); event.stopPropagation(); }, _onTouchCancel: function(event) { this._impl && this._impl._onTouchCancel(); event.stopPropagation(); }, _onTouchEnded: function(event) { this._impl && this._impl._onTouchEnded(); event.stopPropagation(); }, setFocus: function() { this._impl && this._impl.setFocus(); }, isFocused: function() { var isFocused = false; this._impl && (isFocused = this._impl.isFocused()); return isFocused; }, update: function() { this._impl && this._impl.update(); } }); cc.EditBox = module.exports = EditBox; }), { "../../platform/CCMacro": 166, "../CCLabel": 70, "../editbox/CCEditBoxImpl": 93, "./types": 94 } ], 93: [ (function(require, module, exports) { var utils = require("../../platform/utils"); var macro = require("../../platform/CCMacro"); var Types = require("./types"); var InputMode = Types.InputMode; var InputFlag = Types.InputFlag; var KeyboardReturnType = Types.KeyboardReturnType; var SCROLLY = 40; var LEFT_PADDING = 2; var DELAY_TIME = 400; var FOCUS_DELAY_UC = 400; var FOCUS_DELAY_FIREFOX = 0; var math = cc.vmath; var _worldMat = math.mat4.create(); var _cameraMat = math.mat4.create(); var _vec3 = cc.v3(); var _currentEditBoxImpl = null; var polyfill = { zoomInvalid: false }; cc.sys.OS_ANDROID !== cc.sys.os || cc.sys.browserType !== cc.sys.BROWSER_TYPE_SOUGOU && cc.sys.browserType !== cc.sys.BROWSER_TYPE_360 || (polyfill.zoomInvalid = true); function getKeyboardReturnType(type) { switch (type) { case KeyboardReturnType.DEFAULT: case KeyboardReturnType.DONE: return "done"; case KeyboardReturnType.SEND: return "send"; case KeyboardReturnType.SEARCH: return "search"; case KeyboardReturnType.GO: return "go"; case KeyboardReturnType.NEXT: return "next"; } return "done"; } var EditBoxImpl = cc.Class({ ctor: function() { this._delegate = null; this._inputMode = -1; this._inputFlag = -1; this._returnType = KeyboardReturnType.DEFAULT; this._maxLength = 50; this._text = ""; this._placeholderText = ""; this._alwaysOnTop = false; this._size = cc.size(); this._node = null; this._editing = false; this.__eventListeners = {}; this.__fullscreen = false; this.__autoResize = false; this.__rotateScreen = false; this.__orientationChanged = null; this._m00 = 0; this._m01 = 0; this._m04 = 0; this._m05 = 0; this._m12 = 0; this._m13 = 0; this._w = 0; this._h = 0; }, onEnable: function() { if (!this._edTxt) return; this._alwaysOnTop ? this._edTxt.style.display = "" : this._edTxt.style.display = "none"; }, onDisable: function() { if (!this._edTxt) return; this._edTxt.style.display = "none"; }, setTabIndex: function(index) { this._edTxt && (this._edTxt.tabIndex = index); }, setFocus: function() { this._beginEditing(); }, isFocused: function() { if (this._edTxt) return document.activeElement === this._edTxt; cc.warnID(4700); return false; }, stayOnTop: function(flag) { if (this._alwaysOnTop === flag || !this._edTxt) return; this._alwaysOnTop = flag; this._edTxt.style.display = flag ? "" : "none"; }, setMaxLength: function(maxLength) { if (!isNaN(maxLength)) { maxLength < 0 && (maxLength = 65535); this._maxLength = maxLength; this._edTxt && (this._edTxt.maxLength = maxLength); } }, setString: function(text) { this._text = text; this._edTxt && (this._edTxt.value = text); }, getString: function() { return this._text; }, setPlaceholderText: function(text) { this._placeholderText = text; }, getPlaceholderText: function() { return this._placeholderText; }, setDelegate: function(delegate) { this._delegate = delegate; }, setInputMode: function(inputMode) { if (this._inputMode === inputMode) return; this._inputMode = inputMode; this.createInput(); this._updateDomInputType(); this._updateSize(this._size.width, this._size.height); }, setInputFlag: function(inputFlag) { if (this._inputFlag === inputFlag) return; this._inputFlag = inputFlag; this._updateDomInputType(); var textTransform = "none"; inputFlag === InputFlag.INITIAL_CAPS_ALL_CHARACTERS ? textTransform = "uppercase" : inputFlag === InputFlag.INITIAL_CAPS_WORD && (textTransform = "capitalize"); if (this._edTxt) { this._edTxt.style.textTransform = textTransform; this._edTxt.value = this._text; } }, setReturnType: function(returnType) { this._returnType = returnType; this._updateDomInputType(); }, setFontSize: function(fontSize) { this._edFontSize = fontSize || this._edFontSize; this._edTxt && (this._edTxt.style.fontSize = this._edFontSize + "px"); }, setFontColor: function(color) { this._textColor = color; this._edTxt && (this._edTxt.style.color = color.toCSS("rgba")); }, setSize: function(width, height) { this._size.width = width; this._size.height = height; this._updateSize(width, height); }, setNode: function(node) { this._node = node; }, update: function() { this._updateMatrix(); }, clear: function() { this._node = null; this.setDelegate(null); this.removeDom(); this.removeOrientationchangeEvent(); }, _onTouchBegan: function(touch) {}, _onTouchEnded: function() { this._beginEditing(); }, _beginEditing: function() { var _this = this; cc.sys.isMobile && !this._editing && this.addOrientationchangeEvent(); this._edTxt && (function() { _this._edTxt.style.display = ""; var self = _this; function startFocus() { self._edTxt.focus(); } cc.sys.browserType === cc.sys.BROWSER_TYPE_UC ? setTimeout(startFocus, FOCUS_DELAY_UC) : cc.sys.browserType === cc.sys.BROWSER_TYPE_FIREFOX ? setTimeout(startFocus, FOCUS_DELAY_FIREFOX) : startFocus(); })(); this._editing = true; }, _endEditing: function() { var self = this; var hideDomInputAndShowLabel = function() { !self._alwaysOnTop && self._edTxt && (self._edTxt.style.display = "none"); self._delegate && self._delegate.editBoxEditingDidEnded && self._delegate.editBoxEditingDidEnded(); }; this._editing && (cc.sys.isMobile ? setTimeout((function() { self._endEditingOnMobile(); hideDomInputAndShowLabel(); }), DELAY_TIME) : hideDomInputAndShowLabel()); this._editing = false; }, _updateDomInputType: function() { var inputMode = this._inputMode; var edTxt = this._edTxt; if (!edTxt) return; if (this._inputFlag === InputFlag.PASSWORD) { edTxt.type = "password"; return; } var type = edTxt.type; if (inputMode === InputMode.EMAIL_ADDR) type = "email"; else if (inputMode === InputMode.NUMERIC || inputMode === InputMode.DECIMAL) type = "number"; else if (inputMode === InputMode.PHONE_NUMBER) { type = "number"; edTxt.pattern = "[0-9]*"; } else if (inputMode === InputMode.URL) type = "url"; else { type = "text"; this._returnType === KeyboardReturnType.SEARCH && (type = "search"); } edTxt.type = type; }, _updateSize: function(newWidth, newHeight) { var edTxt = this._edTxt; if (!edTxt) return; edTxt.style.width = newWidth + "px"; edTxt.style.height = newHeight + "px"; }, _updateMatrix: function() { if (!this._edTxt) return; var node = this._node; node.getWorldMatrix(_worldMat); if (this._m00 === _worldMat.m00 && this._m01 === _worldMat.m01 && this._m04 === _worldMat.m04 && this._m05 === _worldMat.m05 && this._m12 === _worldMat.m12 && this._m13 === _worldMat.m13 && this._w === node._contentSize.width && this._h === node._contentSize.height) return; this._m00 = _worldMat.m00; this._m01 = _worldMat.m01; this._m04 = _worldMat.m04; this._m05 = _worldMat.m05; this._m12 = _worldMat.m12; this._m13 = _worldMat.m13; this._w = node._contentSize.width; this._h = node._contentSize.height; var scaleX = cc.view._scaleX, scaleY = cc.view._scaleY, viewport = cc.view._viewportRect, dpr = cc.view._devicePixelRatio; _vec3.x = -node._anchorPoint.x * this._w; _vec3.y = -node._anchorPoint.y * this._h; math.mat4.translate(_worldMat, _worldMat, _vec3); false; var camera = cc.Camera.findCamera(node); camera.getWorldToCameraMatrix(_cameraMat); math.mat4.mul(_cameraMat, _cameraMat, _worldMat); scaleX /= dpr; scaleY /= dpr; var container = cc.game.container; var a = _cameraMat.m00 * scaleX, b = _cameraMat.m01, c = _cameraMat.m04, d = _cameraMat.m05 * scaleY; var offsetX = container && container.style.paddingLeft && parseInt(container.style.paddingLeft); offsetX += viewport.x / dpr; var offsetY = container && container.style.paddingBottom && parseInt(container.style.paddingBottom); offsetY += viewport.y / dpr; var tx = _cameraMat.m12 * scaleX + offsetX, ty = _cameraMat.m13 * scaleY + offsetY; if (polyfill.zoomInvalid) { this._updateSize(this._size.width * a, this._size.height * d); a = 1; d = 1; } var matrix = "matrix(" + a + "," + -b + "," + -c + "," + d + "," + tx + "," + -ty + ")"; this._edTxt.style["transform"] = matrix; this._edTxt.style["-webkit-transform"] = matrix; this._edTxt.style["transform-origin"] = "0px 100% 0px"; this._edTxt.style["-webkit-transform-origin"] = "0px 100% 0px"; }, _adjustEditBoxPosition: function() { this._node.getWorldMatrix(_worldMat); var y = _worldMat.m13; var windowHeight = cc.visibleRect.height; var windowWidth = cc.visibleRect.width; var factor = .5; windowWidth > windowHeight && (factor = .7); setTimeout((function() { if (window.scrollY < SCROLLY && y < windowHeight * factor) { var scrollOffset = windowHeight * factor - y - window.scrollY; scrollOffset < 35 && (scrollOffset = 35); scrollOffset > 320 && (scrollOffset = 320); window.scrollTo(0, scrollOffset); } }), DELAY_TIME); } }); var _p = EditBoxImpl.prototype; _p.createInput = function() { this._inputMode === InputMode.ANY ? this._createDomTextArea() : this._createDomInput(); }; _p._beginEditingOnMobile = function() { this.addOrientationchangeEvent(); if (cc.view.isAutoFullScreenEnabled()) { this.__fullscreen = true; cc.view.enableAutoFullScreen(false); cc.screen.exitFullScreen(); } else this.__fullscreen = false; this.__autoResize = cc.view._resizeWithBrowserSize; cc.view.resizeWithBrowserSize(false); _currentEditBoxImpl = this; }; _p._endEditingOnMobile = function() { if (this.__rotateScreen) { cc.game.container.style["-webkit-transform"] = "rotate(90deg)"; cc.game.container.style.transform = "rotate(90deg)"; var view = cc.view; var width = view._originalDesignResolutionSize.width; var height = view._originalDesignResolutionSize.height; width > 0 && view.setDesignResolutionSize(width, height, view._resolutionPolicy); this.__rotateScreen = false; } this.removeOrientationchangeEvent(); this.__fullscreen && cc.view.enableAutoFullScreen(true); this.__autoResize && _currentEditBoxImpl === this && cc.view.resizeWithBrowserSize(true); }; function _inputValueHandle(input, editBoxImpl) { input.value.length > editBoxImpl._maxLength && (input.value = input.value.slice(0, editBoxImpl._maxLength)); if (editBoxImpl._delegate && editBoxImpl._delegate.editBoxTextChanged && editBoxImpl._text !== input.value) { editBoxImpl._text = input.value; editBoxImpl._delegate.editBoxTextChanged(editBoxImpl._text); } } function registerInputEventListener(tmpEdTxt, editBoxImpl, isTextarea) { var inputLock = false; var blurWhenComposition = false; var cbs = editBoxImpl.__eventListeners; cbs.compositionstart = function() { inputLock = true; }; tmpEdTxt.addEventListener("compositionstart", cbs.compositionstart); cbs.compositionend = function() { inputLock = false; if (blurWhenComposition) { this.value = editBoxImpl._text; blurWhenComposition = false; } _inputValueHandle(this, editBoxImpl); }; tmpEdTxt.addEventListener("compositionend", cbs.compositionend); cbs.input = function() { if (inputLock) return; _inputValueHandle(this, editBoxImpl); }; tmpEdTxt.addEventListener("input", cbs.input); cbs.focus = function() { this.style.fontSize = editBoxImpl._edFontSize + "px"; this.style.color = editBoxImpl._textColor.toCSS("rgba"); editBoxImpl._alwaysOnTop && (editBoxImpl._editing = true); cc.sys.isMobile && editBoxImpl._beginEditingOnMobile(); editBoxImpl._delegate && editBoxImpl._delegate.editBoxEditingDidBegan && editBoxImpl._delegate.editBoxEditingDidBegan(); }; tmpEdTxt.addEventListener("focus", cbs.focus); cbs.keypress = function(e) { if (e.keyCode === macro.KEY.enter) { e.stopPropagation(); editBoxImpl._delegate && editBoxImpl._delegate.editBoxEditingReturn && editBoxImpl._delegate.editBoxEditingReturn(); if (!isTextarea) { editBoxImpl._text = this.value; editBoxImpl._endEditing(); cc.game.canvas.focus(); } } }; tmpEdTxt.addEventListener("keypress", cbs.keypress); cbs.blur = function() { inputLock ? blurWhenComposition = true : editBoxImpl._text = this.value; editBoxImpl._endEditing(); if (cc.sys.os == cc.sys.OS_IOS) { input = document.createElement("INPUT"); input.type = "text"; input.style.height = "0px"; input.style.width = "0px"; input.style.position = "absolute"; input.id = "reset-input"; document.body.prepend(input); input.focus(); input.blur(); } }; tmpEdTxt.addEventListener("blur", cbs.blur); editBoxImpl._addDomToGameContainer(); } _p._createDomInput = function() { this.removeDom(); var tmpEdTxt = this._edTxt = document.createElement("input"); tmpEdTxt.type = "text"; tmpEdTxt.style.fontSize = this._edFontSize + "px"; tmpEdTxt.style.color = "#000000"; tmpEdTxt.style.border = 0; tmpEdTxt.style.background = "transparent"; tmpEdTxt.style.width = "100%"; tmpEdTxt.style.height = "100%"; tmpEdTxt.style.active = 0; tmpEdTxt.style.outline = "medium"; tmpEdTxt.style.padding = "0"; tmpEdTxt.style.textTransform = "uppercase"; tmpEdTxt.style.display = "none"; tmpEdTxt.style.position = "absolute"; tmpEdTxt.style.bottom = "0px"; tmpEdTxt.style.left = LEFT_PADDING + "px"; tmpEdTxt.style["-moz-appearance"] = "textfield"; tmpEdTxt.style.fontFamily = "Arial"; tmpEdTxt.className = "cocosEditBox"; registerInputEventListener(tmpEdTxt, this); return tmpEdTxt; }; _p._createDomTextArea = function() { this.removeDom(); var tmpEdTxt = this._edTxt = document.createElement("textarea"); tmpEdTxt.style.fontSize = this._edFontSize + "px"; tmpEdTxt.style.color = "#000000"; tmpEdTxt.style.border = 0; tmpEdTxt.style.background = "transparent"; tmpEdTxt.style.width = "100%"; tmpEdTxt.style.height = "100%"; tmpEdTxt.style.active = 0; tmpEdTxt.style.outline = "medium"; tmpEdTxt.style.padding = "0"; tmpEdTxt.style.resize = "none"; tmpEdTxt.style.textTransform = "uppercase"; tmpEdTxt.style.overflow_y = "scroll"; tmpEdTxt.style.display = "none"; tmpEdTxt.style.position = "absolute"; tmpEdTxt.style.bottom = "0px"; tmpEdTxt.style.left = LEFT_PADDING + "px"; tmpEdTxt.style.fontFamily = "Arial"; tmpEdTxt.className = "cocosEditBox"; registerInputEventListener(tmpEdTxt, this, true); return tmpEdTxt; }; _p._addDomToGameContainer = function() { cc.game.container.appendChild(this._edTxt); }; _p.removeDom = function() { var edTxt = this._edTxt; if (edTxt) { var cbs = this.__eventListeners; edTxt.removeEventListener("compositionstart", cbs.compositionstart); edTxt.removeEventListener("compositionend", cbs.compositionend); edTxt.removeEventListener("input", cbs.input); edTxt.removeEventListener("focus", cbs.focus); edTxt.removeEventListener("keypress", cbs.keypress); edTxt.removeEventListener("blur", cbs.blur); cbs.compositionstart = null; cbs.compositionend = null; cbs.input = null; cbs.focus = null; cbs.keypress = null; cbs.blur = null; var hasChild = utils.contains(cc.game.container, edTxt); hasChild && cc.game.container.removeChild(edTxt); } this._edTxt = null; }; _p.addOrientationchangeEvent = function() { var self = this; self.__orientationChanged || (self.__orientationChanged = function() { self._adjustEditBoxPosition(); }); window.addEventListener("orientationchange", self.__orientationChanged); }; _p.removeOrientationchangeEvent = function() { if (this.__orientationChanged) { window.removeEventListener("orientationchange", this.__orientationChanged); this.__orientationChanged = null; } }; module.exports = EditBoxImpl; }), { "../../platform/CCMacro": 166, "../../platform/utils": 185, "./types": 94 } ], 94: [ (function(require, module, exports) { var KeyboardReturnType = cc.Enum({ DEFAULT: 0, DONE: 1, SEND: 2, SEARCH: 3, GO: 4, NEXT: 5 }); var InputMode = cc.Enum({ ANY: 0, EMAIL_ADDR: 1, NUMERIC: 2, PHONE_NUMBER: 3, URL: 4, DECIMAL: 5, SINGLE_LINE: 6 }); var InputFlag = cc.Enum({ PASSWORD: 0, SENSITIVE: 1, INITIAL_CAPS_WORD: 2, INITIAL_CAPS_SENTENCE: 3, INITIAL_CAPS_ALL_CHARACTERS: 4, DEFAULT: 5 }); module.exports = { KeyboardReturnType: KeyboardReturnType, InputMode: InputMode, InputFlag: InputFlag }; }), {} ], 95: [ (function(require, module, exports) { require("./CCComponent"); require("./CCComponentEventHandler"); require("./missing-script"); 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("./CCRichText"), require("./CCToggleContainer"), require("./CCToggleGroup"), require("./CCToggle"), require("./CCBlockInputEvents"), require("./CCMotionStreak"), require("./WXSubContextView"), require("./SwanSubContextView") ]; module.exports = components; }), { "./CCAnimation": 63, "./CCAudioSource": 64, "./CCBlockInputEvents": 65, "./CCButton": 66, "./CCCanvas": 67, "./CCComponent": 68, "./CCComponentEventHandler": 69, "./CCLabel": 70, "./CCLabelOutline": 71, "./CCLayout": 72, "./CCMask": 73, "./CCMotionStreak": 74, "./CCPageView": 75, "./CCPageViewIndicator": 76, "./CCProgressBar": 77, "./CCRichText": 79, "./CCScrollBar": 80, "./CCScrollView": 81, "./CCSlider": 82, "./CCSprite": 83, "./CCToggle": 85, "./CCToggleContainer": 86, "./CCToggleGroup": 87, "./CCWidget": 89, "./SwanSubContextView": 90, "./WXSubContextView": 91, "./editbox/CCEditBox": 92, "./missing-script": 96 } ], 96: [ (function(require, module, exports) { var js = cc.js; var BUILTIN_CLASSID_RE = require("../utils/misc").BUILTIN_CLASSID_RE; var MissingClass = cc.Class({ name: "cc.MissingClass", properties: { _$erialized: { default: null, visible: false, editorOnly: true } } }); 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(id, data) { var cls = js._getClassById(id); if (cls) return cls; if (id) { cc.deserialize.reportMissingClass(id); return MissingScript.getMissingWrapper(id, data); } return null; }, getMissingWrapper: function(id, data) { return data.node && (/^[0-9a-zA-Z+/]{23}$/.test(id) || BUILTIN_CLASSID_RE.test(id)) ? MissingScript : MissingClass; } }, onLoad: function() { cc.warnID(4600, this.node.name); } }); cc._MissingScript = module.exports = MissingScript; }), { "../utils/misc": 243 } ], 97: [ (function(require, module, exports) { var js = cc.js; require("../event/event"); var EventMouse = function(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(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(acc, bubbles) { cc.Event.call(this, cc.Event.ACCELERATION, bubbles); this.acc = acc; }; js.extend(EventAcceleration, cc.Event); var EventKeyboard = function(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": 104 } ], 98: [ (function(require, module, exports) { 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(paused) { this._paused = paused; }, _isPaused: function() { return this._paused; }, _setRegistered: function(registered) { this._registered = registered; }, _isRegistered: function() { return this._registered; }, _getType: function() { return this._type; }, _getListenerID: function() { return this._listenerID; }, _setFixedPriority: function(fixedPriority) { this._fixedPriority = fixedPriority; }, _getFixedPriority: function() { return this._fixedPriority; }, _setSceneGraphPriority: function(node) { this._target = node; this._node = node; }, _getSceneGraphPriority: function() { return this._node; }, checkAvailable: function() { return null !== this._onEvent; }, clone: function() { return null; }, setEnabled: function(enabled) { this._isEnabled = enabled; }, isEnabled: function() { return this._isEnabled; }, retain: function() {}, release: function() {} }; 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(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(event) { null !== this._onCustomEvent && this._onCustomEvent(event); }, checkAvailable: function() { return cc.EventListener.prototype.checkAvailable.call(this) && null !== this._onCustomEvent; }, clone: function() { return new Custom(this._listenerID, this._onCustomEvent); } }); var Mouse = function() { 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(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() { var eventListener = new Mouse(); eventListener.onMouseDown = this.onMouseDown; eventListener.onMouseUp = this.onMouseUp; eventListener.onMouseMove = this.onMouseMove; eventListener.onMouseScroll = this.onMouseScroll; return eventListener; }, checkAvailable: function() { return true; } }); var TouchOneByOne = function() { 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(needSwallow) { this.swallowTouches = needSwallow; }, isSwallowTouches: function() { return this.swallowTouches; }, clone: function() { 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() { if (!this.onTouchBegan) { cc.logID(1801); return false; } return true; } }); var TouchAllAtOnce = function() { 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() { var eventListener = new TouchAllAtOnce(); eventListener.onTouchesBegan = this.onTouchesBegan; eventListener.onTouchesMoved = this.onTouchesMoved; eventListener.onTouchesEnded = this.onTouchesEnded; eventListener.onTouchesCancelled = this.onTouchesCancelled; return eventListener; }, checkAvailable: function() { if (null === this.onTouchesBegan && null === this.onTouchesMoved && null === this.onTouchesEnded && null === this.onTouchesCancelled) { cc.logID(1802); return false; } return true; } }); var Acceleration = function(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(event) { this._onAccelerationEvent(event.acc, event); }, checkAvailable: function() { cc.assertID(this._onAccelerationEvent, 1803); return true; }, clone: function() { return new Acceleration(this._onAccelerationEvent); } }); var Keyboard = function() { 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(event) { event.isPressed ? this.onKeyPressed && this.onKeyPressed(event.keyCode, event) : this.onKeyReleased && this.onKeyReleased(event.keyCode, event); }, clone: function() { var eventListener = new Keyboard(); eventListener.onKeyPressed = this.onKeyPressed; eventListener.onKeyReleased = this.onKeyReleased; return eventListener; }, checkAvailable: function() { 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": 181 } ], 99: [ (function(require, module, exports) { var js = require("../platform/js"); require("./CCEventListener"); var ListenerID = cc.EventListener.ListenerID; var _EventListenerVector = function() { this._fixedListeners = []; this._sceneGraphListeners = []; this.gt0Index = 0; }; _EventListenerVector.prototype = { constructor: _EventListenerVector, size: function() { return this._fixedListeners.length + this._sceneGraphListeners.length; }, empty: function() { return 0 === this._fixedListeners.length && 0 === this._sceneGraphListeners.length; }, push: function(listener) { 0 === listener._getFixedPriority() ? this._sceneGraphListeners.push(listener) : this._fixedListeners.push(listener); }, clearSceneGraphListeners: function() { this._sceneGraphListeners.length = 0; }, clearFixedListeners: function() { this._fixedListeners.length = 0; }, clear: function() { this._sceneGraphListeners.length = 0; this._fixedListeners.length = 0; }, getFixedPriorityListeners: function() { return this._fixedListeners; }, getSceneGraphPriorityListeners: function() { return this._sceneGraphListeners; } }; var __getListenerID = function(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: {}, _nodePriorityMap: js.createMap(true), _globalZOrderNodeMap: [], _toAddedListeners: [], _toRemovedListeners: [], _dirtyNodes: [], _inDispatch: 0, _isEnabled: false, _nodePriorityIndex: 0, _internalCustomListenerIDs: [], _setDirtyForNode: function(node) { void 0 !== this._nodeListenersMap[node._id] && this._dirtyNodes.push(node); if (node.getChildren) { var _children = node.getChildren(); for (var i = 0, len = _children ? _children.length : 0; i < len; i++) this._setDirtyForNode(_children[i]); } }, pauseTarget: function(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(true); if (true === recursive) { var locChildren = node.getChildren(); for (i = 0, len = locChildren ? locChildren.length : 0; i < len; i++) this.pauseTarget(locChildren[i], true); } }, resumeTarget: function(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 && node.getChildren) { var locChildren = node.getChildren(); for (i = 0, len = locChildren ? locChildren.length : 0; i < len; i++) this.resumeTarget(locChildren[i], true); } }, _addListener: function(listener) { 0 === this._inDispatch ? this._forceAddEventListener(listener) : this._toAddedListeners.push(listener); }, _forceAddEventListener: function(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(listenerID) { return this._listenersMap[listenerID]; }, _updateDirtyFlagForSceneGraph: function() { if (0 === this._dirtyNodes.length) return; var locDirtyNodes = this._dirtyNodes, selListeners, selListener, locNodeListenersMap = this._nodeListenersMap; for (var i = 0, len = locDirtyNodes.length; i < len; i++) { selListeners = locNodeListenersMap[locDirtyNodes[i]._id]; if (selListeners) for (var j = 0, listenersLen = selListeners.length; j < listenersLen; j++) { selListener = selListeners[j]; selListener && this._setDirty(selListener._getListenerID(), this.DIRTY_SCENE_GRAPH_PRIORITY); } } this._dirtyNodes.length = 0; }, _removeAllListenersInVector: function(listenerVector) { if (!listenerVector) return; var selListener; for (var i = 0; i < listenerVector.length; ) { selListener = listenerVector[i]; selListener._setRegistered(false); if (null != selListener._getSceneGraphPriority()) { this._dissociateNodeAndEventListener(selListener._getSceneGraphPriority(), selListener); selListener._setSceneGraphPriority(null); } 0 === this._inDispatch ? cc.js.array.remove(listenerVector, selListener) : ++i; } }, _removeListenersForListenerID: function(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 = 0; i < locToAddedListeners.length; ) { listener = locToAddedListeners[i]; listener && listener._getListenerID() === listenerID ? cc.js.array.remove(locToAddedListeners, listener) : ++i; } }, _sortEventListeners: function(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, rootEntity); } } }, _sortListenersOfSceneGraphPriority: function(listenerID, rootNode) { var listeners = this._getListeners(listenerID); if (!listeners) return; var sceneGraphListener = listeners.getSceneGraphPriorityListeners(); if (!sceneGraphListener || 0 === sceneGraphListener.length) return; this._nodePriorityIndex = 0; this._nodePriorityMap = js.createMap(true); this._visitTarget(rootNode, true); listeners.getSceneGraphPriorityListeners().sort(this._sortEventListenersOfSceneGraphPriorityDes); }, _sortEventListenersOfSceneGraphPriorityDes: function(l1, l2) { var locNodePriorityMap = eventManager._nodePriorityMap, node1 = l1._getSceneGraphPriority(), node2 = l2._getSceneGraphPriority(); if (!(l2 && node2 && locNodePriorityMap[node2._id])) return -1; if (!l1 || !node1 || !locNodePriorityMap[node1._id]) return 1; return locNodePriorityMap[node2._id] - locNodePriorityMap[node1._id]; }, _sortListenersOfFixedPriority: function(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(l1, l2) { return l1._getFixedPriority() - l2._getFixedPriority(); }, _onUpdateListeners: function(listeners) { var fixedPriorityListeners = listeners.getFixedPriorityListeners(); var sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners(); var i, selListener, idx, toRemovedListeners = this._toRemovedListeners; if (sceneGraphPriorityListeners) for (i = 0; i < sceneGraphPriorityListeners.length; ) { selListener = sceneGraphPriorityListeners[i]; if (selListener._isRegistered()) ++i; else { cc.js.array.remove(sceneGraphPriorityListeners, selListener); idx = toRemovedListeners.indexOf(selListener); -1 !== idx && toRemovedListeners.splice(idx, 1); } } if (fixedPriorityListeners) for (i = 0; i < fixedPriorityListeners.length; ) { selListener = fixedPriorityListeners[i]; if (selListener._isRegistered()) ++i; else { cc.js.array.remove(fixedPriorityListeners, selListener); idx = toRemovedListeners.indexOf(selListener); -1 !== idx && toRemovedListeners.splice(idx, 1); } } sceneGraphPriorityListeners && 0 === sceneGraphPriorityListeners.length && listeners.clearSceneGraphListeners(); fixedPriorityListeners && 0 === fixedPriorityListeners.length && listeners.clearFixedListeners(); }, frameUpdateListeners: function() { 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(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() { 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(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 (listener.onTouchBegan) { isClaimed = listener.onTouchBegan(selTouch, event); isClaimed && listener._registered && listener._claimedTouches.push(selTouch); } } else if (listener._claimedTouches.length > 0 && -1 !== (removedIdx = listener._claimedTouches.indexOf(selTouch))) { isClaimed = true; 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); } else if (getCode === EventTouch.CANCELLED) { listener.onTouchCancelled && listener.onTouchCancelled(selTouch, event); listener._registered && listener._claimedTouches.splice(removedIdx, 1); } } 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(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(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.CANCELLED && listener.onTouchesCancelled && listener.onTouchesCancelled(touches, event); if (event.isStopped()) { eventManager._updateTouchListeners(event); return true; } return false; }, _associateNodeAndEventListener: function(node, listener) { var listeners = this._nodeListenersMap[node._id]; if (!listeners) { listeners = []; this._nodeListenersMap[node._id] = listeners; } listeners.push(listener); }, _dissociateNodeAndEventListener: function(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(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(listenerID, flag) { var locDirtyFlagMap = this._priorityDirtyFlagMap; null == locDirtyFlagMap[listenerID] ? locDirtyFlagMap[listenerID] = flag : locDirtyFlagMap[listenerID] = flag | locDirtyFlagMap[listenerID]; }, _visitTarget: function(node, isRootNode) { node._reorderChildDirty && node.sortAllChildren(); var children = node.getChildren(), i = 0; var childrenCount = children.length, locGlobalZOrderNodeMap = this._globalZOrderNodeMap, locNodeListenersMap = this._nodeListenersMap; if (childrenCount > 0) { if (void 0 !== locNodeListenersMap[node._id]) { locGlobalZOrderNodeMap || (locGlobalZOrderNodeMap = []); locGlobalZOrderNodeMap.push(node._id); } var child; for (;i < childrenCount; i++) { child = children[i]; child && this._visitTarget(child, false); } } else if (void 0 !== locNodeListenersMap[node._id]) { locGlobalZOrderNodeMap || (locGlobalZOrderNodeMap = []); locGlobalZOrderNodeMap.push(node._id); } if (isRootNode) { var locNodePriorityMap = this._nodePriorityMap; for (var j = 0; j < locGlobalZOrderNodeMap.length; j++) locNodePriorityMap[locGlobalZOrderNodeMap[j]] = ++this._nodePriorityIndex; this._globalZOrderNodeMap.length = 0; } }, _sortNumberAsc: function(a, b) { return a - b; }, hasEventListener: function(listenerID) { return !!this._getListeners(listenerID); }, addListener: function(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(eventName, callback) { var listener = new cc.EventListener.create({ event: cc.EventListener.CUSTOM, eventName: eventName, callback: callback }); this.addListener(listener, 1); return listener; }, removeListener: function(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 = 0, len = locToAddedListeners.length; i < len; i++) { var selListener = locToAddedListeners[i]; if (selListener === listener) { cc.js.array.remove(locToAddedListeners, selListener); selListener._setRegistered(false); break; } } } }, _removeListenerInCallback: function(listeners, callback) { if (null == listeners) return false; for (var i = 0, len = listeners.length; i < len; i++) { var selListener = listeners[i]; if (selListener._onCustomEvent === callback || selListener._onEvent === callback) { selListener._setRegistered(false); if (null != selListener._getSceneGraphPriority()) { this._dissociateNodeAndEventListener(selListener._getSceneGraphPriority(), selListener); selListener._setSceneGraphPriority(null); } 0 === this._inDispatch ? cc.js.array.remove(listeners, selListener) : this._toRemovedListeners.push(selListener); return true; } } return false; }, _removeListenerInVector: function(listeners, listener) { if (null == listeners) return false; for (var i = 0, len = listeners.length; i < len; 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.remove(listeners, selListener) : this._toRemovedListeners.push(selListener); return true; } } return false; }, removeListeners: function(listenerType, recursive) { var i, _t = this; if (!(cc.js.isNumber(listenerType) || listenerType instanceof cc._BaseNode)) { cc.warnID(3506); return; } if (void 0 !== listenerType._id) { delete _t._nodePriorityMap[listenerType._id]; cc.js.array.remove(_t._dirtyNodes, listenerType); 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.getChildren(), 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(customEventName) { this._removeListenersForListenerID(customEventName); }, removeAllListeners: function() { var locListeners = this._listenersMap, locInternalCustomEventIDs = this._internalCustomListenerIDs; for (var selKey in locListeners) -1 === locInternalCustomEventIDs.indexOf(selKey) && this._removeListenersForListenerID(selKey); }, setPriority: function(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(enabled) { this._isEnabled = enabled; }, isEnabled: function() { return this._isEnabled; }, dispatchEvent: function(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(listener, event) { event.currentTarget = listener._target; listener._onEvent(event); return event.isStopped(); }, dispatchCustomEvent: function(eventName, optionalUserData) { var ev = new cc.Event.EventCustom(eventName); ev.setUserData(optionalUserData); this.dispatchEvent(ev); } }; js.get(cc, "eventManager", (function() { cc.warnID(1405, "cc.eventManager", "cc.EventTarget or cc.systemEvent"); return eventManager; })); module.exports = eventManager; }), { "../platform/js": 181, "./CCEventListener": 98 } ], 100: [ (function(require, module, exports) { cc.Touch = function(x, y, id) { this._lastModified = 0; this.setTouchInfo(id, x, y); }; cc.Touch.prototype = { constructor: cc.Touch, getLocation: function() { return cc.v2(this._point.x, this._point.y); }, getLocationX: function() { return this._point.x; }, getLocationY: function() { return this._point.y; }, getPreviousLocation: function() { return cc.v2(this._prevPoint.x, this._prevPoint.y); }, getStartLocation: function() { return cc.v2(this._startPoint.x, this._startPoint.y); }, getDelta: function() { return this._point.sub(this._prevPoint); }, getLocationInView: function() { return cc.v2(this._point.x, cc.view._designResolutionSize.height - this._point.y); }, getPreviousLocationInView: function() { return cc.v2(this._prevPoint.x, cc.view._designResolutionSize.height - this._prevPoint.y); }, getStartLocationInView: function() { return cc.v2(this._startPoint.x, cc.view._designResolutionSize.height - this._startPoint.y); }, getID: function() { return this._id; }, setTouchInfo: function(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(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(x, y) { this._prevPoint = void 0 === y ? cc.v2(x.x, x.y) : cc.v2(x || 0, y || 0); } }; }), {} ], 101: [ (function(require, module, exports) { require("./CCEvent"); require("./CCTouch"); require("./CCEventListener"); var eventManager = require("./CCEventManager"); module.exports = eventManager; false; }), { "./CCEvent": 97, "./CCEventListener": 98, "./CCEventManager": 99, "./CCTouch": 100 } ], 102: [ (function(require, module, exports) { var js = cc.js; var CallbacksHandler = require("../platform/callbacks-invoker").CallbacksHandler; function EventListeners() { CallbacksHandler.call(this); } js.extend(EventListeners, CallbacksHandler); EventListeners.prototype.invoke = function(event, captureListeners) { var key = event.type; var list = this._callbackTable[key]; if (list) { var rootInvoker = !list.isInvoking; list.isInvoking = true; var callbacks = list.callbacks; var targets = list.targets; for (var i = 0, len = callbacks.length; i < len; ++i) { var callback = callbacks[i]; if (callback) { var target = targets[i] || event.currentTarget; callback.call(target, event, captureListeners); if (event._propagationImmediateStopped) break; } } if (rootInvoker) { list.isInvoking = false; list.containCanceled && list.purgeCanceled(); } } }; module.exports = EventListeners; false; }), { "../platform/callbacks-invoker": 174 } ], 103: [ (function(require, module, exports) { 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 = function(type, callback, target) { if (!callback) { cc.errorID(6800); return; } if (!this.hasEventListener(type, callback, target)) { this.add(type, callback, target); target && target.__eventTargets && target.__eventTargets.push(this); } return callback; }; proto.off = function(type, callback, target) { if (callback) { this.remove(type, callback, target); target && target.__eventTargets && fastRemove(target.__eventTargets, this); } else this.removeAll(type); }; proto.targetOff = proto.removeAll; proto.once = function(type, callback, target) { var eventType_hasOnceListener = "__ONCE_FLAG:" + type; var hasOnceListener = this.hasEventListener(eventType_hasOnceListener, callback, target); if (!hasOnceListener) { var self = this; var onceWrapper = function(arg1, arg2, arg3, arg4, arg5) { self.off(type, onceWrapper, target); self.remove(eventType_hasOnceListener, callback, target); callback.call(this, arg1, arg2, arg3, arg4, arg5); }; this.on(type, onceWrapper, target); this.add(eventType_hasOnceListener, callback, target); } }; proto.emit = CallbacksInvoker.prototype.invoke; proto.dispatchEvent = function(event) { this.invoke(event.type, event); }; cc.EventTarget = module.exports = EventTarget; }), { "../platform/callbacks-invoker": 174, "../platform/js": 181 } ], 104: [ (function(require, module, exports) { 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() { 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(type, bubbles) { this.type = type; this.bubbles = bubbles || false; }, stopPropagation: function() { this._propagationStopped = true; }, stopPropagationImmediate: function() { this._propagationImmediateStopped = true; }, isStopped: function() { return this._propagationStopped || this._propagationImmediateStopped; }, getCurrentTarget: function() { return this.currentTarget; }, getType: function() { 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(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": 181 } ], 105: [ (function(require, module, exports) { require("./event"); require("./event-listeners"); require("./event-target"); require("./system-event"); }), { "./event": 104, "./event-listeners": 102, "./event-target": 103, "./system-event": 106 } ], 106: [ (function(require, module, exports) { 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(isEnable) { false; inputManger.setAccelerometerEnabled(isEnable); }, setAccelerometerInterval: function(interval) { false; inputManger.setAccelerometerInterval(interval); }, on: function(type, callback, target) { false; this._super(type, callback, target); if (type === EventType.KEY_DOWN || type === EventType.KEY_UP) { keyboardListener || (keyboardListener = cc.EventListener.create({ event: cc.EventListener.KEYBOARD, onKeyPressed: function(keyCode, event) { event.type = EventType.KEY_DOWN; cc.systemEvent.dispatchEvent(event); }, onKeyReleased: function(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(acc, event) { event.type = EventType.DEVICEMOTION; cc.systemEvent.dispatchEvent(event); } })); eventManager.hasEventListener(cc.EventListener.ListenerID.ACCELERATION) || eventManager.addListener(accelerationListener, 1); } }, off: function(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": 101, "../event/event-target": 103, "../platform/CCInputManager": 165 } ], 107: [ (function(require, module, exports) { var RenderComponent = require("../components/CCRenderComponent"); var SpriteMaterial = require("../renderer/render-engine").SpriteMaterial; 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() { this._impl = Graphics._assembler.createImpl(this); }, properties: { _lineWidth: 1, _strokeColor: cc.Color.BLACK, _lineJoin: LineJoin.MITER, _lineCap: LineCap.BUTT, _fillColor: cc.Color.WHITE, _miterLimit: 10, lineWidth: { get: function() { return this._lineWidth; }, set: function(value) { this._lineWidth = value; this._impl.lineWidth = value; } }, lineJoin: { get: function() { return this._lineJoin; }, set: function(value) { this._lineJoin = value; this._impl.lineJoin = value; }, type: LineJoin }, lineCap: { get: function() { return this._lineCap; }, set: function(value) { this._lineCap = value; this._impl.lineCap = value; }, type: LineCap }, strokeColor: { get: function() { return this._strokeColor; }, set: function(value) { this._impl.strokeColor = this._strokeColor = cc.color(value); } }, fillColor: { get: function() { return this._fillColor; }, set: function(value) { this._impl.fillColor = this._fillColor = cc.color(value); } }, miterLimit: { get: function() { return this._miterLimit; }, set: function(value) { this._miterLimit = value; this._impl.miterLimit = value; } } }, statics: { LineJoin: LineJoin, LineCap: LineCap }, onRestore: function() { this._impl || (this._impl = Graphics._assembler.createImpl()); }, onEnable: function() { this._super(); this._activateMaterial(); }, onDestroy: function() { this._super(); this._impl.clear(this, true); this._impl = null; }, _activateMaterial: function() { if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) return; this.node._renderFlag &= ~cc.RenderFlow.FLAG_RENDER; this.node._renderFlag |= cc.RenderFlow.FLAG_CUSTOM_IA_RENDER; if (this._material) return; var material = new SpriteMaterial(); material.useColor = false; material.useTexture = false; material.useModel = true; this._updateMaterial(material); }, moveTo: function(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(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(c1x, c1y, c2x, c2y, x, y) { this._impl.bezierCurveTo(c1x, c1y, c2x, c2y, x, y); }, quadraticCurveTo: function(cx, cy, x, y) { this._impl.quadraticCurveTo(cx, cy, x, y); }, arc: function(cx, cy, r, startAngle, endAngle, counterclockwise) { this._impl.arc(cx, cy, r, startAngle, endAngle, counterclockwise); }, ellipse: function(cx, cy, rx, ry) { this._impl.ellipse(cx, cy, rx, ry); }, circle: function(cx, cy, r) { this._impl.circle(cx, cy, r); }, rect: function(x, y, w, h) { this._impl.rect(x, y, w, h); }, roundRect: function(x, y, w, h, r) { this._impl.roundRect(x, y, w, h, r); }, fillRect: function(x, y, w, h) { this.rect(x, y, w, h); this.fill(); }, clear: function(clean) { this._impl.clear(this, clean); }, close: function() { this._impl.close(); }, stroke: function() { Graphics._assembler.stroke(this); }, fill: function() { Graphics._assembler.fill(this); } }); cc.Graphics = module.exports = Graphics; }), { "../components/CCRenderComponent": 78, "../renderer/render-engine": 203, "./types": 110 } ], 108: [ (function(require, module, exports) { 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": 110 } ], 109: [ (function(require, module, exports) { "use strict"; require("./graphics"); }), { "./graphics": 107 } ], 110: [ (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 }; }), {} ], 111: [ (function(require, module, exports) { 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("./utils/polyfill-3d"); require("./base-ui/CCWidgetManager"); }), { "./CCNode": 30, "./CCPrivateNode": 31, "./CCScene": 32, "./assets": 51, "./base-ui/CCWidgetManager": 52, "./camera/CCCamera": 53, "./collider": 61, "./collider/CCIntersection": 59, "./components": 95, "./graphics": 109, "./physics": 144, "./platform": 178, "./utils/polyfill-3d": 245 } ], 112: [ (function(require, module, exports) { var js = require("../platform/js"); var Pipeline = require("./pipeline"); var LoadingItems = require("./loading-items"); var AssetLoader = require("./asset-loader"); var Downloader = require("./downloader"); var Loader = require("./loader"); var AssetTable = require("./asset-table"); var callInNextTick = require("../platform/utils").callInNextTick; var AutoReleaseUtils = require("./auto-release-utils"); var urlAppendTimestamp = require("./utils").urlAppendTimestamp; var ReleasedAssetChecker = (true, require("./released-asset-checker")); var resources = new AssetTable(); function getXMLHttpRequest() { return window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP"); } function getImportConfigs() { return window.ImportConfigs; } var _info = { url: null, raw: false }; function getResWithUrl(res) { var id, result, isUuid; if ("object" === (__typeofVal = typeof res, "object" === __typeofVal ? __realTypeOfObj(res) : __typeofVal)) { result = res; if (res.url) return result; id = res.uuid; } else { result = {}; id = res; } isUuid = result.type ? "uuid" === result.type : cc.AssetLibrary._uuidInSettings(id); cc.AssetLibrary._getAssetInfoInRuntime(id, _info); result.url = isUuid ? _info.url : id; if (_info.url && "uuid" === result.type && _info.raw) { result.type = null; result.isRawAsset = true; } else isUuid || (result.isRawAsset = true); return result; } var _sharedResources = []; var _sharedList = []; function CCLoader() { var assetLoader = new AssetLoader(); var downloader = new Downloader(); var loader = new Loader(); Pipeline.call(this, [ assetLoader, downloader, loader ]); this.assetLoader = assetLoader; this.md5Pipe = null; this.downloader = downloader; this.loader = loader; this.onProgress = null; this._autoReleaseSetting = js.createMap(true); true; this._releasedAssetChecker_DEBUG = new ReleasedAssetChecker(); } js.extend(CCLoader, Pipeline); var proto = CCLoader.prototype; proto.init = function(director) { true; var self = this; director.on(cc.Director.EVENT_AFTER_UPDATE, (function() { self._releasedAssetChecker_DEBUG.checkCouldRelease(self._cache); })); }; proto.getXMLHttpRequest = getXMLHttpRequest; proto.getImportConfigs = getImportConfigs; proto.addDownloadHandlers = function(extMap) { this.downloader.addHandlers(extMap); }; proto.addLoadHandlers = function(extMap) { this.loader.addHandlers(extMap); }; proto.load = function(resources, progressCallback, completeCallback) { false; if (void 0 === completeCallback) { completeCallback = progressCallback; progressCallback = this.onProgress || null; } var self = this; var singleRes = false; var res; if (!(resources instanceof Array)) if (resources) { singleRes = true; resources = [ resources ]; } else resources = []; _sharedResources.length = 0; for (var i = 0; i < resources.length; ++i) { var resource = resources[i]; if (resource && resource.id) { cc.warnID(4920, resource.id); resource.uuid || resource.url || (resource.url = resource.id); } res = getResWithUrl(resource); if (!res.url && !res.uuid) continue; var item = this._cache[res.url]; _sharedResources.push(item || res); } var queue = LoadingItems.create(this, progressCallback, (function(errors, items) { callInNextTick((function() { if (completeCallback) { if (singleRes) { var id = res.url; completeCallback.call(self, errors, items.getContent(id)); } else completeCallback.call(self, errors, items); completeCallback = null; } var _id; false; items.destroy(); })); })); LoadingItems.initQueueDeps(queue); queue.append(_sharedResources); _sharedResources.length = 0; }; proto.flowInDeps = function(owner, urlList, callback) { _sharedList.length = 0; for (var i = 0; i < urlList.length; ++i) { var res = getResWithUrl(urlList[i]); if (!res.url && !res.uuid) continue; var item = this._cache[res.url]; item ? _sharedList.push(item) : _sharedList.push(res); } var queue = LoadingItems.create(this, owner ? function(completedCount, totalCount, item) { this._ownerQueue && this._ownerQueue.onProgress && this._ownerQueue._childOnProgress(item); } : null, (function(errors, items) { callback(errors, items); owner && owner.deps && (owner.deps.length = 0); items.destroy(); })); if (owner) { var ownerQueue = LoadingItems.getQueue(owner); queue._ownerQueue = ownerQueue._ownerQueue || ownerQueue; } var accepted = queue.append(_sharedList, owner); _sharedList.length = 0; return accepted; }; proto._resources = resources; proto._getResUuid = function(url, type, quiet) { if (!url) return null; var index = url.indexOf("?"); -1 !== index && (url = url.substr(0, index)); var uuid = resources.getUuid(url, type); if (!uuid) { var extname = cc.path.extname(url); if (extname) { url = url.slice(0, -extname.length); uuid = resources.getUuid(url, type); uuid && !quiet && cc.warnID(4901, url, extname); } } return uuid; }; proto._getReferenceKey = function(assetOrUrlOrUuid) { var key; "object" === (__typeofVal = typeof assetOrUrlOrUuid, "object" === __typeofVal ? __realTypeOfObj(assetOrUrlOrUuid) : __typeofVal) ? key = assetOrUrlOrUuid._uuid || null : "string" === (__typeofVal = typeof assetOrUrlOrUuid, "object" === __typeofVal ? __realTypeOfObj(assetOrUrlOrUuid) : __typeofVal) && (key = this._getResUuid(assetOrUrlOrUuid, null, true) || assetOrUrlOrUuid); if (!key) { cc.warnID(4800, assetOrUrlOrUuid); return key; } cc.AssetLibrary._getAssetInfoInRuntime(key, _info); return this._cache[_info.url] ? _info.url : key; }; proto._urlNotFound = function(url, type, completeCallback) { callInNextTick((function() { url = cc.url.normalize(url); var info = (type ? js.getClassName(type) : "Asset") + ' in "resources/' + url + '" does not exist.'; completeCallback && completeCallback(new Error(info), []); })); }; proto._parseLoadResArgs = function(type, onProgress, onComplete) { if (void 0 === onComplete) { var isValidType = type instanceof Array || js.isChildClassOf(type, cc.RawAsset); if (onProgress) { onComplete = onProgress; isValidType && (onProgress = this.onProgress || null); } else if (void 0 === onProgress && !isValidType) { onComplete = type; onProgress = this.onProgress || null; type = null; } if (void 0 !== onProgress && !isValidType) { onProgress = type; type = null; } } return { type: type, onProgress: onProgress, onComplete: onComplete }; }; proto.loadRes = function(url, type, progressCallback, completeCallback) { var args = this._parseLoadResArgs(type, progressCallback, completeCallback); type = args.type; progressCallback = args.onProgress; completeCallback = args.onComplete; var self = this; var uuid = self._getResUuid(url, type); uuid ? this.load({ type: "uuid", uuid: uuid }, progressCallback, (function(err, asset) { asset && self.setAutoReleaseRecursively(uuid, false); completeCallback && completeCallback(err, asset); })) : self._urlNotFound(url, type, completeCallback); }; proto._loadResUuids = function(uuids, progressCallback, completeCallback, urls) { if (uuids.length > 0) { var self = this; var res = uuids.map((function(uuid) { return { type: "uuid", uuid: uuid }; })); this.load(res, progressCallback, (function(errors, items) { if (completeCallback) { var assetRes = []; var urlRes = urls && []; for (var i = 0; i < res.length; ++i) { var uuid = res[i].uuid; var id = this._getReferenceKey(uuid); var item = items.getContent(id); if (item) { self.setAutoReleaseRecursively(uuid, false); assetRes.push(item); urlRes && urlRes.push(urls[i]); } } urls ? completeCallback(errors, assetRes, urlRes) : completeCallback(errors, assetRes); } })); } else completeCallback && callInNextTick((function() { urls ? completeCallback(null, [], []) : completeCallback(null, []); })); }; proto.loadResArray = function(urls, type, progressCallback, completeCallback) { var args = this._parseLoadResArgs(type, progressCallback, completeCallback); type = args.type; progressCallback = args.onProgress; completeCallback = args.onComplete; var uuids = []; var isTypesArray = type instanceof Array; for (var i = 0; i < urls.length; i++) { var url = urls[i]; var assetType = isTypesArray ? type[i] : type; var uuid = this._getResUuid(url, assetType); if (!uuid) { this._urlNotFound(url, assetType, completeCallback); return; } uuids.push(uuid); } this._loadResUuids(uuids, progressCallback, completeCallback); }; proto.loadResDir = function(url, type, progressCallback, completeCallback) { var args = this._parseLoadResArgs(type, progressCallback, completeCallback); type = args.type; progressCallback = args.onProgress; completeCallback = args.onComplete; var urls = []; var uuids = resources.getUuidArray(url, type, urls); this._loadResUuids(uuids, progressCallback, (function(errors, assetRes, urlRes) { var assetResLength = assetRes.length; for (var i = 0; i < assetResLength; ++i) if (assetRes[i] instanceof cc.SpriteAtlas) { var spriteFrames = assetRes[i].getSpriteFrames(); for (var k in spriteFrames) { var sf = spriteFrames[k]; assetRes.push(sf); urlRes && urlRes.push(urlRes[i] + "/" + sf.name); } } completeCallback && completeCallback(errors, assetRes, urlRes); }), urls); }; proto.getRes = function(url, type) { var item = this._cache[url]; if (!item) { var uuid = this._getResUuid(url, type, true); if (!uuid) return null; var ref = this._getReferenceKey(uuid); item = this._cache[ref]; } item && item.alias && (item = item.alias); return item && item.complete ? item.content : null; }; proto.getResCount = function() { return Object.keys(this._cache).length; }; proto.getDependsRecursively = function(owner) { if (owner) { var key = this._getReferenceKey(owner); var assets = AutoReleaseUtils.getDependsRecursively(key); assets.push(key); return assets; } return []; }; proto.getDownLoadStatus = function() { return LoadingItems.getDownLoadStatus(); }; proto.getUrlWithUuid = function(uuid) { if (!uuid) return; var res = getResWithUrl({ type: "uuid", uuid: uuid }); return urlAppendTimestamp(res.url); }; proto.getDirUuids = function(url, type) { var urls = []; var uuids = resources.getUuidArray(url, type, urls); return uuids; }; proto.release = function(asset) { if (Array.isArray(asset)) for (var i = 0; i < asset.length; i++) { var key = asset[i]; this.release(key); } else if (asset) { var id = this._getReferenceKey(asset); var item = this.getItem(id); if (item) { var removed = this.removeItem(id); asset = item.content; if (asset instanceof cc.Asset) { var nativeUrl = asset.nativeUrl; nativeUrl && this.release(nativeUrl); asset.destroy(); } (true, removed) && this._releasedAssetChecker_DEBUG.setReleased(item, id); } } }; proto.releaseAsset = function(asset) { var uuid = asset._uuid; uuid && this.release(uuid); }; proto.releaseRes = function(url, type) { var uuid = this._getResUuid(url, type); uuid ? this.release(uuid) : cc.errorID(4914, url); }; proto.releaseResDir = function(url, type) { var uuids = resources.getUuidArray(url, type); for (var i = 0; i < uuids.length; i++) { var uuid = uuids[i]; this.release(uuid); } }; proto.releaseAll = function() { for (var id in this._cache) this.release(id); }; proto.removeItem = function(key) { var removed = Pipeline.prototype.removeItem.call(this, key); delete this._autoReleaseSetting[key]; return removed; }; proto.setAutoRelease = function(assetOrUrlOrUuid, autoRelease) { var key = this._getReferenceKey(assetOrUrlOrUuid); !!key && (this._autoReleaseSetting[key] = !!autoRelease); }; proto.setAutoReleaseRecursively = function(assetOrUrlOrUuid, autoRelease) { autoRelease = !!autoRelease; var key = this._getReferenceKey(assetOrUrlOrUuid); if (key) { this._autoReleaseSetting[key] = autoRelease; var depends = AutoReleaseUtils.getDependsRecursively(key); for (var i = 0; i < depends.length; i++) { var depend = depends[i]; this._autoReleaseSetting[depend] = autoRelease; } } else false; }; proto.isAutoRelease = function(assetOrUrl) { var key = this._getReferenceKey(assetOrUrl); if (key) return !!this._autoReleaseSetting[key]; return false; }; cc.loader = new CCLoader(); false; module.exports = cc.loader; }), { "../platform/js": 181, "../platform/utils": 185, "./asset-loader": 113, "./asset-table": 114, "./auto-release-utils": 116, "./downloader": 118, "./loader": 121, "./loading-items": 122, "./pipeline": 125, "./released-asset-checker": 126, "./utils": 130 } ], 113: [ (function(require, module, exports) { require("../utils/CCPath"); var debug = require("../CCDebug"); var Pipeline = require("./pipeline"); var LoadingItems = require("./loading-items"); var ID = "AssetLoader"; var AssetLoader = function(extMap) { this.id = ID; this.async = true; this.pipeline = null; }; AssetLoader.ID = ID; var reusedArray = []; AssetLoader.prototype.handle = function(item, callback) { var uuid = item.uuid; if (!uuid) return item.content || null; var self = this; cc.AssetLibrary.queryAssetInfo(uuid, (function(error, url, isRawAsset) { if (error) callback(error); else { item.url = item.rawUrl = url; item.isRawAsset = isRawAsset; if (isRawAsset) { var ext = cc.path.extname(url).toLowerCase(); if (!ext) { callback(new Error(debug.getError(4931, uuid, url))); return; } ext = ext.substr(1); var queue = LoadingItems.getQueue(item); reusedArray[0] = { queueId: item.queueId, id: url, url: url, type: ext, error: null, alias: item, complete: true }; false; queue.append(reusedArray); item.type = ext; callback(null, item.content); } else { item.type = "uuid"; callback(null, item.content); } } })); }; Pipeline.AssetLoader = module.exports = AssetLoader; }), { "../CCDebug": 27, "../utils/CCPath": 234, "./loading-items": 122, "./pipeline": 125 } ], 114: [ (function(require, module, exports) { var pushToMap = require("../utils/misc").pushToMap; var js = require("../platform/js"); function Entry(uuid, type) { this.uuid = uuid; this.type = type; } function AssetTable() { this._pathToUuid = js.createMap(true); } function isMatchByWord(path, test) { if (path.length > test.length) { var nextAscii = path.charCodeAt(test.length); return 46 === nextAscii || 47 === nextAscii; } return true; } var proto = AssetTable.prototype; proto.getUuid = function(path, type) { path = cc.url.normalize(path); var item = this._pathToUuid[path]; if (item) if (Array.isArray(item)) { if (!type) return item[0].uuid; for (var i = 0; i < item.length; i++) { var entry = item[i]; if (js.isChildClassOf(entry.type, type)) return entry.uuid; } if (true, js.isChildClassOf(type, cc.SpriteFrame)) for (var _i = 0; _i < item.length; _i++) { var _entry = item[_i]; if (js.isChildClassOf(_entry.type, cc.SpriteAtlas)) { cc.errorID(4932, path); break; } } } else { if (!type || js.isChildClassOf(item.type, type)) return item.uuid; (true, js.isChildClassOf(type, cc.SpriteFrame)) && js.isChildClassOf(item.type, cc.SpriteAtlas) && cc.errorID(4932, path); } return ""; }; proto.getUuidArray = function(path, type, out_urls) { path = cc.url.normalize(path); "/" === path[path.length - 1] && (path = path.slice(0, -1)); var path2uuid = this._pathToUuid; var uuids = []; var isChildClassOf = js.isChildClassOf; var _foundAtlasUrl; for (var p in path2uuid) if (p.startsWith(path) && isMatchByWord(p, path) || !path) { var item = path2uuid[p]; if (Array.isArray(item)) for (var i = 0; i < item.length; i++) { var entry = item[i]; if (!type || isChildClassOf(entry.type, type)) { uuids.push(entry.uuid); out_urls && out_urls.push(p); } else (true, entry.type === cc.SpriteAtlas) && (_foundAtlasUrl = p); } else if (!type || isChildClassOf(item.type, type)) { uuids.push(item.uuid); out_urls && out_urls.push(p); } else (true, item.type === cc.SpriteAtlas) && (_foundAtlasUrl = p); } (true, 0 === uuids.length) && _foundAtlasUrl && js.isChildClassOf(type, cc.SpriteFrame) && cc.errorID(4932, _foundAtlasUrl); return uuids; }; proto.add = function(path, uuid, type, isMainAsset) { path = path.substring(0, path.length - cc.path.extname(path).length); var newEntry = new Entry(uuid, type); pushToMap(this._pathToUuid, path, newEntry, isMainAsset); }; proto._getInfo_DEBUG = (true, function(uuid, out_info) { var path2uuid = this._pathToUuid; var paths = Object.keys(path2uuid); for (var p = 0; p < paths.length; ++p) { var path = paths[p]; var item = path2uuid[path]; if (Array.isArray(item)) for (var i = 0; i < item.length; i++) { var entry = item[i]; if (entry.uuid === uuid) { out_info.path = path; out_info.type = entry.type; return true; } } else if (item.uuid === uuid) { out_info.path = path; out_info.type = item.type; return true; } } return false; }); proto.reset = function() { this._pathToUuid = js.createMap(true); }; module.exports = AssetTable; }), { "../platform/js": 181, "../utils/misc": 243 } ], 115: [ (function(require, module, exports) { var sys = require("../platform/CCSys"); var debug = require("../CCDebug"); var __audioSupport = sys.__audioSupport; var formatSupport = __audioSupport.format; var context = __audioSupport.context; function loadDomAudio(item, callback) { var dom = document.createElement("audio"); dom.src = item.url; var isBaiduGame = cc.sys.platform === cc.sys.BAIDU_GAME; if (false, isBaiduGame) { callback(null, dom); return; } var clearEvent = function() { 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() { clearEvent(); callback(null, dom); }; var failure = function() { clearEvent(); var message = "load audio failure - " + item.url; cc.log(message); callback(message); }; dom.addEventListener("canplaythrough", success, false); dom.addEventListener("error", failure, false); __audioSupport.USE_LOADER_EVENT && dom.addEventListener(__audioSupport.USE_LOADER_EVENT, success, false); } function loadWebAudio(item, callback) { context || callback(new Error(debug.getError(4926))); var request = cc.loader.getXMLHttpRequest(); request.open("GET", item.url, true); request.responseType = "arraybuffer"; request.onload = function() { context["decodeAudioData"](request.response, (function(buffer) { callback(null, buffer); }), (function() { callback("decode error - " + item.id, null); })); }; request.onerror = function() { callback("request error - " + item.id, null); }; request.send(); } function downloadAudio(item, callback) { if (0 === formatSupport.length) return new Error(debug.getError(4927)); var loader; if (__audioSupport.WEB_AUDIO) { var loadByDeserializedAudio = item._owner instanceof cc.AudioClip; loader = loadByDeserializedAudio ? item._owner.loadMode === cc.AudioClip.LoadMode.WEB_AUDIO ? loadWebAudio : loadDomAudio : item.urlParam && item.urlParam["useDom"] ? loadDomAudio : loadWebAudio; } else loader = loadDomAudio; loader(item, callback); } module.exports = downloadAudio; }), { "../CCDebug": 27, "../platform/CCSys": 170 } ], 116: [ (function(require, module, exports) { var js = require("../platform/js"); function parseDepends(key, parsed) { var item = cc.loader.getItem(key); if (item) { var depends = item.dependKeys; if (depends) for (var i = 0; i < depends.length; i++) { var depend = depends[i]; if (!parsed[depend]) { parsed[depend] = true; parseDepends(depend, parsed); } } } } function visitAsset(asset, excludeMap) { if (!asset._uuid) return; var key = cc.loader._getReferenceKey(asset); if (!excludeMap[key]) { excludeMap[key] = true; parseDepends(key, excludeMap); } } function visitComponent(comp, excludeMap) { var props = Object.getOwnPropertyNames(comp); for (var i = 0; i < props.length; i++) { var value = comp[props[i]]; if ("object" === (__typeofVal = typeof value, "object" === __typeofVal ? __realTypeOfObj(value) : __typeofVal) && value) if (Array.isArray(value)) for (var j = 0; j < value.length; j++) { var val = value[j]; val instanceof cc.RawAsset && visitAsset(val, excludeMap); } else if (value.constructor && value.constructor !== Object) value instanceof cc.RawAsset && visitAsset(value, excludeMap); else { var keys = Object.getOwnPropertyNames(value); for (var _j = 0; _j < keys.length; _j++) { var _val = value[keys[_j]]; _val instanceof cc.RawAsset && visitAsset(_val, excludeMap); } } } } function visitNode(node, excludeMap) { for (var i = 0; i < node._components.length; i++) visitComponent(node._components[i], excludeMap); for (var _i = 0; _i < node._children.length; _i++) visitNode(node._children[_i], excludeMap); } module.exports = { autoRelease: function(oldSceneAssets, nextSceneAssets, persistNodes) { var releaseSettings = cc.loader._autoReleaseSetting; var excludeMap = js.createMap(); if (nextSceneAssets) for (var i = 0; i < nextSceneAssets.length; i++) excludeMap[nextSceneAssets[i]] = true; for (var _i2 = 0; _i2 < persistNodes.length; _i2++) visitNode(persistNodes[_i2], excludeMap); if (oldSceneAssets) for (var _i3 = 0; _i3 < oldSceneAssets.length; _i3++) { var key = oldSceneAssets[_i3]; false === releaseSettings[key] || excludeMap[key] || cc.loader.release(key); } var keys = Object.keys(releaseSettings); for (var _i4 = 0; _i4 < keys.length; _i4++) { var _key = keys[_i4]; true !== releaseSettings[_key] || excludeMap[_key] || cc.loader.release(_key); } }, getDependsRecursively: function(key) { var depends = {}; parseDepends(key, depends); return Object.keys(depends); } }; }), { "../platform/js": 181 } ], 117: [ (function(require, module, exports) { function downloadBinary(item, callback) { var url = item.url; var xhr = cc.loader.getXMLHttpRequest(), errInfo = "Load binary data failed: " + url; xhr.open("GET", url, true); xhr.responseType = "arraybuffer"; xhr.onload = function() { var arrayBuffer = xhr.response; if (arrayBuffer) { var result = new Uint8Array(arrayBuffer); callback(null, result); } else callback({ status: xhr.status, errorMessage: errInfo + "(no response)" }); }; xhr.onerror = function() { callback({ status: xhr.status, errorMessage: errInfo + "(error)" }); }; xhr.ontimeout = function() { callback({ status: xhr.status, errorMessage: errInfo + "(time out)" }); }; xhr.send(null); } module.exports = downloadBinary; }), {} ], 118: [ (function(require, module, exports) { var js = require("../platform/js"); var debug = require("../CCDebug"); require("../utils/CCPath"); var Pipeline = require("./pipeline"); var PackDownloader = require("./pack-downloader"); var downloadBinary = require("./binary-downloader"); var downloadText = require("./text-downloader"); var urlAppendTimestamp = require("./utils").urlAppendTimestamp; var downloadAudio; true; downloadAudio = require("./audio-downloader"); function skip() { return null; } function downloadScript(item, callback, isAsync) { var url = item.url, d = document, s = document.createElement("script"); "file:" !== window.location.protocol && (s.crossOrigin = "anonymous"); s.async = isAsync; s.src = urlAppendTimestamp(url); function loadHandler() { s.parentNode.removeChild(s); s.removeEventListener("load", loadHandler, false); s.removeEventListener("error", errorHandler, false); callback(null, url); } function errorHandler() { s.parentNode.removeChild(s); s.removeEventListener("load", loadHandler, false); s.removeEventListener("error", errorHandler, false); callback(new Error(debug.getError(4928, url))); } s.addEventListener("load", loadHandler, false); s.addEventListener("error", errorHandler, false); d.body.appendChild(s); } function downloadWebp(item, callback, isCrossOrigin, img) { if (!cc.sys.capabilities.webp) return new Error(debug.getError(4929, item.url)); return downloadImage(item, callback, isCrossOrigin, img); } function downloadImage(item, callback, isCrossOrigin, img) { void 0 === isCrossOrigin && (isCrossOrigin = true); var url = urlAppendTimestamp(item.url); img = img || new Image(); isCrossOrigin && "file:" !== window.location.protocol ? img.crossOrigin = "anonymous" : img.crossOrigin = null; if (img.complete && img.naturalWidth > 0 && img.src === url) return img; (function() { function loadCallback() { img.removeEventListener("load", loadCallback); img.removeEventListener("error", errorCallback); img.id = item.id; callback(null, img); } function errorCallback() { img.removeEventListener("load", loadCallback); img.removeEventListener("error", errorCallback); "https:" !== window.location.protocol && img.crossOrigin && "anonymous" === img.crossOrigin.toLowerCase() ? downloadImage(item, callback, false, img) : callback(new Error(debug.getError(4930, url))); } img.addEventListener("load", loadCallback); img.addEventListener("error", errorCallback); img.src = url; })(); } function downloadUuid(item, callback) { var result = PackDownloader.load(item, callback); if (void 0 === result) return this.extMap["json"](item, callback); return result || void 0; } var defaultMap = { js: downloadScript, png: downloadImage, jpg: downloadImage, bmp: downloadImage, jpeg: downloadImage, gif: downloadImage, ico: downloadImage, tiff: downloadImage, webp: downloadWebp, image: downloadImage, mp3: downloadAudio, ogg: downloadAudio, wav: downloadAudio, m4a: downloadAudio, txt: downloadText, xml: downloadText, vsh: downloadText, fsh: downloadText, atlas: downloadText, tmx: downloadText, tsx: downloadText, json: downloadText, ExportJson: downloadText, plist: downloadText, fnt: downloadText, font: skip, eot: skip, ttf: skip, woff: skip, svg: skip, ttc: skip, uuid: downloadUuid, binary: downloadBinary, dbbin: downloadBinary, default: downloadText }; var ID = "Downloader"; var Downloader = function(extMap) { this.id = ID; this.async = true; this.pipeline = null; this._curConcurrent = 0; this._loadQueue = []; this._subpackages = {}; this.extMap = js.mixin(extMap, defaultMap); }; Downloader.ID = ID; Downloader.PackDownloader = PackDownloader; Downloader.prototype.addHandlers = function(extMap) { js.mixin(this.extMap, extMap); }; Downloader.prototype._handleLoadQueue = function() { while (this._curConcurrent < cc.macro.DOWNLOAD_MAX_CONCURRENT) { var nextOne = this._loadQueue.shift(); if (!nextOne) break; var syncRet = this.handle(nextOne.item, nextOne.callback); void 0 !== syncRet && (syncRet instanceof Error ? nextOne.callback(syncRet) : nextOne.callback(null, syncRet)); } }; Downloader.prototype.handle = function(item, callback) { var self = this; var downloadFunc = this.extMap[item.type] || this.extMap["default"]; var syncRet = void 0; if (this._curConcurrent < cc.macro.DOWNLOAD_MAX_CONCURRENT) { this._curConcurrent++; syncRet = downloadFunc.call(this, item, (function(err, result) { self._curConcurrent = Math.max(0, self._curConcurrent - 1); self._handleLoadQueue(); callback && callback(err, result); })); if (void 0 !== syncRet) { this._curConcurrent = Math.max(0, this._curConcurrent - 1); this._handleLoadQueue(); return syncRet; } } else if (item.ignoreMaxConcurrency) { syncRet = downloadFunc.call(this, item, callback); if (void 0 !== syncRet) return syncRet; } else this._loadQueue.push({ item: item, callback: callback }); }; Downloader.prototype.loadSubpackage = function(name, completeCallback) { var pac = this._subpackages[name]; pac ? pac.loaded ? completeCallback && completeCallback() : downloadScript({ url: pac.path + "index.js" }, (function(err) { err || (pac.loaded = true); completeCallback && completeCallback(err); })) : completeCallback && completeCallback(new Error("Can't find subpackage " + name)); }; Pipeline.Downloader = module.exports = Downloader; }), { "../CCDebug": 27, "../platform/js": 181, "../utils/CCPath": 234, "./audio-downloader": 115, "./binary-downloader": 117, "./pack-downloader": 124, "./pipeline": 125, "./text-downloader": 128, "./utils": 130 } ], 119: [ (function(require, module, exports) { var textUtils = require("../utils/text-utils"); var _canvasContext = null; var _testString = "BES bswy:->@123\u4e01\u3041\u1101"; var _fontFaces = {}; var _intervalId = -1; var _loadingFonts = []; var _timeout = 6e4; 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.callback(null, fontFamily); _loadingFonts.splice(i, 1); continue; } var oldWidth = fontLoadHandle.refWidth; _canvasContext.font = "40px " + fontFamily; var newWidth = textUtils.safeMeasureText(_canvasContext, _testString); if (oldWidth !== newWidth) { _loadingFonts.splice(i, 1); fontLoadHandle.callback(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() { 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(item, callback) { var url = item.url; var fontFamilyName = fontLoader._getFontFamily(url); if (_fontFaces[fontFamilyName]) return 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); 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, callback); else { var fontLoadHandle = { fontFamilyName: fontFamilyName, refWidth: refWidth, callback: callback, startTime: Date.now() }; _loadingFonts.push(fontLoadHandle); -1 === _intervalId && (_intervalId = setInterval(_checkFontLoaded, 100)); } _fontFaces[fontFamilyName] = fontStyle; }, _getFontFamily: function(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": 250 } ], 120: [ (function(require, module, exports) { require("./downloader"); require("./loader"); require("./loading-items"); require("./pipeline"); require("./CCLoader"); }), { "./CCLoader": 112, "./downloader": 118, "./loader": 121, "./loading-items": 122, "./pipeline": 125 } ], 121: [ (function(require, module, exports) { var js = require("../platform/js"); var plistParser = require("../platform/CCSAXParser").plistParser; var Pipeline = require("./pipeline"); var Texture2D = require("../assets/CCTexture2D"); var loadUuid = require("./uuid-loader"); var fontLoader = require("./font-loader"); function loadNothing() { return null; } function loadJSON(item) { if ("string" !== (__typeofVal = typeof item.content, "object" === __typeofVal ? __realTypeOfObj(item.content) : __typeofVal)) return new Error("JSON Loader: Input item doesn't contain string content"); try { var result = JSON.parse(item.content); return result; } catch (e) { return new Error("JSON Loader: Parse json [" + item.id + "] failed : " + e); } } function loadImage(item) { var loadByDeserializedAsset = item._owner instanceof cc.Asset; if (loadByDeserializedAsset) return null; var image = item.content; if ((true, true) && cc.sys.platform !== cc.sys.FB_PLAYABLE_ADS && !(image instanceof Image)) return new Error("Image Loader: Input item doesn't contain Image content"); var rawUrl = item.rawUrl; var tex = item.texture || new Texture2D(); tex._uuid = item.uuid; tex.url = rawUrl; tex._setRawAsset(rawUrl, false); tex._nativeAsset = image; return tex; } function loadAudioAsAsset(item, callback) { var loadByDeserializedAsset = item._owner instanceof cc.Asset; if (loadByDeserializedAsset) return null; var audioClip = new cc.AudioClip(); audioClip._setRawAsset(item.rawUrl, false); audioClip._nativeAsset = item.content; return audioClip; } function loadPlist(item) { if ("string" !== (__typeofVal = typeof item.content, "object" === __typeofVal ? __realTypeOfObj(item.content) : __typeofVal)) return new Error("Plist Loader: Input item doesn't contain string content"); var result = plistParser.parse(item.content); return result || new Error("Plist Loader: Parse [" + item.id + "] failed"); } function loadBinary(item) { return item.load ? item.load(item.content) : null; } var defaultMap = { png: loadImage, jpg: loadImage, bmp: loadImage, jpeg: loadImage, gif: loadImage, ico: loadImage, tiff: loadImage, webp: loadImage, image: loadImage, mp3: loadAudioAsAsset, ogg: loadAudioAsAsset, wav: loadAudioAsAsset, m4a: loadAudioAsAsset, json: loadJSON, ExportJson: loadJSON, plist: loadPlist, uuid: loadUuid, prefab: loadUuid, fire: loadUuid, scene: loadUuid, binary: loadBinary, dbbin: loadBinary, font: fontLoader.loadFont, eot: fontLoader.loadFont, ttf: fontLoader.loadFont, woff: fontLoader.loadFont, svg: fontLoader.loadFont, ttc: fontLoader.loadFont, default: loadNothing }; var ID = "Loader"; var Loader = function(extMap) { this.id = ID; this.async = true; this.pipeline = null; this.extMap = js.mixin(extMap, defaultMap); }; Loader.ID = ID; Loader.prototype.addHandlers = function(extMap) { this.extMap = js.mixin(this.extMap, extMap); }; Loader.prototype.handle = function(item, callback) { var loadFunc = this.extMap[item.type] || this.extMap["default"]; return loadFunc.call(this, item, callback); }; Pipeline.Loader = module.exports = Loader; }), { "../assets/CCTexture2D": 50, "../platform/CCSAXParser": 168, "../platform/js": 181, "./font-loader": 119, "./pipeline": 125, "./uuid-loader": 131 } ], 122: [ (function(require, module, exports) { var CallbacksInvoker = require("../platform/callbacks-invoker"); require("../utils/CCPath"); var js = require("../platform/js"); var _qid = 0 | 998 * Math.random(); var _queues = js.createMap(true); var _pool = []; var _POOL_MAX_LENGTH = 10; var ItemState = { WORKING: 1, COMPLETE: 2, ERROR: 3 }; var _queueDeps = js.createMap(true); function isIdValid(id) { var realId = id.url || id; return "string" === (__typeofVal = typeof realId, "object" === __typeofVal ? __realTypeOfObj(realId) : __typeofVal); } function _parseUrlParam(url) { if (!url) return; var split = url.split("?"); if (!split || !split[0] || !split[1]) return; var urlParam = {}; var queries = split[1].split("&"); queries.forEach((function(item) { var itemSplit = item.split("="); urlParam[itemSplit[0]] = itemSplit[1]; })); return urlParam; } function createItem(id, queueId) { var url = "object" === (__typeofVal = typeof id, "object" === __typeofVal ? __realTypeOfObj(id) : __typeofVal) ? id.url : id; var result = { queueId: queueId, id: url, url: url, rawUrl: void 0, urlParam: _parseUrlParam(url), type: "", error: null, content: null, complete: false, states: {}, deps: null }; if ("object" === (__typeofVal = typeof id, "object" === __typeofVal ? __realTypeOfObj(id) : __typeofVal)) { js.mixin(result, id); if (id.skips) for (var i = 0; i < id.skips.length; i++) { var skip = id.skips[i]; result.states[skip] = ItemState.COMPLETE; } } result.rawUrl = result.url; url && !result.type && (result.type = cc.path.extname(url).toLowerCase().substr(1)); return result; } var checkedIds = []; function checkCircleReference(owner, item, recursiveCall) { if (!owner || !item) return false; var result = false; checkedIds.push(item.id); if (item.deps) { var i, deps = item.deps, subDep; for (i = 0; i < deps.length; i++) { subDep = deps[i]; if (subDep.id === owner.id) { result = true; break; } if (checkedIds.indexOf(subDep.id) >= 0) continue; if (subDep.deps && checkCircleReference(owner, subDep, true)) { result = true; break; } } } recursiveCall || (checkedIds.length = 0); return result; } var LoadingItems = function(pipeline, urlList, onProgress, onComplete) { CallbacksInvoker.call(this); this._id = ++_qid; _queues[this._id] = this; this._pipeline = pipeline; this._errorUrls = js.createMap(true); this._appending = false; this._ownerQueue = null; this.onProgress = onProgress; this.onComplete = onComplete; this.map = js.createMap(true); this.completed = {}; this.totalCount = 0; this.completedCount = 0; this._pipeline ? this.active = true : this.active = false; urlList && (urlList.length > 0 ? this.append(urlList) : this.allComplete()); }; LoadingItems.ItemState = new cc.Enum(ItemState); LoadingItems.create = function(pipeline, urlList, onProgress, onComplete) { if (void 0 === onProgress) { if ("function" === (__typeofVal = typeof urlList, "object" === __typeofVal ? __realTypeOfObj(urlList) : __typeofVal)) { onComplete = urlList; urlList = onProgress = null; } } else if (void 0 === onComplete) if ("function" === (__typeofVal = typeof urlList, "object" === __typeofVal ? __realTypeOfObj(urlList) : __typeofVal)) { onComplete = onProgress; onProgress = urlList; urlList = null; } else { onComplete = onProgress; onProgress = null; } var queue = _pool.pop(); if (queue) { queue._pipeline = pipeline; queue.onProgress = onProgress; queue.onComplete = onComplete; _queues[queue._id] = queue; queue._pipeline && (queue.active = true); urlList && queue.append(urlList); } else queue = new LoadingItems(pipeline, urlList, onProgress, onComplete); return queue; }; LoadingItems.getQueue = function(item) { return item.queueId ? _queues[item.queueId] : null; }; LoadingItems.itemComplete = function(item) { var queue = _queues[item.queueId]; queue && queue.itemComplete(item.id); }; LoadingItems.initQueueDeps = function(queue) { var dep = _queueDeps[queue._id]; if (dep) { dep.completed.length = 0; dep.deps.length = 0; } else dep = _queueDeps[queue._id] = { completed: [], deps: [] }; }; LoadingItems.registerQueueDep = function(owner, depId) { var queueId = owner.queueId || owner; if (!queueId) return false; var queueDepList = _queueDeps[queueId]; if (queueDepList) -1 === queueDepList.deps.indexOf(depId) && queueDepList.deps.push(depId); else if (owner.id) for (var id in _queueDeps) { var queue = _queueDeps[id]; -1 !== queue.deps.indexOf(owner.id) && -1 === queue.deps.indexOf(depId) && queue.deps.push(depId); } }; LoadingItems.finishDep = function(depId) { for (var id in _queueDeps) { var queue = _queueDeps[id]; -1 !== queue.deps.indexOf(depId) && -1 === queue.completed.indexOf(depId) && queue.completed.push(depId); } }; LoadingItems.getDownLoadStatus = function() { if (_queues) for (var item_i in _queues) if (_queues[item_i]) return true; if (_queueDeps) for (var item_i in _queueDeps) if (_queueDeps[item_i]) return true; return false; }; var proto = LoadingItems.prototype; js.mixin(proto, CallbacksInvoker.prototype); proto.append = function(urlList, owner) { if (!this.active) return []; owner && !owner.deps && (owner.deps = []); this._appending = true; var accepted = [], i, url, item; for (i = 0; i < urlList.length; ++i) { url = urlList[i]; if (url.queueId && !this.map[url.id]) { this.map[url.id] = url; owner && owner.deps.push(url); if (url.complete || checkCircleReference(owner, url)) { this.totalCount++; this.itemComplete(url.id); continue; } var self = this; var queue = _queues[url.queueId]; if (queue) { this.totalCount++; LoadingItems.registerQueueDep(owner || this._id, url.id); queue.addListener(url.id, (function(item) { self.itemComplete(item.id); })); } continue; } if (isIdValid(url)) { item = createItem(url, this._id); var key = item.id; if (!this.map[key]) { this.map[key] = item; this.totalCount++; owner && owner.deps.push(item); LoadingItems.registerQueueDep(owner || this._id, key); accepted.push(item); } } } this._appending = false; this.completedCount === this.totalCount ? this.allComplete() : this._pipeline.flowIn(accepted); return accepted; }; proto._childOnProgress = function(item) { if (this.onProgress) { var dep = _queueDeps[this._id]; this.onProgress(dep ? dep.completed.length : this.completedCount, dep ? dep.deps.length : this.totalCount, item); } }; proto.allComplete = function() { var errors = js.isEmptyObject(this._errorUrls) ? null : this._errorUrls; this.onComplete && this.onComplete(errors, this); }; proto.isCompleted = function() { return this.completedCount >= this.totalCount; }; proto.isItemCompleted = function(id) { return !!this.completed[id]; }; proto.exists = function(id) { return !!this.map[id]; }; proto.getContent = function(id) { var item = this.map[id]; var ret = null; item && (item.content ? ret = item.content : item.alias && (ret = item.alias.content)); return ret; }; proto.getError = function(id) { var item = this.map[id]; var ret = null; item && (item.error ? ret = item.error : item.alias && (ret = item.alias.error)); return ret; }; proto.addListener = CallbacksInvoker.prototype.add; proto.hasListener = CallbacksInvoker.prototype.has; proto.removeListener = CallbacksInvoker.prototype.remove; proto.removeAllListeners = CallbacksInvoker.prototype.removeAll; proto.removeItem = function(url) { var item = this.map[url]; if (!item) return; if (!this.completed[item.alias || url]) return; delete this.completed[url]; delete this.map[url]; if (item.alias) { delete this.completed[item.alias.id]; delete this.map[item.alias.id]; } this.completedCount--; this.totalCount--; }; proto.itemComplete = function(id) { var item = this.map[id]; if (!item) return; var errorListId = id in this._errorUrls; item.error instanceof Error || js.isString(item.error) ? this._errorUrls[id] = item.error : item.error ? js.mixin(this._errorUrls, item.error) : !item.error && errorListId && delete this._errorUrls[id]; this.completed[id] = item; this.completedCount++; LoadingItems.finishDep(item.id); if (this.onProgress) { var dep = _queueDeps[this._id]; this.onProgress(dep ? dep.completed.length : this.completedCount, dep ? dep.deps.length : this.totalCount, item); } this.invoke(id, item); this.removeAll(id); !this._appending && this.completedCount >= this.totalCount && this.allComplete(); }; proto.destroy = function() { this.active = false; this._appending = false; this._pipeline = null; this._ownerQueue = null; js.clear(this._errorUrls); this.onProgress = null; this.onComplete = null; this.map = js.createMap(true); this.completed = {}; this.totalCount = 0; this.completedCount = 0; CallbacksInvoker.call(this); if (_queueDeps[this._id]) { _queueDeps[this._id].completed.length = 0; _queueDeps[this._id].deps.length = 0; } delete _queues[this._id]; delete _queueDeps[this._id]; -1 === _pool.indexOf(this) && _pool.length < _POOL_MAX_LENGTH && _pool.push(this); }; cc.LoadingItems = module.exports = LoadingItems; }), { "../platform/callbacks-invoker": 174, "../platform/js": 181, "../utils/CCPath": 234 } ], 123: [ (function(require, module, exports) { var Pipeline = require("./pipeline"); var ID = "MD5Pipe"; var ExtnameRegex = /(\.[^.\n\\/]*)$/; var UuidRegex = /.*[/\\][0-9a-fA-F]{2}[/\\]([0-9a-fA-F-]{8,})/; function getUuidFromURL(url) { var matches = url.match(UuidRegex); if (matches) return matches[1]; return ""; } var MD5Pipe = function(md5AssetsMap, md5NativeAssetsMap, libraryBase) { this.id = ID; this.async = false; this.pipeline = null; this.md5AssetsMap = md5AssetsMap; this.md5NativeAssetsMap = md5NativeAssetsMap; this.libraryBase = libraryBase; }; MD5Pipe.ID = ID; MD5Pipe.prototype.handle = function(item) { var hashPatchInFolder = false; "ttf" === item.type && (hashPatchInFolder = true); item.url = this.transformURL(item.url, hashPatchInFolder); return null; }; MD5Pipe.prototype.transformURL = function(url, hashPatchInFolder) { var _this = this; var uuid = getUuidFromURL(url); if (uuid) { var isNativeAsset; var map; var dirname; var basename; var matched; (function() { isNativeAsset = !url.startsWith(_this.libraryBase); map = isNativeAsset ? _this.md5NativeAssetsMap : _this.md5AssetsMap; var hashValue = map[uuid]; if (hashValue) if (hashPatchInFolder) { dirname = cc.path.dirname(url); basename = cc.path.basename(url); url = dirname + "." + hashValue + "/" + basename; } else { matched = false; url = url.replace(ExtnameRegex, (function(match, p1) { matched = true; return "." + hashValue + p1; })); matched || (url = url + "." + hashValue); } })(); } return url; }; Pipeline.MD5Pipe = module.exports = MD5Pipe; }), { "./pipeline": 125 } ], 124: [ (function(require, module, exports) { var Unpackers = require("./unpackers"); var pushToMap = require("../utils/misc").pushToMap; var PackState = { Invalid: 0, Removed: 1, Downloading: 2, Loaded: 3 }; function UnpackerData() { this.unpacker = null; this.state = PackState.Invalid; } var uuidToPack = {}; var packIndices = {}; var globalUnpackers = {}; function error(uuid, packUuid) { return new Error("Can not retrieve " + uuid + " from packer " + packUuid); } module.exports = { initPacks: function(packs) { packIndices = packs; for (var packUuid in packs) { var uuids = packs[packUuid]; for (var i = 0; i < uuids.length; i++) { var uuid = uuids[i]; var pushFront = 1 === uuids.length; pushToMap(uuidToPack, uuid, packUuid, pushFront); } } }, _loadNewPack: function(uuid, packUuid, callback) { var self = this; var packUrl = cc.AssetLibrary.getLibUrlNoExt(packUuid) + ".json"; cc.loader.load({ url: packUrl, ignoreMaxConcurrency: true }, (function(err, packJson) { if (err) { cc.errorID(4916, uuid); return callback(err); } var res = self._doLoadNewPack(uuid, packUuid, packJson); res ? callback(null, res) : callback(error(uuid, packUuid)); })); }, _doPreload: function(packUuid, packJson) { var unpackerData = globalUnpackers[packUuid]; if (!unpackerData) { unpackerData = globalUnpackers[packUuid] = new UnpackerData(); unpackerData.state = PackState.Downloading; } if (unpackerData.state !== PackState.Loaded) { unpackerData.unpacker = new Unpackers.JsonUnpacker(); unpackerData.unpacker.load(packIndices[packUuid], packJson); unpackerData.state = PackState.Loaded; } }, _doLoadNewPack: function(uuid, packUuid, packedJson) { var unpackerData = globalUnpackers[packUuid]; if (unpackerData.state !== PackState.Loaded) { "string" === (__typeofVal = typeof packedJson, "object" === __typeofVal ? __realTypeOfObj(packedJson) : __typeofVal) && (packedJson = JSON.parse(packedJson)); Array.isArray(packedJson) ? unpackerData.unpacker = new Unpackers.JsonUnpacker() : packedJson.type === Unpackers.TextureUnpacker.ID && (unpackerData.unpacker = new Unpackers.TextureUnpacker()); unpackerData.unpacker.load(packIndices[packUuid], packedJson); unpackerData.state = PackState.Loaded; } return unpackerData.unpacker.retrieve(uuid); }, _selectLoadedPack: function(packUuids) { var existsPackState = PackState.Invalid; var existsPackUuid = ""; for (var i = 0; i < packUuids.length; i++) { var packUuid = packUuids[i]; var unpackerData = globalUnpackers[packUuid]; if (unpackerData) { var state = unpackerData.state; if (state === PackState.Loaded) return packUuid; if (state > existsPackState) { existsPackState = state; existsPackUuid = packUuid; } } } return existsPackState !== PackState.Invalid ? existsPackUuid : packUuids[0]; }, load: function(item, callback) { var uuid = item.uuid; var packUuid = uuidToPack[uuid]; if (!packUuid) return; Array.isArray(packUuid) && (packUuid = this._selectLoadedPack(packUuid)); var unpackerData = globalUnpackers[packUuid]; if (unpackerData && unpackerData.state === PackState.Loaded) { var json = unpackerData.unpacker.retrieve(uuid); return json || error(uuid, packUuid); } if (!unpackerData) { true; console.log("Create unpacker %s for %s", packUuid, uuid); unpackerData = globalUnpackers[packUuid] = new UnpackerData(); unpackerData.state = PackState.Downloading; } this._loadNewPack(uuid, packUuid, callback); return null; } }; false; }), { "../utils/misc": 243, "./unpackers": 129 } ], 125: [ (function(require, module, exports) { var js = require("../platform/js"); var LoadingItems = require("./loading-items"); var ItemState = LoadingItems.ItemState; function flow(pipe, item) { var pipeId = pipe.id; var itemState = item.states[pipeId]; var next = pipe.next; var pipeline = pipe.pipeline; if (item.error || itemState === ItemState.WORKING || itemState === ItemState.ERROR) return; if (itemState === ItemState.COMPLETE) next ? flow(next, item) : pipeline.flowOut(item); else { item.states[pipeId] = ItemState.WORKING; var result = pipe.handle(item, (function(err, result) { if (err) { item.error = err; item.states[pipeId] = ItemState.ERROR; pipeline.flowOut(item); } else { result && (item.content = result); item.states[pipeId] = ItemState.COMPLETE; next ? flow(next, item) : pipeline.flowOut(item); } })); if (result instanceof Error) { item.error = result; item.states[pipeId] = ItemState.ERROR; pipeline.flowOut(item); } else if (void 0 !== result) { null !== result && (item.content = result); item.states[pipeId] = ItemState.COMPLETE; next ? flow(next, item) : pipeline.flowOut(item); } } } var Pipeline = function(pipes) { this._pipes = pipes; this._cache = js.createMap(true); for (var i = 0; i < pipes.length; ++i) { var pipe = pipes[i]; if (!pipe.handle || !pipe.id) continue; pipe.pipeline = this; pipe.next = i < pipes.length - 1 ? pipes[i + 1] : null; } }; Pipeline.ItemState = ItemState; var proto = Pipeline.prototype; proto.insertPipe = function(pipe, index) { if (!pipe.handle || !pipe.id || index > this._pipes.length) { cc.warnID(4921); return; } if (this._pipes.indexOf(pipe) > 0) { cc.warnID(4922); return; } pipe.pipeline = this; var nextPipe = null; index < this._pipes.length && (nextPipe = this._pipes[index]); var previousPipe = null; index > 0 && (previousPipe = this._pipes[index - 1]); previousPipe && (previousPipe.next = pipe); pipe.next = nextPipe; this._pipes.splice(index, 0, pipe); }; proto.insertPipeAfter = function(refPipe, newPipe) { var index = this._pipes.indexOf(refPipe); if (index < 0) return; this.insertPipe(newPipe, index + 1); }; proto.appendPipe = function(pipe) { if (!pipe.handle || !pipe.id) return; pipe.pipeline = this; pipe.next = null; this._pipes.length > 0 && (this._pipes[this._pipes.length - 1].next = pipe); this._pipes.push(pipe); }; proto.flowIn = function(items) { var i, pipe = this._pipes[0], item; if (pipe) { for (i = 0; i < items.length; i++) { item = items[i]; this._cache[item.id] = item; } for (i = 0; i < items.length; i++) { item = items[i]; flow(pipe, item); } } else for (i = 0; i < items.length; i++) this.flowOut(items[i]); }; proto.flowInDeps = function(owner, urlList, callback) { var deps = LoadingItems.create(this, (function(errors, items) { callback(errors, items); items.destroy(); })); return deps.append(urlList, owner); }; proto.flowOut = function(item) { item.error ? delete this._cache[item.id] : this._cache[item.id] || (this._cache[item.id] = item); item.complete = true; LoadingItems.itemComplete(item); }; proto.copyItemStates = function(srcItem, dstItems) { if (!(dstItems instanceof Array)) { dstItems.states = srcItem.states; return; } for (var i = 0; i < dstItems.length; ++i) dstItems[i].states = srcItem.states; }; proto.getItem = function(id) { var item = this._cache[id]; if (!item) return item; item.alias && (item = item.alias); return item; }; proto.removeItem = function(id) { var removed = this._cache[id]; removed && removed.complete && delete this._cache[id]; return removed; }; proto.clear = function() { for (var id in this._cache) { var item = this._cache[id]; delete this._cache[id]; if (!item.complete) { item.error = new Error("Canceled manually"); this.flowOut(item); } } }; cc.Pipeline = module.exports = Pipeline; }), { "../platform/js": 181, "./loading-items": 122 } ], 126: [ (function(require, module, exports) { true; var js; var tmpInfo; (function() { js = require("../platform/js"); function ReleasedAssetChecker() { this._releasedKeys = js.createMap(true); this._dirty = false; } ReleasedAssetChecker.prototype.setReleased = function(item, releasedKey) { this._releasedKeys[releasedKey] = true; this._dirty = true; }; tmpInfo = null; function getItemDesc(item) { if (item.uuid) { tmpInfo || (tmpInfo = { path: "", type: null }); if (cc.loader._resources._getInfo_DEBUG(item.uuid, tmpInfo)) { tmpInfo.path = "resources/" + tmpInfo.path; return '"' + tmpInfo.path + '" (type: ' + js.getClassName(tmpInfo.type) + ", uuid: " + item.uuid + ")"; } return '"' + item.rawUrl + '" (' + item.uuid + ")"; } return '"' + item.rawUrl + '"'; } function doCheckCouldRelease(releasedKey, refOwnerItem, caches) { var loadedAgain = caches[releasedKey]; loadedAgain || cc.log('"' + releasedKey + '" was released but maybe still referenced by ' + getItemDesc(refOwnerItem)); } ReleasedAssetChecker.prototype.checkCouldRelease = function(caches) { if (!this._dirty) return; this._dirty = false; var released = this._releasedKeys; for (var id in caches) { var item = caches[id]; item.alias && (item = item.alias); var depends = item.dependKeys; if (depends) for (var i = 0; i < depends.length; ++i) { var depend = depends[i]; if (released[depend]) { doCheckCouldRelease(depend, item, caches); delete released[depend]; } } } js.clear(released); }; module.exports = ReleasedAssetChecker; })(); }), { "../platform/js": 181 } ], 127: [ (function(require, module, exports) { var Pipeline = require("./pipeline"); var ID = "SubPackPipe"; var UuidRegex = /.*[/\\][0-9a-fA-F]{2}[/\\]([0-9a-fA-F-]{8,})/; function getUuidFromURL(url) { var matches = url.match(UuidRegex); if (matches) return matches[1]; return ""; } var _uuidToSubPack = Object.create(null); var SubPackPipe = function(subpackage) { this.id = ID; this.async = false; this.pipeline = null; for (var packName in subpackage) { var pack = subpackage[packName]; pack.uuids && pack.uuids.forEach((function(val) { _uuidToSubPack[val] = pack.path; })); } }; SubPackPipe.ID = ID; SubPackPipe.prototype.handle = function(item) { item.url = this.transformURL(item.url); return null; }; SubPackPipe.prototype.transformURL = function(url) { var uuid = getUuidFromURL(url); if (uuid) { var subpackage = _uuidToSubPack[uuid]; if (subpackage) return url.replace("res/raw-assets/", subpackage + "raw-assets/"); } return url; }; Pipeline.SubPackPipe = module.exports = SubPackPipe; }), { "./pipeline": 125 } ], 128: [ (function(require, module, exports) { var urlAppendTimestamp = require("./utils").urlAppendTimestamp; module.exports = function(item, callback) { if (item && item.url && true) { var urlInfos = item.url.split("/"); var fileName = urlInfos.pop(); var importConfigs = cc.loader.getImportConfigs(); if (importConfigs && importConfigs[fileName]) { var result = importConfigs[fileName]; if (result) { result = JSON.stringify(result); callback(null, result); return; } } } var url = item.url; url = urlAppendTimestamp(url); var xhr = cc.loader.getXMLHttpRequest(), errInfo = "Load text file failed: " + url; xhr.open("GET", url, true); xhr.overrideMimeType && xhr.overrideMimeType("text/plain; charset=utf-8"); xhr.onload = function() { 4 === xhr.readyState ? 200 === xhr.status || 0 === xhr.status ? callback(null, xhr.responseText) : callback({ status: xhr.status, errorMessage: errInfo + "(wrong status)" }) : callback({ status: xhr.status, errorMessage: errInfo + "(wrong readyState)" }); }; xhr.onerror = function() { callback({ status: xhr.status, errorMessage: errInfo + "(error)" }); }; xhr.ontimeout = function() { callback({ status: xhr.status, errorMessage: errInfo + "(time out)" }); }; xhr.send(null); }; }), { "./utils": 130 } ], 129: [ (function(require, module, exports) { var Texture2D = require("../assets/CCTexture2D"); var js = require("../platform/js"); function JsonUnpacker() { this.jsons = {}; } JsonUnpacker.prototype.load = function(indices, packedJson) { packedJson.length !== indices.length && cc.errorID(4915); for (var i = 0; i < indices.length; i++) { var key = indices[i]; var json = packedJson[i]; this.jsons[key] = json; } }; JsonUnpacker.prototype.retrieve = function(key) { return this.jsons[key] || null; }; function TextureUnpacker() { this.contents = {}; } TextureUnpacker.ID = js._getClassId(Texture2D); TextureUnpacker.prototype.load = function(indices, packedJson) { var datas = packedJson.data.split("|"); datas.length !== indices.length && cc.errorID(4915); for (var i = 0; i < indices.length; i++) this.contents[indices[i]] = datas[i]; }; TextureUnpacker.prototype.retrieve = function(key) { var content = this.contents[key]; return content ? { __type__: TextureUnpacker.ID, content: content } : null; }; false; module.exports = { JsonUnpacker: JsonUnpacker, TextureUnpacker: TextureUnpacker }; }), { "../assets/CCTexture2D": 50, "../platform/js": 181 } ], 130: [ (function(require, module, exports) { var _noCacheRex = /\?/; module.exports = { urlAppendTimestamp: function(url) { cc.game.config["noCache"] && "string" === (__typeofVal = typeof url, "object" === __typeofVal ? __realTypeOfObj(url) : __typeofVal) && (_noCacheRex.test(url) ? url += "&_t=" + (new Date() - 0) : url += "?_t=" + (new Date() - 0)); return url; } }; }), {} ], 131: [ (function(require, module, exports) { var js = require("../platform/js"); var debug = require("../CCDebug"); require("../platform/deserialize"); var LoadingItems = require("./loading-items"); function isSceneObj(json) { var SCENE_ID = "cc.Scene"; var PREFAB_ID = "cc.Prefab"; return json && (json[0] && json[0].__type__ === SCENE_ID || json[1] && json[1].__type__ === SCENE_ID || json[0] && json[0].__type__ === PREFAB_ID); } function parseDepends(item, asset, tdInfo, deferredLoadRawAssetsInRuntime) { var uuidList = tdInfo.uuidList; var objList = tdInfo.uuidObjList; var propList = tdInfo.uuidPropList; var stillUseUrl = tdInfo._stillUseUrl; var depends; var i, dependUuid; var dependKeys = item.dependKeys = []; if (deferredLoadRawAssetsInRuntime) { depends = []; for (i = 0; i < uuidList.length; i++) { dependUuid = uuidList[i]; var obj = objList[i]; var prop = propList[i]; var info = cc.AssetLibrary._getAssetInfoInRuntime(dependUuid); if (info.raw) { var url = info.url; obj[prop] = url; dependKeys.push(url); } else depends.push({ type: "uuid", uuid: dependUuid, deferredLoadRaw: true, _owner: obj, _ownerProp: prop, _stillUseUrl: stillUseUrl[i] }); } } else { depends = new Array(uuidList.length); for (i = 0; i < uuidList.length; i++) { dependUuid = uuidList[i]; depends[i] = { type: "uuid", uuid: dependUuid, _owner: objList[i], _ownerProp: propList[i], _stillUseUrl: stillUseUrl[i] }; } asset._native && !asset.constructor.preventPreloadNativeObject && depends.push({ url: asset.nativeUrl, _owner: asset, _ownerProp: "_nativeAsset" }); } return depends; } function loadDepends(pipeline, item, asset, depends, callback) { item.content = asset; var dependKeys = item.dependKeys; pipeline.flowInDeps(item, depends, (function(errors, items) { var item, missingAssetReporter; var itemsMap = items.map; for (var src in itemsMap) { item = itemsMap[src]; item.uuid && item.content && (item.content._uuid = item.uuid); } for (var i = 0; i < depends.length; i++) { var dep = depends[i]; var dependSrc = dep.uuid; var dependUrl = dep.url; var dependObj = dep._owner; var dependProp = dep._ownerProp; item = itemsMap[dependUrl]; if (!item) continue; var loadCallbackCtx = dep; function loadCallback(item) { var value = item.content; this._stillUseUrl && (value = value && cc.RawAsset.wasRawAssetType(value.constructor) ? value.nativeUrl : item.rawUrl); this._owner[this._ownerProp] = value; item.uuid !== asset._uuid && dependKeys.indexOf(item.id) < 0 && dependKeys.push(item.id); } if (item.complete || item.content) if (item.error) { var MissingObjectReporter; false; cc._throw(item.error); } else loadCallback.call(loadCallbackCtx, item); else { var queue = LoadingItems.getQueue(item); var list = queue._callbackTable[dependSrc]; list ? list.unshift(loadCallback, loadCallbackCtx) : queue.addListener(dependSrc, loadCallback, loadCallbackCtx); } } false; callback(errors, asset); })); } function canDeferredLoad(asset, item, isScene) { false; var res = item.deferredLoadRaw; if (res) asset instanceof cc.Asset && asset.constructor.preventDeferredLoadDependents && (res = false); else if (isScene && (asset instanceof cc.SceneAsset || asset instanceof cc.Prefab)) { res = asset.asyncLoadAssets; false; } return res; } var MissingClass; function loadUuid(item, callback) { false; var json; if ("string" === (__typeofVal = typeof item.content, "object" === __typeofVal ? __realTypeOfObj(item.content) : __typeofVal)) try { json = JSON.parse(item.content); } catch (e) { return new Error(debug.getError(4923, item.id, e.stack)); } else { if ("object" !== (__typeofVal = typeof item.content, "object" === __typeofVal ? __realTypeOfObj(item.content) : __typeofVal)) return new Error(debug.getError(4924)); json = item.content; } var classFinder; var isScene = isSceneObj(json); if (isScene) { false; classFinder = cc._MissingScript.safeFindClass; } else classFinder = function(id) { var cls = js._getClassById(id); if (cls) return cls; cc.warnID(4903, id); return Object; }; var tdInfo = cc.deserialize.Details.pool.get(); var asset; try { asset = cc.deserialize(json, tdInfo, { classFinder: classFinder, target: item.existingAsset, customEnv: item }); } catch (e) { cc.deserialize.Details.pool.put(tdInfo); var err = e + "\n" + e.stack; return new Error(debug.getError(4925, item.id, err)); } asset._uuid = item.uuid; false; var deferredLoad = canDeferredLoad(asset, item, isScene); var depends = parseDepends(item, asset, tdInfo, deferredLoad); cc.deserialize.Details.pool.put(tdInfo); if (0 === depends.length) return callback(null, asset); loadDepends(this.pipeline, item, asset, depends, callback); } module.exports = loadUuid; loadUuid.isSceneObj = isSceneObj; }), { "../CCDebug": 27, "../platform/deserialize": 176, "../platform/js": 181, "./loading-items": 122 } ], 132: [ (function(require, module, exports) { 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 callResetInTryCatch = false; var callOnFocusInTryCatch = false; var callOnLostFocusInTryCatch = false; var callPreload = "c.__preload();"; var callOnLoad = "c.onLoad();c._objFlags|=" + IsOnLoadCalled; var UnsortedInvoker = cc.Class({ extends: CompScheduler.LifeCycleInvoker, add: function(comp) { this._zero.array.push(comp); }, remove: function(comp) { this._zero.fastRemove(comp); }, cancelInactive: function(flagToClear) { CompScheduler.LifeCycleInvoker.stableRemoveInactive(this._zero, flagToClear); }, invoke: function() { this._invoke(this._zero); this._zero.array.length = 0; } }); var invokePreload = CompScheduler.createInvokeImpl(callPreload); var invokeOnLoad = CompScheduler.createInvokeImpl(callOnLoad); 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(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; } } for (var _i = 0, len = node._children.length; _i < len; ++_i) { var child = node._children[_i]; child._active && this._activateNodeRecursively(child, preloadInvoker, onLoadInvoker, onEnableInvoker); } node._onPostActivated(true); }, _deactivateNodeRecursively: function(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(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": 62, "./platform/CCObject": 167, "./platform/js": 181, "./utils/misc": 243 } ], 133: [ (function(require, module, exports) { var PTM_RATIO = require("./CCPhysicsTypes").PTM_RATIO; var ContactType = require("./CCPhysicsTypes").ContactType; var pools = []; var pointCache = [ cc.v2(), cc.v2() ]; var b2worldmanifold = new b2.WorldManifold(); var worldmanifold = { points: [], separations: [], normal: cc.v2() }; function ManifoldPoint() { this.localPoint = cc.v2(); this.normalImpulse = 0; this.tangentImpulse = 0; } var manifoldPointCache = [ new ManifoldPoint(), new ManifoldPoint() ]; var b2manifold = new b2.Manifold(); var manifold = { type: 0, localPoint: cc.v2(), localNormal: cc.v2(), points: [] }; var impulse = { normalImpulses: [], tangentImpulses: [] }; function PhysicsContact() {} PhysicsContact.prototype.init = function(b2contact) { this.colliderA = b2contact.GetFixtureA().collider; this.colliderB = b2contact.GetFixtureB().collider; this.disabled = false; this.disabledOnce = false; this._impulse = null; this._inverted = false; this._b2contact = b2contact; b2contact._contact = this; }; PhysicsContact.prototype.reset = function() { this.setTangentSpeed(0); this.resetFriction(); this.resetRestitution(); this.colliderA = null; this.colliderB = null; this.disabled = false; this._impulse = null; this._b2contact._contact = null; this._b2contact = null; }; PhysicsContact.prototype.getWorldManifold = function() { var points = worldmanifold.points; var separations = worldmanifold.separations; var normal = worldmanifold.normal; this._b2contact.GetWorldManifold(b2worldmanifold); var b2points = b2worldmanifold.points; var b2separations = b2worldmanifold.separations; var count = this._b2contact.GetManifold().pointCount; points.length = separations.length = count; for (var i = 0; i < count; i++) { var p = pointCache[i]; p.x = b2points[i].x * PTM_RATIO; p.y = b2points[i].y * PTM_RATIO; points[i] = p; separations[i] = b2separations[i] * PTM_RATIO; } normal.x = b2worldmanifold.normal.x; normal.y = b2worldmanifold.normal.y; if (this._inverted) { normal.x *= -1; normal.y *= -1; } return worldmanifold; }; PhysicsContact.prototype.getManifold = function() { var points = manifold.points; var localNormal = manifold.localNormal; var localPoint = manifold.localPoint; var b2manifold = this._b2contact.GetManifold(); var b2points = b2manifold.points; var count = points.length = b2manifold.pointCount; for (var i = 0; i < count; i++) { var p = manifoldPointCache[i]; var b2p = b2points[i]; p.localPoint.x = b2p.localPoint.x * PTM_RATIO; p.localPoint.Y = b2p.localPoint.Y * PTM_RATIO; p.normalImpulse = b2p.normalImpulse * PTM_RATIO; p.tangentImpulse = b2p.tangentImpulse; points[i] = p; } localPoint.x = b2manifold.localPoint.x * PTM_RATIO; localPoint.y = b2manifold.localPoint.y * PTM_RATIO; localNormal.x = b2manifold.localNormal.x; localNormal.y = b2manifold.localNormal.y; manifold.type = b2manifold.type; if (this._inverted) { localNormal.x *= -1; localNormal.y *= -1; } return manifold; }; PhysicsContact.prototype.getImpulse = function() { var b2impulse = this._impulse; if (!b2impulse) return null; var normalImpulses = impulse.normalImpulses; var tangentImpulses = impulse.tangentImpulses; var count = b2impulse.count; for (var i = 0; i < count; i++) { normalImpulses[i] = b2impulse.normalImpulses[i] * PTM_RATIO; tangentImpulses[i] = b2impulse.tangentImpulses[i]; } tangentImpulses.length = normalImpulses.length = count; return impulse; }; PhysicsContact.prototype.emit = function(contactType) { var func; switch (contactType) { case ContactType.BEGIN_CONTACT: func = "onBeginContact"; break; case ContactType.END_CONTACT: func = "onEndContact"; break; case ContactType.PRE_SOLVE: func = "onPreSolve"; break; case ContactType.POST_SOLVE: func = "onPostSolve"; } var colliderA = this.colliderA; var colliderB = this.colliderB; var bodyA = colliderA.body; var bodyB = colliderB.body; var comps; var i, l, comp; if (bodyA.enabledContactListener) { comps = bodyA.node._components; this._inverted = false; for (i = 0, l = comps.length; i < l; i++) { comp = comps[i]; comp[func] && comp[func](this, colliderA, colliderB); } } if (bodyB.enabledContactListener) { comps = bodyB.node._components; this._inverted = true; for (i = 0, l = comps.length; i < l; i++) { comp = comps[i]; comp[func] && comp[func](this, colliderB, colliderA); } } if (this.disabled || this.disabledOnce) { this.setEnabled(false); this.disabledOnce = false; } }; PhysicsContact.get = function(b2contact) { var c; c = 0 === pools.length ? new cc.PhysicsContact() : pools.pop(); c.init(b2contact); return c; }; PhysicsContact.put = function(b2contact) { var c = b2contact._contact; if (!c) return; pools.push(c); c.reset(); }; var _p = PhysicsContact.prototype; _p.setEnabled = function(value) { this._b2contact.SetEnabled(value); }; _p.isTouching = function() { return this._b2contact.IsTouching(); }; _p.setTangentSpeed = function(value) { this._b2contact.SetTangentSpeed(value / PTM_RATIO); }; _p.getTangentSpeed = function() { return this._b2contact.GetTangentSpeed() * PTM_RATIO; }; _p.setFriction = function(value) { this._b2contact.SetFriction(value); }; _p.getFriction = function() { return this._b2contact.GetFriction(); }; _p.resetFriction = function() { return this._b2contact.ResetFriction(); }; _p.setRestitution = function(value) { this._b2contact.SetRestitution(value); }; _p.getRestitution = function() { return this._b2contact.GetRestitution(); }; _p.resetRestitution = function() { return this._b2contact.ResetRestitution(); }; PhysicsContact.ContactType = ContactType; cc.PhysicsContact = module.exports = PhysicsContact; }), { "./CCPhysicsTypes": 135 } ], 134: [ (function(require, module, exports) { var PhysicsTypes = require("./CCPhysicsTypes"); var ContactType = PhysicsTypes.ContactType; var BodyType = PhysicsTypes.BodyType; var RayCastType = PhysicsTypes.RayCastType; var DrawBits = PhysicsTypes.DrawBits; var PTM_RATIO = PhysicsTypes.PTM_RATIO; var ANGLE_TO_PHYSICS_ANGLE = PhysicsTypes.ANGLE_TO_PHYSICS_ANGLE; var PHYSICS_ANGLE_TO_ANGLE = PhysicsTypes.PHYSICS_ANGLE_TO_ANGLE; var convertToNodeRotation = require("./utils").convertToNodeRotation; var DebugDraw = require("./platform/CCPhysicsDebugDraw"); var b2_aabb_tmp = new b2.AABB(); var b2_vec2_tmp1 = new b2.Vec2(); var b2_vec2_tmp2 = new b2.Vec2(); var vec2_tmp = cc.v2(); var PhysicsManager = cc.Class({ mixins: [ cc.EventTarget ], statics: { DrawBits: DrawBits, PTM_RATIO: PTM_RATIO, VELOCITY_ITERATIONS: 10, POSITION_ITERATIONS: 10, FIXED_TIME_STEP: 1 / 60, MAX_ACCUMULATOR: .2 }, ctor: function() { this._debugDrawFlags = 0; this._debugDrawer = null; this._world = null; this._bodies = []; this._joints = []; this._contactMap = {}; this._contactID = 0; this._delayEvents = []; this._accumulator = 0; cc.director._scheduler && cc.director._scheduler.enableForTarget(this); this.enabledAccumulator = false; }, pushDelayEvent: function(target, func, args) { this._steping ? this._delayEvents.push({ target: target, func: func, args: args }) : target[func].apply(target, args); }, update: function(dt) { var world = this._world; if (!world || !this.enabled) return; this.emit("before-step"); this._steping = true; var velocityIterations = PhysicsManager.VELOCITY_ITERATIONS; var positionIterations = PhysicsManager.POSITION_ITERATIONS; if (this.enabledAccumulator) { this._accumulator += dt; var FIXED_TIME_STEP = PhysicsManager.FIXED_TIME_STEP; var MAX_ACCUMULATOR = PhysicsManager.MAX_ACCUMULATOR; this._accumulator > MAX_ACCUMULATOR && (this._accumulator = MAX_ACCUMULATOR); while (this._accumulator > FIXED_TIME_STEP) { world.Step(FIXED_TIME_STEP, velocityIterations, positionIterations); this._accumulator -= FIXED_TIME_STEP; } } else { var timeStep = 1 / cc.game.config["frameRate"]; world.Step(timeStep, velocityIterations, positionIterations); } if (this.debugDrawFlags) { this._checkDebugDrawValid(); this._debugDrawer.clear(); world.DrawDebugData(); } this._steping = false; var events = this._delayEvents; for (var i = 0, l = events.length; i < l; i++) { var event = events[i]; event.target[event.func].apply(event.target, event.args); } events.length = 0; this._syncNode(); }, testPoint: function(point) { var x = b2_vec2_tmp1.x = point.x / PTM_RATIO; var y = b2_vec2_tmp1.y = point.y / PTM_RATIO; var d = .2 / PTM_RATIO; b2_aabb_tmp.lowerBound.x = x - d; b2_aabb_tmp.lowerBound.y = y - d; b2_aabb_tmp.upperBound.x = x + d; b2_aabb_tmp.upperBound.y = y + d; var callback = this._aabbQueryCallback; callback.init(b2_vec2_tmp1); this._world.QueryAABB(callback, b2_aabb_tmp); var fixture = callback.getFixture(); if (fixture) return fixture.collider; return null; }, testAABB: function(rect) { b2_aabb_tmp.lowerBound.x = rect.xMin / PTM_RATIO; b2_aabb_tmp.lowerBound.y = rect.yMin / PTM_RATIO; b2_aabb_tmp.upperBound.x = rect.xMax / PTM_RATIO; b2_aabb_tmp.upperBound.y = rect.yMax / PTM_RATIO; var callback = this._aabbQueryCallback; callback.init(); this._world.QueryAABB(callback, b2_aabb_tmp); var fixtures = callback.getFixtures(); var colliders = fixtures.map((function(fixture) { return fixture.collider; })); return colliders; }, rayCast: function(p1, p2, type) { if (p1.equals(p2)) return []; type = type || RayCastType.Closest; b2_vec2_tmp1.x = p1.x / PTM_RATIO; b2_vec2_tmp1.y = p1.y / PTM_RATIO; b2_vec2_tmp2.x = p2.x / PTM_RATIO; b2_vec2_tmp2.y = p2.y / PTM_RATIO; var callback = this._raycastQueryCallback; callback.init(type); this._world.RayCast(callback, b2_vec2_tmp1, b2_vec2_tmp2); var fixtures = callback.getFixtures(); if (fixtures.length > 0) { var points = callback.getPoints(); var normals = callback.getNormals(); var fractions = callback.getFractions(); var results = []; for (var i = 0, l = fixtures.length; i < l; i++) { var fixture = fixtures[i]; var collider = fixture.collider; if (type === RayCastType.AllClosest) { var result = results.find((function(result) { return result.collider === collider; })); if (result) { if (fractions[i] < result.fraction) { result.fixtureIndex = collider._getFixtureIndex(fixture); result.point.x = points[i].x * PTM_RATIO; result.point.y = points[i].y * PTM_RATIO; result.normal.x = normals[i].x; result.normal.y = normals[i].y; result.fraction = fractions[i]; } continue; } } results.push({ collider: collider, fixtureIndex: collider._getFixtureIndex(fixture), point: cc.v2(points[i].x * PTM_RATIO, points[i].y * PTM_RATIO), normal: cc.v2(normals[i]), fraction: fractions[i] }); } return results; } return []; }, syncPosition: function() { var bodies = this._bodies; for (var i = 0; i < bodies.length; i++) bodies[i].syncPosition(); }, syncRotation: function() { var bodies = this._bodies; for (var i = 0; i < bodies.length; i++) bodies[i].syncRotation(); }, _registerContactFixture: function(fixture) { this._contactListener.registerContactFixture(fixture); }, _unregisterContactFixture: function(fixture) { this._contactListener.unregisterContactFixture(fixture); }, _addBody: function(body, bodyDef) { var world = this._world; var node = body.node; if (!world || !node) return; body._b2Body = world.CreateBody(bodyDef); body._b2Body.body = body; this._bodies.push(body); }, _removeBody: function(body) { var world = this._world; if (!world) return; body._b2Body.body = null; world.DestroyBody(body._b2Body); body._b2Body = null; cc.js.array.remove(this._bodies, body); }, _addJoint: function(joint, jointDef) { var b2joint = this._world.CreateJoint(jointDef); if (!b2joint) return; b2joint._joint = joint; joint._joint = b2joint; this._joints.push(joint); }, _removeJoint: function(joint) { joint._isValid() && this._world.DestroyJoint(joint._joint); joint._joint && (joint._joint._joint = null); cc.js.array.remove(this._joints, joint); }, _initCallback: function() { if (!this._world) { cc.warn("Please init PhysicsManager first"); return; } if (this._contactListener) return; var listener = new cc.PhysicsContactListener(); listener.setBeginContact(this._onBeginContact); listener.setEndContact(this._onEndContact); listener.setPreSolve(this._onPreSolve); listener.setPostSolve(this._onPostSolve); this._world.SetContactListener(listener); this._contactListener = listener; this._aabbQueryCallback = new cc.PhysicsAABBQueryCallback(); this._raycastQueryCallback = new cc.PhysicsRayCastCallback(); }, _init: function() { this.enabled = true; this.debugDrawFlags = DrawBits.e_shapeBit; }, _getWorld: function() { return this._world; }, _syncNode: function() { var bodies = this._bodies; for (var i = 0, l = bodies.length; i < l; i++) { var body = bodies[i]; var node = body.node; var b2body = body._b2Body; var pos = b2body.GetPosition(); vec2_tmp.x = pos.x * PTM_RATIO; vec2_tmp.y = pos.y * PTM_RATIO; var angle = b2body.GetAngle() * PHYSICS_ANGLE_TO_ANGLE; if (null !== node.parent.parent) { vec2_tmp = node.parent.convertToNodeSpaceAR(vec2_tmp); angle = convertToNodeRotation(node.parent, angle); } var tempMask = node._eventMask; node._eventMask = 0; node.position = vec2_tmp; node.rotation = angle; node._eventMask = tempMask; body.type === BodyType.Animated && body.resetVelocity(); } }, _onBeginContact: function(b2contact) { var c = cc.PhysicsContact.get(b2contact); c.emit(ContactType.BEGIN_CONTACT); }, _onEndContact: function(b2contact) { var c = b2contact._contact; if (!c) return; c.emit(ContactType.END_CONTACT); cc.PhysicsContact.put(b2contact); }, _onPreSolve: function(b2contact) { var c = b2contact._contact; if (!c) return; c.emit(ContactType.PRE_SOLVE); }, _onPostSolve: function(b2contact, impulse) { var c = b2contact._contact; if (!c) return; c._impulse = impulse; c.emit(ContactType.POST_SOLVE); c._impulse = null; }, _checkDebugDrawValid: function() { if (!this._debugDrawer || !this._debugDrawer.isValid) { var node = new cc.Node("PHYSICS_MANAGER_DEBUG_DRAW"); node.zIndex = cc.macro.MAX_ZINDEX; cc.game.addPersistRootNode(node); this._debugDrawer = node.addComponent(cc.Graphics); var debugDraw = new DebugDraw(this._debugDrawer); debugDraw.SetFlags(this.debugDrawFlags); this._world.SetDebugDraw(debugDraw); } } }); cc.js.getset(PhysicsManager.prototype, "enabled", (function() { return this._enabled; }), (function(value) { false; if (value && !this._world) { var world = new b2.World(new b2.Vec2(0, -10)); world.SetAllowSleeping(true); this._world = world; this._initCallback(); } this._enabled = value; })); cc.js.getset(PhysicsManager.prototype, "debugDrawFlags", (function() { return this._debugDrawFlags; }), (function(value) { false; value && !this._debugDrawFlags ? this._debugDrawer && this._debugDrawer.node && (this._debugDrawer.node.active = true) : !value && this._debugDrawFlags && this._debugDrawer && this._debugDrawer.node && (this._debugDrawer.node.active = false); if (value) { this._checkDebugDrawValid(); this._world.m_debugDraw.SetFlags(value); } this._debugDrawFlags = value; if (value) { this._checkDebugDrawValid(); this._world.m_debugDraw.SetFlags(value); } })); cc.js.getset(PhysicsManager.prototype, "gravity", (function() { if (this._world) { var g = this._world.GetGravity(); return cc.v2(g.x * PTM_RATIO, g.y * PTM_RATIO); } return cc.v2(); }), (function(value) { this._world && this._world.SetGravity(new b2.Vec2(value.x / PTM_RATIO, value.y / PTM_RATIO)); })); cc.PhysicsManager = module.exports = PhysicsManager; }), { "./CCPhysicsTypes": 135, "./platform/CCPhysicsDebugDraw": 156, "./utils": 158 } ], 135: [ (function(require, module, exports) { var ContactType = { BEGIN_CONTACT: "begin-contact", END_CONTACT: "end-contact", PRE_SOLVE: "pre-solve", POST_SOLVE: "post-solve" }; var BodyType = cc.Enum({ Static: 0, Kinematic: 1, Dynamic: 2, Animated: 3 }); cc.RigidBodyType = BodyType; var RayCastType = cc.Enum({ Closest: 0, Any: 1, AllClosest: 2, All: 3 }); cc.RayCastType = RayCastType; module.exports = { BodyType: BodyType, ContactType: ContactType, RayCastType: RayCastType, DrawBits: b2.DrawFlags, PTM_RATIO: 32, ANGLE_TO_PHYSICS_ANGLE: -Math.PI / 180, PHYSICS_ANGLE_TO_ANGLE: -180 / Math.PI }; }), {} ], 136: [ (function(require, module, exports) { function At(i, vertices) { var s = vertices.length; return vertices[i < 0 ? s - -i % s : i % s]; } function Copy(i, j, vertices) { var p = []; while (j < i) j += vertices.length; for (;i <= j; ++i) p.push(At(i, vertices)); return p; } function ConvexPartition(vertices) { ForceCounterClockWise(vertices); var list = []; var d, lowerDist, upperDist; var p; var lowerInt = cc.v2(); var upperInt = cc.v2(); var lowerIndex = 0, upperIndex = 0; var lowerPoly, upperPoly; for (var i = 0; i < vertices.length; ++i) if (Reflex(i, vertices)) { lowerDist = upperDist = 1e8; for (var j = 0; j < vertices.length; ++j) { if (Left(At(i - 1, vertices), At(i, vertices), At(j, vertices)) && RightOn(At(i - 1, vertices), At(i, vertices), At(j - 1, vertices))) { p = LineIntersect(At(i - 1, vertices), At(i, vertices), At(j, vertices), At(j - 1, vertices)); if (Right(At(i + 1, vertices), At(i, vertices), p)) { d = SquareDist(At(i, vertices), p); if (d < lowerDist) { lowerDist = d; lowerInt = p; lowerIndex = j; } } } if (Left(At(i + 1, vertices), At(i, vertices), At(j + 1, vertices)) && RightOn(At(i + 1, vertices), At(i, vertices), At(j, vertices))) { p = LineIntersect(At(i + 1, vertices), At(i, vertices), At(j, vertices), At(j + 1, vertices)); if (Left(At(i - 1, vertices), At(i, vertices), p)) { d = SquareDist(At(i, vertices), p); if (d < upperDist) { upperDist = d; upperIndex = j; upperInt = p; } } } } if (lowerIndex == (upperIndex + 1) % vertices.length) { var sp = lowerInt.add(upperInt).div(2); lowerPoly = Copy(i, upperIndex, vertices); lowerPoly.push(sp); upperPoly = Copy(lowerIndex, i, vertices); upperPoly.push(sp); } else { var highestScore = 0, bestIndex = lowerIndex; while (upperIndex < lowerIndex) upperIndex += vertices.length; for (var j = lowerIndex; j <= upperIndex; ++j) if (CanSee(i, j, vertices)) { var score = 1 / (SquareDist(At(i, vertices), At(j, vertices)) + 1); Reflex(j, vertices) ? RightOn(At(j - 1, vertices), At(j, vertices), At(i, vertices)) && LeftOn(At(j + 1, vertices), At(j, vertices), At(i, vertices)) ? score += 3 : score += 2 : score += 1; if (score > highestScore) { bestIndex = j; highestScore = score; } } lowerPoly = Copy(i, bestIndex, vertices); upperPoly = Copy(bestIndex, i, vertices); } list = list.concat(ConvexPartition(lowerPoly)); list = list.concat(ConvexPartition(upperPoly)); return list; } list.push(vertices); for (var i = list.length - 1; i >= 0; i--) 0 == list[i].length && list.splice(i, 0); return list; } function CanSee(i, j, vertices) { if (Reflex(i, vertices)) { if (LeftOn(At(i, vertices), At(i - 1, vertices), At(j, vertices)) && RightOn(At(i, vertices), At(i + 1, vertices), At(j, vertices))) return false; } else if (RightOn(At(i, vertices), At(i + 1, vertices), At(j, vertices)) || LeftOn(At(i, vertices), At(i - 1, vertices), At(j, vertices))) return false; if (Reflex(j, vertices)) { if (LeftOn(At(j, vertices), At(j - 1, vertices), At(i, vertices)) && RightOn(At(j, vertices), At(j + 1, vertices), At(i, vertices))) return false; } else if (RightOn(At(j, vertices), At(j + 1, vertices), At(i, vertices)) || LeftOn(At(j, vertices), At(j - 1, vertices), At(i, vertices))) return false; for (var k = 0; k < vertices.length; ++k) { if ((k + 1) % vertices.length == i || k == i || (k + 1) % vertices.length == j || k == j) continue; var intersectionPoint = cc.v2(); if (LineIntersect2(At(i, vertices), At(j, vertices), At(k, vertices), At(k + 1, vertices), intersectionPoint)) return false; } return true; } function Reflex(i, vertices) { return Right(i, vertices); } function Right(a, b, c) { if ("undefined" === (__typeofVal = typeof c, "object" === __typeofVal ? __realTypeOfObj(c) : __typeofVal)) { var i = a, vertices = b; a = At(i - 1, vertices); b = At(i, vertices); c = At(i + 1, vertices); } return Area(a, b, c) < 0; } function Left(a, b, c) { return Area(a, b, c) > 0; } function LeftOn(a, b, c) { return Area(a, b, c) >= 0; } function RightOn(a, b, c) { return Area(a, b, c) <= 0; } function SquareDist(a, b) { var dx = b.x - a.x; var dy = b.y - a.y; return dx * dx + dy * dy; } function ForceCounterClockWise(vertices) { IsCounterClockWise(vertices) || vertices.reverse(); } function IsCounterClockWise(vertices) { if (vertices.length < 3) return true; return GetSignedArea(vertices) > 0; } function GetSignedArea(vertices) { var i; var area = 0; for (i = 0; i < vertices.length; i++) { var j = (i + 1) % vertices.length; area += vertices[i].x * vertices[j].y; area -= vertices[i].y * vertices[j].x; } area /= 2; return area; } function LineIntersect(p1, p2, q1, q2) { var i = cc.v2(); var a1 = p2.y - p1.y; var b1 = p1.x - p2.x; var c1 = a1 * p1.x + b1 * p1.y; var a2 = q2.y - q1.y; var b2 = q1.x - q2.x; var c2 = a2 * q1.x + b2 * q1.y; var det = a1 * b2 - a2 * b1; if (!FloatEquals(det, 0)) { i.x = (b2 * c1 - b1 * c2) / det; i.y = (a1 * c2 - a2 * c1) / det; } return i; } function LineIntersect2(a0, a1, b0, b1, intersectionPoint) { if (a0 == b0 || a0 == b1 || a1 == b0 || a1 == b1) return false; var x1 = a0.x; var y1 = a0.y; var x2 = a1.x; var y2 = a1.y; var x3 = b0.x; var y3 = b0.y; var x4 = b1.x; var y4 = b1.y; if (Math.max(x1, x2) < Math.min(x3, x4) || Math.max(x3, x4) < Math.min(x1, x2)) return false; if (Math.max(y1, y2) < Math.min(y3, y4) || Math.max(y3, y4) < Math.min(y1, y2)) return false; var ua = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3); var ub = (x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3); var denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1); if (Math.abs(denom) < 1e-6) return false; ua /= denom; ub /= denom; if (0 < ua && ua < 1 && 0 < ub && ub < 1) { intersectionPoint.x = x1 + ua * (x2 - x1); intersectionPoint.y = y1 + ua * (y2 - y1); return true; } return false; } function FloatEquals(value1, value2) { return Math.abs(value1 - value2) <= 1e-6; } function Area(a, b, c) { return a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y); } module.exports = { ConvexPartition: ConvexPartition, ForceCounterClockWise: ForceCounterClockWise, IsCounterClockWise: IsCounterClockWise }; }), {} ], 137: [ (function(require, module, exports) { var NodeEvent = require("../CCNode").EventType; var PTM_RATIO = require("./CCPhysicsTypes").PTM_RATIO; var ANGLE_TO_PHYSICS_ANGLE = require("./CCPhysicsTypes").ANGLE_TO_PHYSICS_ANGLE; var PHYSICS_ANGLE_TO_ANGLE = require("./CCPhysicsTypes").PHYSICS_ANGLE_TO_ANGLE; var getWorldRotation = require("./utils").getWorldRotation; var BodyType = require("./CCPhysicsTypes").BodyType; var tempb2Vec21 = new b2.Vec2(); var tempb2Vec22 = new b2.Vec2(); var VEC2_ZERO = cc.Vec2.ZERO; var RigidBody = cc.Class({ name: "cc.RigidBody", extends: cc.Component, editor: false, properties: { _type: BodyType.Dynamic, _allowSleep: true, _gravityScale: 1, _linearDamping: 0, _angularDamping: 0, _linearVelocity: cc.v2(0, 0), _angularVelocity: 0, _fixedRotation: false, enabled: { get: function() { return this._enabled; }, set: function() { cc.warnID(8200); }, visible: false, override: true }, enabledContactListener: { default: false, tooltip: false }, bullet: { default: false, tooltip: false }, type: { type: BodyType, tooltip: false, get: function() { return this._type; }, set: function(value) { this._type = value; this._b2Body && (value === BodyType.Animated ? this._b2Body.SetType(BodyType.Kinematic) : this._b2Body.SetType(value)); } }, allowSleep: { tooltip: false, get: function() { if (this._b2Body) return this._b2Body.IsSleepingAllowed(); return this._allowSleep; }, set: function(value) { this._allowSleep = value; this._b2Body && this._b2Body.SetSleepingAllowed(value); } }, gravityScale: { tooltip: false, get: function() { return this._gravityScale; }, set: function(value) { this._gravityScale = value; this._b2Body && this._b2Body.SetGravityScale(value); } }, linearDamping: { tooltip: false, get: function() { return this._linearDamping; }, set: function(value) { this._linearDamping = value; this._b2Body && this._b2Body.SetLinearDamping(this._linearDamping); } }, angularDamping: { tooltip: false, get: function() { return this._angularDamping; }, set: function(value) { this._angularDamping = value; this._b2Body && this._b2Body.SetAngularDamping(value); } }, linearVelocity: { tooltip: false, type: cc.Vec2, get: function() { var lv = this._linearVelocity; if (this._b2Body) { var velocity = this._b2Body.GetLinearVelocity(); lv.x = velocity.x * PTM_RATIO; lv.y = velocity.y * PTM_RATIO; } return lv; }, set: function(value) { this._linearVelocity = value; var b2body = this._b2Body; if (b2body) { var temp = b2body.m_linearVelocity; temp.Set(value.x / PTM_RATIO, value.y / PTM_RATIO); b2body.SetLinearVelocity(temp); } } }, angularVelocity: { tooltip: false, get: function() { if (this._b2Body) return this._b2Body.GetAngularVelocity() * PHYSICS_ANGLE_TO_ANGLE; return this._angularVelocity; }, set: function(value) { this._angularVelocity = value; this._b2Body && this._b2Body.SetAngularVelocity(value * ANGLE_TO_PHYSICS_ANGLE); } }, fixedRotation: { tooltip: false, get: function() { return this._fixedRotation; }, set: function(value) { this._fixedRotation = value; this._b2Body && this._b2Body.SetFixedRotation(value); } }, awake: { visible: false, tooltip: false, get: function() { return !!this._b2Body && this._b2Body.IsAwake(); }, set: function(value) { this._b2Body && this._b2Body.SetAwake(value); } }, awakeOnLoad: { default: true, tooltip: false, animatable: false }, active: { visible: false, get: function() { return !!this._b2Body && this._b2Body.IsActive(); }, set: function(value) { this._b2Body && this._b2Body.SetActive(value); } } }, getLocalPoint: function(worldPoint, out) { out = out || cc.v2(); if (this._b2Body) { tempb2Vec21.Set(worldPoint.x / PTM_RATIO, worldPoint.y / PTM_RATIO); var pos = this._b2Body.GetLocalPoint(tempb2Vec21, out); out.x = pos.x * PTM_RATIO; out.y = pos.y * PTM_RATIO; } return out; }, getWorldPoint: function(localPoint, out) { out = out || cc.v2(); if (this._b2Body) { tempb2Vec21.Set(localPoint.x / PTM_RATIO, localPoint.y / PTM_RATIO); var pos = this._b2Body.GetWorldPoint(tempb2Vec21, out); out.x = pos.x * PTM_RATIO; out.y = pos.y * PTM_RATIO; } return out; }, getWorldVector: function(localVector, out) { out = out || cc.v2(); if (this._b2Body) { tempb2Vec21.Set(localVector.x / PTM_RATIO, localVector.y / PTM_RATIO); var vector = this._b2Body.GetWorldVector(tempb2Vec21, out); out.x = vector.x * PTM_RATIO; out.y = vector.y * PTM_RATIO; } return out; }, getLocalVector: function(worldVector, out) { out = out || cc.v2(); if (this._b2Body) { tempb2Vec21.Set(worldVector.x / PTM_RATIO, worldVector.y / PTM_RATIO); var vector = this._b2Body.GetLocalVector(tempb2Vec21, out); out.x = vector.x * PTM_RATIO; out.y = vector.y * PTM_RATIO; } return out; }, getWorldPosition: function(out) { out = out || cc.v2(); if (this._b2Body) { var pos = this._b2Body.GetPosition(); out.x = pos.x * PTM_RATIO; out.y = pos.y * PTM_RATIO; } return out; }, getWorldRotation: function() { if (this._b2Body) return this._b2Body.GetAngle() * PHYSICS_ANGLE_TO_ANGLE; return 0; }, getLocalCenter: function(out) { out = out || cc.v2(); if (this._b2Body) { var pos = this._b2Body.GetLocalCenter(); out.x = pos.x * PTM_RATIO; out.y = pos.y * PTM_RATIO; } return out; }, getWorldCenter: function(out) { out = out || cc.v2(); if (this._b2Body) { var pos = this._b2Body.GetWorldCenter(); out.x = pos.x * PTM_RATIO; out.y = pos.y * PTM_RATIO; } return out; }, getLinearVelocityFromWorldPoint: function(worldPoint, out) { out = out || cc.v2(); if (this._b2Body) { tempb2Vec21.Set(worldPoint.x / PTM_RATIO, worldPoint.y / PTM_RATIO); var velocity = this._b2Body.GetLinearVelocityFromWorldPoint(tempb2Vec21, out); out.x = velocity.x * PTM_RATIO; out.y = velocity.y * PTM_RATIO; } return out; }, getMass: function() { return this._b2Body ? this._b2Body.GetMass() : 0; }, getInertia: function() { return this._b2Body ? this._b2Body.GetInertia() * PTM_RATIO * PTM_RATIO : 0; }, getJointList: function() { if (!this._b2Body) return []; var joints = []; var list = this._b2Body.GetJointList(); if (!list) return []; joints.push(list.joint._joint); var prev = list.prev; while (prev) { joints.push(prev.joint._joint); prev = prev.prev; } var next = list.next; while (next) { joints.push(next.joint._joint); next = next.next; } return joints; }, applyForce: function(force, point, wake) { if (this._b2Body) { tempb2Vec21.Set(force.x / PTM_RATIO, force.y / PTM_RATIO); tempb2Vec22.Set(point.x / PTM_RATIO, point.y / PTM_RATIO); this._b2Body.ApplyForce(tempb2Vec21, tempb2Vec22, wake); } }, applyForceToCenter: function(force, wake) { if (this._b2Body) { tempb2Vec21.Set(force.x / PTM_RATIO, force.y / PTM_RATIO); this._b2Body.ApplyForceToCenter(tempb2Vec21, wake); } }, applyTorque: function(torque, wake) { this._b2Body && this._b2Body.ApplyTorque(torque / PTM_RATIO, wake); }, applyLinearImpulse: function(impulse, point, wake) { if (this._b2Body) { tempb2Vec21.Set(impulse.x / PTM_RATIO, impulse.y / PTM_RATIO); tempb2Vec22.Set(point.x / PTM_RATIO, point.y / PTM_RATIO); this._b2Body.ApplyLinearImpulse(tempb2Vec21, tempb2Vec22, wake); } }, applyAngularImpulse: function(impulse, wake) { this._b2Body && this._b2Body.ApplyAngularImpulse(impulse / PTM_RATIO / PTM_RATIO, wake); }, syncPosition: function(enableAnimated) { var b2body = this._b2Body; if (!b2body) return; var pos = this.node.convertToWorldSpaceAR(VEC2_ZERO); var temp; temp = this.type === BodyType.Animated ? b2body.GetLinearVelocity() : b2body.GetPosition(); temp.x = pos.x / PTM_RATIO; temp.y = pos.y / PTM_RATIO; if (this.type === BodyType.Animated && enableAnimated) { var b2Pos = b2body.GetPosition(); var timeStep = cc.game.config["frameRate"]; temp.x = (temp.x - b2Pos.x) * timeStep; temp.y = (temp.y - b2Pos.y) * timeStep; b2body.SetAwake(true); b2body.SetLinearVelocity(temp); } else b2body.SetTransformVec(temp, b2body.GetAngle()); }, syncRotation: function(enableAnimated) { var b2body = this._b2Body; if (!b2body) return; var rotation = ANGLE_TO_PHYSICS_ANGLE * getWorldRotation(this.node); if (this.type === BodyType.Animated && enableAnimated) { var b2Rotation = b2body.GetAngle(); var timeStep = cc.game.config["frameRate"]; b2body.SetAwake(true); b2body.SetAngularVelocity((rotation - b2Rotation) * timeStep); } else b2body.SetTransformVec(b2body.GetPosition(), rotation); }, resetVelocity: function() { var b2body = this._b2Body; if (!b2body) return; var temp = b2body.m_linearVelocity; temp.Set(0, 0); b2body.SetLinearVelocity(temp); b2body.SetAngularVelocity(0); }, onEnable: function() { this._init(); }, onDisable: function() { this._destroy(); }, _registerNodeEvents: function() { var node = this.node; node.on(NodeEvent.POSITION_CHANGED, this._onNodePositionChanged, this); node.on(NodeEvent.ROTATION_CHANGED, this._onNodeRotationChanged, this); node.on(NodeEvent.SCALE_CHANGED, this._onNodeScaleChanged, this); }, _unregisterNodeEvents: function() { var node = this.node; node.off(NodeEvent.POSITION_CHANGED, this._onNodePositionChanged, this); node.off(NodeEvent.ROTATION_CHANGED, this._onNodeRotationChanged, this); node.off(NodeEvent.SCALE_CHANGED, this._onNodeScaleChanged, this); }, _onNodePositionChanged: function() { this.syncPosition(true); }, _onNodeRotationChanged: function(event) { this.syncRotation(true); }, _onNodeScaleChanged: function(event) { if (this._b2Body) { var colliders = this.getComponents(cc.PhysicsCollider); for (var i = 0; i < colliders.length; i++) colliders[i].apply(); } }, _init: function() { cc.director.getPhysicsManager().pushDelayEvent(this, "__init", []); }, _destroy: function() { cc.director.getPhysicsManager().pushDelayEvent(this, "__destroy", []); }, __init: function() { if (this._inited) return; this._registerNodeEvents(); var bodyDef = new b2.BodyDef(); this.type === BodyType.Animated ? bodyDef.type = BodyType.Kinematic : bodyDef.type = this.type; bodyDef.allowSleep = this.allowSleep; bodyDef.gravityScale = this.gravityScale; bodyDef.linearDamping = this.linearDamping; bodyDef.angularDamping = this.angularDamping; var linearVelocity = this.linearVelocity; bodyDef.linearVelocity = new b2.Vec2(linearVelocity.x / PTM_RATIO, linearVelocity.y / PTM_RATIO); bodyDef.angularVelocity = this.angularVelocity * ANGLE_TO_PHYSICS_ANGLE; bodyDef.fixedRotation = this.fixedRotation; bodyDef.bullet = this.bullet; var node = this.node; var pos = node.convertToWorldSpaceAR(VEC2_ZERO); bodyDef.position = new b2.Vec2(pos.x / PTM_RATIO, pos.y / PTM_RATIO); bodyDef.angle = -Math.PI / 180 * getWorldRotation(node); bodyDef.awake = this.awakeOnLoad; cc.director.getPhysicsManager()._addBody(this, bodyDef); this._inited = true; }, __destroy: function() { if (!this._inited) return; cc.director.getPhysicsManager()._removeBody(this); this._unregisterNodeEvents(); this._inited = false; }, _getBody: function() { return this._b2Body; } }); cc.RigidBody = module.exports = RigidBody; }), { "../CCNode": 30, "./CCPhysicsTypes": 135, "./utils": 158 } ], 138: [ (function(require, module, exports) { var box2d = require("../../../external/box2d/box2d"); window.b2 = {}; false; for (var key in box2d) { if (-1 !== key.indexOf("b2_")) continue; var newKey = key.replace("b2", ""); b2[newKey] = box2d[key]; } b2.maxPolygonVertices = 8; }), { "../../../external/box2d/box2d": 295 } ], 139: [ (function(require, module, exports) { var PTM_RATIO = require("../CCPhysicsTypes").PTM_RATIO; var PhysicsBoxCollider = cc.Class({ name: "cc.PhysicsBoxCollider", extends: cc.PhysicsCollider, mixins: [ cc.Collider.Box ], editor: { menu: false, requireComponent: cc.RigidBody }, _createShape: function(scale) { var scaleX = Math.abs(scale.x); var scaleY = Math.abs(scale.y); var width = this.size.width / 2 / PTM_RATIO * scaleX; var height = this.size.height / 2 / PTM_RATIO * scaleY; var offsetX = this.offset.x / PTM_RATIO * scaleX; var offsetY = this.offset.y / PTM_RATIO * scaleY; var shape = new b2.PolygonShape(); shape.SetAsBox(width, height, new b2.Vec2(offsetX, offsetY), 0); return shape; } }); cc.PhysicsBoxCollider = module.exports = PhysicsBoxCollider; }), { "../CCPhysicsTypes": 135 } ], 140: [ (function(require, module, exports) { var PTM_RATIO = require("../CCPhysicsTypes").PTM_RATIO; var PhysicsChainCollider = cc.Class({ name: "cc.PhysicsChainCollider", extends: cc.PhysicsCollider, editor: { menu: false, inspector: false, requireComponent: cc.RigidBody }, properties: { loop: false, points: { default: function() { return [ cc.v2(-50, 0), cc.v2(50, 0) ]; }, type: [ cc.Vec2 ] }, threshold: { default: 1, serializable: false, visible: false } }, _createShape: function(scale) { var shape = new b2.ChainShape(); var points = this.points; var vertices = []; for (var i = 0; i < points.length; i++) { var p = points[i]; vertices.push(new b2.Vec2(p.x / PTM_RATIO * scale.x, p.y / PTM_RATIO * scale.y)); } this.loop ? shape.CreateLoop(vertices, vertices.length) : shape.CreateChain(vertices, vertices.length); return shape; }, resetInEditor: false, resetPointsByContour: false }); cc.PhysicsChainCollider = module.exports = PhysicsChainCollider; }), { "../CCPhysicsTypes": 135 } ], 141: [ (function(require, module, exports) { var PTM_RATIO = require("../CCPhysicsTypes").PTM_RATIO; var PhysicsCircleCollider = cc.Class({ name: "cc.PhysicsCircleCollider", extends: cc.PhysicsCollider, mixins: [ cc.Collider.Circle ], editor: { menu: false, requireComponent: cc.RigidBody }, _createShape: function(scale) { var scaleX = Math.abs(scale.x); var scaleY = Math.abs(scale.y); var offsetX = this.offset.x / PTM_RATIO * scaleX; var offsetY = this.offset.y / PTM_RATIO * scaleY; var shape = new b2.CircleShape(); shape.m_radius = this.radius / PTM_RATIO * scaleX; shape.m_p = new b2.Vec2(offsetX, offsetY); return shape; } }); cc.PhysicsCircleCollider = module.exports = PhysicsCircleCollider; }), { "../CCPhysicsTypes": 135 } ], 142: [ (function(require, module, exports) { var PTM_RATIO = require("../CCPhysicsTypes").PTM_RATIO; var getWorldScale = require("../utils").getWorldScale; var PhysicsCollider = cc.Class({ name: "cc.PhysicsCollider", extends: cc.Collider, ctor: function() { this._fixtures = []; this._shapes = []; this._inited = false; this._rect = cc.rect(); }, properties: { _density: 1, _sensor: false, _friction: .2, _restitution: 0, density: { tooltip: false, get: function() { return this._density; }, set: function(value) { this._density = value; } }, sensor: { tooltip: false, get: function() { return this._sensor; }, set: function(value) { this._sensor = value; } }, friction: { tooltip: false, get: function() { return this._friction; }, set: function(value) { this._friction = value; } }, restitution: { tooltip: false, get: function() { return this._restitution; }, set: function(value) { this._restitution = value; } }, body: { default: null, type: cc.RigidBody, visible: false } }, onDisable: function() { this._destroy(); }, onEnable: function() { this._init(); }, start: function() { this._init(); }, _getFixtureIndex: function(fixture) { return this._fixtures.indexOf(fixture); }, _init: function() { cc.director.getPhysicsManager().pushDelayEvent(this, "__init", []); }, _destroy: function() { cc.director.getPhysicsManager().pushDelayEvent(this, "__destroy", []); }, __init: function() { if (this._inited) return; var body = this.body || this.getComponent(cc.RigidBody); if (!body) return; var innerBody = body._getBody(); if (!innerBody) return; var node = body.node; var scale = getWorldScale(node); this._scale = scale; var shapes = 0 === scale.x && 0 === scale.y ? [] : this._createShape(scale); shapes instanceof Array || (shapes = [ shapes ]); var categoryBits = 1 << node.groupIndex; var maskBits = 0; var bits = cc.game.collisionMatrix[node.groupIndex]; for (var i = 0; i < bits.length; i++) { if (!bits[i]) continue; maskBits |= 1 << i; } var filter = { categoryBits: categoryBits, maskBits: maskBits, groupIndex: 0 }; var manager = cc.director.getPhysicsManager(); for (var _i = 0; _i < shapes.length; _i++) { var shape = shapes[_i]; var fixDef = new b2.FixtureDef(); fixDef.density = this.density; fixDef.isSensor = this.sensor; fixDef.friction = this.friction; fixDef.restitution = this.restitution; fixDef.shape = shape; fixDef.filter = filter; var fixture = innerBody.CreateFixture(fixDef); fixture.collider = this; body.enabledContactListener && manager._registerContactFixture(fixture); this._shapes.push(shape); this._fixtures.push(fixture); } this.body = body; this._inited = true; }, __destroy: function() { if (!this._inited) return; var fixtures = this._fixtures; var body = this.body._getBody(); var manager = cc.director.getPhysicsManager(); for (var i = fixtures.length - 1; i >= 0; i--) { var fixture = fixtures[i]; fixture.collider = null; manager._unregisterContactFixture(fixture); body && body.DestroyFixture(fixture); } this.body = null; this._fixtures.length = 0; this._shapes.length = 0; this._inited = false; }, _createShape: function() {}, apply: function() { this._destroy(); this._init(); }, getAABB: function() { var MAX = 1e7; var minX = MAX, minY = MAX; var maxX = -MAX, maxY = -MAX; var fixtures = this._fixtures; for (var i = 0; i < fixtures.length; i++) { var fixture = fixtures[i]; var count = fixture.GetShape().GetChildCount(); for (var j = 0; j < count; j++) { var aabb = fixture.GetAABB(j); aabb.lowerBound.x < minX && (minX = aabb.lowerBound.x); aabb.lowerBound.y < minY && (minY = aabb.lowerBound.y); aabb.upperBound.x > maxX && (maxX = aabb.upperBound.x); aabb.upperBound.y > maxY && (maxY = aabb.upperBound.y); } } minX *= PTM_RATIO; minY *= PTM_RATIO; maxX *= PTM_RATIO; maxY *= PTM_RATIO; var r = this._rect; r.x = minX; r.y = minY; r.width = maxX - minX; r.height = maxY - minY; return r; } }); cc.PhysicsCollider = module.exports = PhysicsCollider; }), { "../CCPhysicsTypes": 135, "../utils": 158 } ], 143: [ (function(require, module, exports) { var PTM_RATIO = require("../CCPhysicsTypes").PTM_RATIO; var PolygonSeparator = require("../CCPolygonSeparator"); var PhysicsPolygonCollider = cc.Class({ name: "cc.PhysicsPolygonCollider", extends: cc.PhysicsCollider, mixins: [ cc.Collider.Polygon ], editor: { menu: false, inspector: false, requireComponent: cc.RigidBody }, _createShape: function(scale) { var shapes = []; var points = this.points; points.length > 0 && points[0].equals(points[points.length - 1]) && (points.length -= 1); var polys = PolygonSeparator.ConvexPartition(points); var offset = this.offset; for (var i = 0; i < polys.length; i++) { var poly = polys[i]; var shape = null, vertices = []; var firstVertice = null; for (var j = 0, l = poly.length; j < l; j++) { shape || (shape = new b2.PolygonShape()); var p = poly[j]; var x = (p.x + offset.x) / PTM_RATIO * scale.x; var y = (p.y + offset.y) / PTM_RATIO * scale.y; var v = new b2.Vec2(x, y); vertices.push(v); firstVertice || (firstVertice = v); if (vertices.length === b2.maxPolygonVertices) { shape.Set(vertices, vertices.length); shapes.push(shape); shape = null; j < l - 1 && (vertices = [ firstVertice, vertices[vertices.length - 1] ]); } } if (shape) { shape.Set(vertices, vertices.length); shapes.push(shape); } } return shapes; } }); cc.PhysicsPolygonCollider = module.exports = PhysicsPolygonCollider; }), { "../CCPhysicsTypes": 135, "../CCPolygonSeparator": 136 } ], 144: [ (function(require, module, exports) { require("./box2d-adapter"); require("./CCPhysicsManager"); require("./CCRigidBody"); require("./CCPhysicsContact"); require("./collider/CCPhysicsCollider"); require("./collider/CCPhysicsChainCollider"); require("./collider/CCPhysicsCircleCollider"); require("./collider/CCPhysicsBoxCollider"); require("./collider/CCPhysicsPolygonCollider"); require("./joint/CCJoint"); require("./joint/CCDistanceJoint"); require("./joint/CCRevoluteJoint"); require("./joint/CCMouseJoint"); require("./joint/CCMotorJoint"); require("./joint/CCPrismaticJoint"); require("./joint/CCWeldJoint"); require("./joint/CCWheelJoint"); require("./joint/CCRopeJoint"); require("./platform/CCPhysicsContactListner"); require("./platform/CCPhysicsAABBQueryCallback"); require("./platform/CCPhysicsRayCastCallback"); }), { "./CCPhysicsContact": 133, "./CCPhysicsManager": 134, "./CCRigidBody": 137, "./box2d-adapter": 138, "./collider/CCPhysicsBoxCollider": 139, "./collider/CCPhysicsChainCollider": 140, "./collider/CCPhysicsCircleCollider": 141, "./collider/CCPhysicsCollider": 142, "./collider/CCPhysicsPolygonCollider": 143, "./joint/CCDistanceJoint": 145, "./joint/CCJoint": 146, "./joint/CCMotorJoint": 147, "./joint/CCMouseJoint": 148, "./joint/CCPrismaticJoint": 149, "./joint/CCRevoluteJoint": 150, "./joint/CCRopeJoint": 151, "./joint/CCWeldJoint": 152, "./joint/CCWheelJoint": 153, "./platform/CCPhysicsAABBQueryCallback": 154, "./platform/CCPhysicsContactListner": 155, "./platform/CCPhysicsRayCastCallback": 157 } ], 145: [ (function(require, module, exports) { var PTM_RATIO = require("../CCPhysicsTypes").PTM_RATIO; var DistanceJoint = cc.Class({ name: "cc.DistanceJoint", extends: cc.Joint, editor: false, properties: { _distance: 1, _frequency: 0, _dampingRatio: 0, distance: { tooltip: false, get: function() { return this._distance; }, set: function(value) { this._distance = value; this._joint && this._joint.SetLength(value); } }, frequency: { tooltip: false, get: function() { return this._frequency; }, set: function(value) { this._frequency = value; this._joint && this._joint.SetFrequency(value); } }, dampingRatio: { tooltip: false, get: function() { return this._dampingRatio; }, set: function(value) { this._dampingRatio = value; this._joint && this._joint.SetDampingRatio(value); } } }, _createJointDef: function() { var def = new b2.DistanceJointDef(); def.localAnchorA = new b2.Vec2(this.anchor.x / PTM_RATIO, this.anchor.y / PTM_RATIO); def.localAnchorB = new b2.Vec2(this.connectedAnchor.x / PTM_RATIO, this.connectedAnchor.y / PTM_RATIO); def.length = this.distance / PTM_RATIO; def.dampingRatio = this.dampingRatio; def.frequencyHz = this.frequency; return def; } }); cc.DistanceJoint = module.exports = DistanceJoint; }), { "../CCPhysicsTypes": 135 } ], 146: [ (function(require, module, exports) { var PTM_RATIO = require("../CCPhysicsTypes").PTM_RATIO; var Joint = cc.Class({ name: "cc.Joint", extends: cc.Component, editor: { requireComponent: cc.RigidBody }, properties: { anchor: { default: cc.v2(0, 0), tooltip: false }, connectedAnchor: { default: cc.v2(0, 0), tooltip: false }, connectedBody: { default: null, type: cc.RigidBody, tooltip: false }, collideConnected: { default: false, tooltip: false } }, onDisable: function() { this._destroy(); }, onEnable: function() { this._init(); }, start: function() { this._init(); }, apply: function() { this._destroy(); this._init(); }, getWorldAnchor: function() { if (this._joint) { var anchor = this._joint.GetAnchorA(); return cc.v2(anchor.x * PTM_RATIO, anchor.y * PTM_RATIO); } return cc.Vec2.ZERO; }, getWorldConnectedAnchor: function() { if (this._joint) { var anchor = this._joint.GetAnchorB(); return cc.v2(anchor.x * PTM_RATIO, anchor.y * PTM_RATIO); } return cc.Vec2.ZERO; }, getReactionForce: function(timeStep) { var out = cc.v2(); if (this._joint) return this._joint.GetReactionForce(timeStep, out); return out; }, getReactionTorque: function(timeStep) { if (this._joint) return this._joint.GetReactionTorque(timeStep); return 0; }, _init: function() { cc.director.getPhysicsManager().pushDelayEvent(this, "__init", []); }, _destroy: function() { cc.director.getPhysicsManager().pushDelayEvent(this, "__destroy", []); }, __init: function() { if (this._inited) return; this.body = this.getComponent(cc.RigidBody); if (this._isValid()) { var def = this._createJointDef(); if (!def) return; def.bodyA = this.body._getBody(); def.bodyB = this.connectedBody._getBody(); def.collideConnected = this.collideConnected; cc.director.getPhysicsManager()._addJoint(this, def); this._inited = true; } }, __destroy: function() { if (!this._inited) return; cc.director.getPhysicsManager()._removeJoint(this); this._joint = null; this._inited = false; }, _createJointDef: function() { return null; }, _isValid: function() { return this.body && this.body._getBody() && this.connectedBody && this.connectedBody._getBody(); } }); cc.Joint = module.exports = Joint; }), { "../CCPhysicsTypes": 135 } ], 147: [ (function(require, module, exports) { var PTM_RATIO = require("../CCPhysicsTypes").PTM_RATIO; var ANGLE_TO_PHYSICS_ANGLE = require("../CCPhysicsTypes").ANGLE_TO_PHYSICS_ANGLE; var MotorJoint = cc.Class({ name: "cc.MotorJoint", extends: cc.Joint, editor: false, properties: { _linearOffset: cc.v2(0, 0), _angularOffset: 0, _maxForce: 1, _maxTorque: 1, _correctionFactor: .3, anchor: { tooltip: false, default: cc.v2(0, 0), override: true, visible: false }, connectedAnchor: { tooltip: false, default: cc.v2(0, 0), override: true, visible: false }, linearOffset: { tooltip: false, get: function() { return this._linearOffset; }, set: function(value) { this._linearOffset = value; this._joint && this._joint.SetLinearOffset(new b2.Vec2(value.x / PTM_RATIO, value.y / PTM_RATIO)); } }, angularOffset: { tooltip: false, get: function() { return this._angularOffset; }, set: function(value) { this._angularOffset = value; this._joint && this._joint.SetAngularOffset(value); } }, maxForce: { tooltip: false, get: function() { return this._maxForce; }, set: function(value) { this._maxForce = value; this._joint && this._joint.SetMaxForce(value); } }, maxTorque: { tooltip: false, get: function() { return this._maxTorque; }, set: function(value) { this._maxTorque = value; this._joint && this._joint.SetMaxTorque(value); } }, correctionFactor: { tooltip: false, get: function() { return this._correctionFactor; }, set: function(value) { this._correctionFactor = value; this._joint && this._joint.SetCorrectionFactor(value); } } }, _createJointDef: function() { var def = new b2.MotorJointDef(); def.linearOffset = new b2.Vec2(this.linearOffset.x / PTM_RATIO, this.linearOffset.y / PTM_RATIO); def.angularOffset = this.angularOffset * ANGLE_TO_PHYSICS_ANGLE; def.maxForce = this.maxForce; def.maxTorque = this.maxTorque; def.correctionFactor = this.correctionFactor; return def; } }); cc.MotorJoint = module.exports = MotorJoint; }), { "../CCPhysicsTypes": 135 } ], 148: [ (function(require, module, exports) { var PTM_RATIO = require("../CCPhysicsTypes").PTM_RATIO; var tempB2Vec2 = new b2.Vec2(); var MouseJoint = cc.Class({ name: "cc.MouseJoint", extends: cc.Joint, editor: false, properties: { _target: 1, _frequency: 5, _dampingRatio: .7, _maxForce: 0, connectedBody: { default: null, type: cc.RigidBody, visible: false, override: true }, collideConnected: { default: true, visible: false, override: true }, anchor: { tooltip: false, default: cc.v2(0, 0), override: true, visible: false }, connectedAnchor: { tooltip: false, default: cc.v2(0, 0), override: true, visible: false }, mouseRegion: { tooltip: false, default: null, type: cc.Node }, target: { tooltip: false, visible: false, get: function() { return this._target; }, set: function(value) { this._target = value; if (this._joint) { tempB2Vec2.x = value.x / PTM_RATIO; tempB2Vec2.y = value.y / PTM_RATIO; this._joint.SetTarget(tempB2Vec2); } } }, frequency: { tooltip: false, get: function() { return this._frequency; }, set: function(value) { this._frequency = value; this._joint && this._joint.SetFrequency(value); } }, dampingRatio: { tooltip: false, get: function() { return this._dampingRatio; }, set: function(value) { this._dampingRatio = value; this._joint && this._joint.SetDampingRatio(value); } }, maxForce: { tooltip: false, visible: false, get: function() { return this._maxForce; }, set: function(value) { this._maxForce = value; this._joint && this._joint.SetMaxForce(value); } } }, onLoad: function() { var mouseRegion = this.mouseRegion || this.node; mouseRegion.on(cc.Node.EventType.TOUCH_START, this.onTouchBegan, this); mouseRegion.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this); mouseRegion.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this); mouseRegion.on(cc.Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this); }, onEnable: function() {}, start: function() {}, onTouchBegan: function(event) { var manager = cc.director.getPhysicsManager(); var target = this._pressPoint = event.touch.getLocation(); cc.Camera && cc.Camera.main && (target = cc.Camera.main.getCameraToWorldPoint(target)); var collider = manager.testPoint(target); if (!collider) return; var body = this.connectedBody = collider.body; body.awake = true; this.maxForce = 1e3 * this.connectedBody.getMass(); this.target = target; this._init(); }, onTouchMove: function(event) { this._pressPoint = event.touch.getLocation(); }, onTouchEnd: function(event) { this._destroy(); this._pressPoint = null; }, _createJointDef: function() { var def = new b2.MouseJointDef(); tempB2Vec2.x = this.target.x / PTM_RATIO; tempB2Vec2.y = this.target.y / PTM_RATIO; def.target = tempB2Vec2; def.maxForce = this.maxForce; def.dampingRatio = this.dampingRatio; def.frequencyHz = this.frequency; return def; }, update: function() { if (!this._pressPoint || !this._isValid()) return; var camera = cc.Camera.findCamera(this.node); this.target = camera ? camera.getCameraToWorldPoint(this._pressPoint) : this._pressPoint; } }); cc.MouseJoint = module.exports = MouseJoint; }), { "../CCPhysicsTypes": 135 } ], 149: [ (function(require, module, exports) { var PTM_RATIO = require("../CCPhysicsTypes").PTM_RATIO; var ANGLE_TO_PHYSICS_ANGLE = require("../CCPhysicsTypes").ANGLE_TO_PHYSICS_ANGLE; var PrismaticJoint = cc.Class({ name: "cc.PrismaticJoint", extends: cc.Joint, editor: false, properties: { localAxisA: { default: cc.v2(1, 0), tooltip: false }, referenceAngle: { default: 0, tooltip: false }, enableLimit: { default: false, tooltip: false }, enableMotor: { default: false, tooltip: false }, lowerLimit: { default: 0, tooltip: false }, upperLimit: { default: 0, tooltip: false }, _maxMotorForce: 0, _motorSpeed: 0, maxMotorForce: { tooltip: false, get: function() { return this._maxMotorForce; }, set: function(value) { this._maxMotorForce = value; this._joint && this._joint.SetMaxMotorForce(value); } }, motorSpeed: { tooltip: false, get: function() { return this._motorSpeed; }, set: function(value) { this._motorSpeed = value; this._joint && this._joint.SetMotorSpeed(value); } } }, _createJointDef: function() { var def = new b2.PrismaticJointDef(); def.localAnchorA = new b2.Vec2(this.anchor.x / PTM_RATIO, this.anchor.y / PTM_RATIO); def.localAnchorB = new b2.Vec2(this.connectedAnchor.x / PTM_RATIO, this.connectedAnchor.y / PTM_RATIO); def.localAxisA = new b2.Vec2(this.localAxisA.x, this.localAxisA.y); def.referenceAngle = this.referenceAngle * ANGLE_TO_PHYSICS_ANGLE; def.enableLimit = this.enableLimit; def.lowerTranslation = this.lowerLimit / PTM_RATIO; def.upperTranslation = this.upperLimit / PTM_RATIO; def.enableMotor = this.enableMotor; def.maxMotorForce = this.maxMotorForce; def.motorSpeed = this.motorSpeed; return def; } }); cc.PrismaticJoint = module.exports = PrismaticJoint; }), { "../CCPhysicsTypes": 135 } ], 150: [ (function(require, module, exports) { var PTM_RATIO = require("../CCPhysicsTypes").PTM_RATIO; var ANGLE_TO_PHYSICS_ANGLE = require("../CCPhysicsTypes").ANGLE_TO_PHYSICS_ANGLE; var PHYSICS_ANGLE_TO_ANGLE = require("../CCPhysicsTypes").PHYSICS_ANGLE_TO_ANGLE; var RevoluteJoint = cc.Class({ name: "cc.RevoluteJoint", extends: cc.Joint, editor: false, properties: { _maxMotorTorque: 0, _motorSpeed: 0, _enableLimit: false, _enableMotor: false, referenceAngle: { default: 0, tooltip: false }, lowerAngle: { default: 0, tooltip: false }, upperAngle: { default: 0, tooltip: false }, maxMotorTorque: { tooltip: false, get: function() { return this._maxMotorTorque; }, set: function(value) { this._maxMotorTorque = value; this._joint && this._joint.SetMaxMotorTorque(value); } }, motorSpeed: { tooltip: false, get: function() { return this._motorSpeed; }, set: function(value) { this._motorSpeed = value; this._joint && this._joint.SetMotorSpeed(value * ANGLE_TO_PHYSICS_ANGLE); } }, enableLimit: { tooltip: false, get: function() { return this._enableLimit; }, set: function(value) { this._enableLimit = value; this._joint && this._joint.EnableLimit(value); } }, enableMotor: { tooltip: false, get: function() { return this._enableMotor; }, set: function(value) { this._enableMotor = value; this._joint && this._joint.EnableMotor(value); } } }, getJointAngle: function() { if (this._joint) return this._joint.GetJointAngle() * PHYSICS_ANGLE_TO_ANGLE; return 0; }, setLimits: function(lower, upper) { if (this._joint) return this._joint.SetLimits(lower * ANGLE_TO_PHYSICS_ANGLE, upper * ANGLE_TO_PHYSICS_ANGLE); }, _createJointDef: function() { var def = new b2.RevoluteJointDef(); def.localAnchorA = new b2.Vec2(this.anchor.x / PTM_RATIO, this.anchor.y / PTM_RATIO); def.localAnchorB = new b2.Vec2(this.connectedAnchor.x / PTM_RATIO, this.connectedAnchor.y / PTM_RATIO); def.lowerAngle = this.upperAngle * ANGLE_TO_PHYSICS_ANGLE; def.upperAngle = this.lowerAngle * ANGLE_TO_PHYSICS_ANGLE; def.maxMotorTorque = this.maxMotorTorque; def.motorSpeed = this.motorSpeed * ANGLE_TO_PHYSICS_ANGLE; def.enableLimit = this.enableLimit; def.enableMotor = this.enableMotor; def.referenceAngle = this.referenceAngle * ANGLE_TO_PHYSICS_ANGLE; return def; } }); cc.RevoluteJoint = module.exports = RevoluteJoint; }), { "../CCPhysicsTypes": 135 } ], 151: [ (function(require, module, exports) { var PTM_RATIO = require("../CCPhysicsTypes").PTM_RATIO; var RopeJoint = cc.Class({ name: "cc.RopeJoint", extends: cc.Joint, editor: false, properties: { _maxLength: 1, maxLength: { tooltip: false, get: function() { return this._maxLength; }, set: function(value) { this._maxLength = value; this._joint && this._joint.SetMaxLength(value); } } }, _createJointDef: function() { var def = new b2.RopeJointDef(); def.localAnchorA = new b2.Vec2(this.anchor.x / PTM_RATIO, this.anchor.y / PTM_RATIO); def.localAnchorB = new b2.Vec2(this.connectedAnchor.x / PTM_RATIO, this.connectedAnchor.y / PTM_RATIO); def.maxLength = this.maxLength / PTM_RATIO; return def; } }); cc.RopeJoint = module.exports = RopeJoint; }), { "../CCPhysicsTypes": 135 } ], 152: [ (function(require, module, exports) { var PTM_RATIO = require("../CCPhysicsTypes").PTM_RATIO; var ANGLE_TO_PHYSICS_ANGLE = require("../CCPhysicsTypes").ANGLE_TO_PHYSICS_ANGLE; var WeldJoint = cc.Class({ name: "cc.WeldJoint", extends: cc.Joint, editor: false, properties: { referenceAngle: { default: 0, tooltip: false }, _frequency: 0, _dampingRatio: 0, frequency: { tooltip: false, get: function() { return this._frequency; }, set: function(value) { this._frequency = value; this._joint && this._joint.SetFrequency(value); } }, dampingRatio: { tooltip: false, get: function() { return this._dampingRatio; }, set: function(value) { this._dampingRatio = value; this._joint && this._joint.SetDampingRatio(value); } } }, _createJointDef: function() { var def = new b2.WeldJointDef(); def.localAnchorA = new b2.Vec2(this.anchor.x / PTM_RATIO, this.anchor.y / PTM_RATIO); def.localAnchorB = new b2.Vec2(this.connectedAnchor.x / PTM_RATIO, this.connectedAnchor.y / PTM_RATIO); def.referenceAngle = this.referenceAngle * ANGLE_TO_PHYSICS_ANGLE; def.frequencyHz = this.frequency; def.dampingRatio = this.dampingRatio; return def; } }); cc.WeldJoint = module.exports = WeldJoint; }), { "../CCPhysicsTypes": 135 } ], 153: [ (function(require, module, exports) { var PTM_RATIO = require("../CCPhysicsTypes").PTM_RATIO; var ANGLE_TO_PHYSICS_ANGLE = require("../CCPhysicsTypes").ANGLE_TO_PHYSICS_ANGLE; var WheelJoint = cc.Class({ name: "cc.WheelJoint", extends: cc.Joint, editor: false, properties: { _maxMotorTorque: 0, _motorSpeed: 0, _enableMotor: false, _frequency: 2, _dampingRatio: .7, localAxisA: { default: cc.v2(1, 0), tooltip: false }, maxMotorTorque: { tooltip: false, get: function() { return this._maxMotorTorque; }, set: function(value) { this._maxMotorTorque = value; this._joint && this._joint.SetMaxMotorTorque(value); } }, motorSpeed: { tooltip: false, get: function() { return this._motorSpeed; }, set: function(value) { this._motorSpeed = value; this._joint && this._joint.SetMotorSpeed(value * ANGLE_TO_PHYSICS_ANGLE); } }, enableMotor: { tooltip: false, get: function() { return this._enableMotor; }, set: function(value) { this._enableMotor = value; this._joint && this._joint.EnableMotor(value); } }, frequency: { tooltip: false, get: function() { return this._frequency; }, set: function(value) { this._frequency = value; this._joint && this._joint.SetFrequency(value); } }, dampingRatio: { tooltip: false, get: function() { return this._dampingRatio; }, set: function(value) { this._dampingRatio = value; this._joint && this._joint.SetDampingRatio(value); } } }, _createJointDef: function() { var def = new b2.WheelJointDef(); def.localAnchorA = new b2.Vec2(this.anchor.x / PTM_RATIO, this.anchor.y / PTM_RATIO); def.localAnchorB = new b2.Vec2(this.connectedAnchor.x / PTM_RATIO, this.connectedAnchor.y / PTM_RATIO); def.localAxisA = new b2.Vec2(this.localAxisA.x, this.localAxisA.y); def.maxMotorTorque = this.maxMotorTorque; def.motorSpeed = this.motorSpeed * ANGLE_TO_PHYSICS_ANGLE; def.enableMotor = this.enableMotor; def.dampingRatio = this.dampingRatio; def.frequencyHz = this.frequency; return def; } }); cc.WheelJoint = module.exports = WheelJoint; }), { "../CCPhysicsTypes": 135 } ], 154: [ (function(require, module, exports) { var BodyType = require("../CCPhysicsTypes").BodyType; function PhysicsAABBQueryCallback() { this._point = new b2.Vec2(); this._isPoint = false; this._fixtures = []; } PhysicsAABBQueryCallback.prototype.init = function(point) { if (point) { this._isPoint = true; this._point.x = point.x; this._point.y = point.y; } else this._isPoint = false; this._fixtures.length = 0; }; PhysicsAABBQueryCallback.prototype.ReportFixture = function(fixture) { var body = fixture.GetBody(); if (body.GetType() === BodyType.Dynamic) if (this._isPoint) { if (fixture.TestPoint(this._point)) { this._fixtures.push(fixture); return false; } } else this._fixtures.push(fixture); return true; }; PhysicsAABBQueryCallback.prototype.getFixture = function() { return this._fixtures[0]; }; PhysicsAABBQueryCallback.prototype.getFixtures = function() { return this._fixtures; }; cc.PhysicsAABBQueryCallback = module.exports = PhysicsAABBQueryCallback; }), { "../CCPhysicsTypes": 135 } ], 155: [ (function(require, module, exports) { function PhysicsContactListener() { this._contactFixtures = []; } PhysicsContactListener.prototype.setBeginContact = function(cb) { this._BeginContact = cb; }; PhysicsContactListener.prototype.setEndContact = function(cb) { this._EndContact = cb; }; PhysicsContactListener.prototype.setPreSolve = function(cb) { this._PreSolve = cb; }; PhysicsContactListener.prototype.setPostSolve = function(cb) { this._PostSolve = cb; }; PhysicsContactListener.prototype.BeginContact = function(contact) { if (!this._BeginContact) return; var fixtureA = contact.GetFixtureA(); var fixtureB = contact.GetFixtureB(); var fixtures = this._contactFixtures; contact._shouldReport = false; if (-1 !== fixtures.indexOf(fixtureA) || -1 !== fixtures.indexOf(fixtureB)) { contact._shouldReport = true; this._BeginContact(contact); } }; PhysicsContactListener.prototype.EndContact = function(contact) { if (this._EndContact && contact._shouldReport) { contact._shouldReport = false; this._EndContact(contact); } }; PhysicsContactListener.prototype.PreSolve = function(contact, oldManifold) { this._PreSolve && contact._shouldReport && this._PreSolve(contact, oldManifold); }; PhysicsContactListener.prototype.PostSolve = function(contact, impulse) { this._PostSolve && contact._shouldReport && this._PostSolve(contact, impulse); }; PhysicsContactListener.prototype.registerContactFixture = function(fixture) { this._contactFixtures.push(fixture); }; PhysicsContactListener.prototype.unregisterContactFixture = function(fixture) { cc.js.array.remove(this._contactFixtures, fixture); }; cc.PhysicsContactListener = module.exports = PhysicsContactListener; }), {} ], 156: [ (function(require, module, exports) { var PTM_RATIO = require("../CCPhysicsTypes").PTM_RATIO; var _tmp_vec2 = cc.v2(); var GREEN_COLOR = cc.Color.GREEN; var RED_COLOR = cc.Color.RED; function PhysicsDebugDraw(drawer) { b2.Draw.call(this); this._drawer = drawer; this._xf = this._dxf = new b2.Transform(); } cc.js.extend(PhysicsDebugDraw, b2.Draw); cc.js.mixin(PhysicsDebugDraw.prototype, { _DrawPolygon: function(vertices, vertexCount) { var drawer = this._drawer; for (var i = 0; i < vertexCount; i++) { b2.Transform.MulXV(this._xf, vertices[i], _tmp_vec2); var x = _tmp_vec2.x * PTM_RATIO, y = _tmp_vec2.y * PTM_RATIO; 0 === i ? drawer.moveTo(x, y) : drawer.lineTo(x, y); } drawer.close(); }, DrawPolygon: function(vertices, vertexCount, color) { this._applyStrokeColor(color); this._DrawPolygon(vertices, vertexCount); this._drawer.stroke(); }, DrawSolidPolygon: function(vertices, vertexCount, color) { this._applyFillColor(color); this._DrawPolygon(vertices, vertexCount); this._drawer.fill(); this._drawer.stroke(); }, _DrawCircle: function(center, radius) { var p = this._xf.p; this._drawer.circle((center.x + p.x) * PTM_RATIO, (center.y + p.y) * PTM_RATIO, radius * PTM_RATIO); }, DrawCircle: function(center, radius, color) { this._applyStrokeColor(color); this._DrawCircle(center, radius); this._drawer.stroke(); }, DrawSolidCircle: function(center, radius, axis, color) { this._applyFillColor(color); this._DrawCircle(center, radius); this._drawer.fill(); }, DrawSegment: function(p1, p2, color) { var drawer = this._drawer; if (p1.x === p2.x && p1.y === p2.y) { this._applyFillColor(color); this._DrawCircle(p1, 2 / PTM_RATIO); drawer.fill(); return; } this._applyStrokeColor(color); b2.Transform.MulXV(this._xf, p1, _tmp_vec2); drawer.moveTo(_tmp_vec2.x * PTM_RATIO, _tmp_vec2.y * PTM_RATIO); b2.Transform.MulXV(this._xf, p2, _tmp_vec2); drawer.lineTo(_tmp_vec2.x * PTM_RATIO, _tmp_vec2.y * PTM_RATIO); drawer.stroke(); }, DrawTransform: function(xf) { var drawer = this._drawer; drawer.strokeColor = RED_COLOR; _tmp_vec2.x = _tmp_vec2.y = 0; b2.Transform.MulXV(xf, _tmp_vec2, _tmp_vec2); drawer.moveTo(_tmp_vec2.x * PTM_RATIO, _tmp_vec2.y * PTM_RATIO); _tmp_vec2.x = 1; _tmp_vec2.y = 0; b2.Transform.MulXV(xf, _tmp_vec2, _tmp_vec2); drawer.lineTo(_tmp_vec2.x * PTM_RATIO, _tmp_vec2.y * PTM_RATIO); drawer.stroke(); drawer.strokeColor = GREEN_COLOR; _tmp_vec2.x = _tmp_vec2.y = 0; b2.Transform.MulXV(xf, _tmp_vec2, _tmp_vec2); drawer.moveTo(_tmp_vec2.x * PTM_RATIO, _tmp_vec2.y * PTM_RATIO); _tmp_vec2.x = 0; _tmp_vec2.y = 1; b2.Transform.MulXV(xf, _tmp_vec2, _tmp_vec2); drawer.lineTo(_tmp_vec2.x * PTM_RATIO, _tmp_vec2.y * PTM_RATIO); drawer.stroke(); }, DrawPoint: function(center, radius, color) {}, _applyStrokeColor: function(color) { var strokeColor = this._drawer.strokeColor; strokeColor.r = 255 * color.r; strokeColor.g = 255 * color.g; strokeColor.b = 255 * color.b; strokeColor.a = 150; this._drawer.strokeColor = strokeColor; }, _applyFillColor: function(color) { var fillColor = this._drawer.fillColor; fillColor.r = 255 * color.r; fillColor.g = 255 * color.g; fillColor.b = 255 * color.b; fillColor.a = 150; this._drawer.fillColor = fillColor; }, PushTransform: function(xf) { this._xf = xf; }, PopTransform: function() { this._xf = this._dxf; } }); module.exports = PhysicsDebugDraw; }), { "../CCPhysicsTypes": 135 } ], 157: [ (function(require, module, exports) { function PhysicsRayCastCallback() { this._type = 0; this._fixtures = []; this._points = []; this._normals = []; this._fractions = []; } PhysicsRayCastCallback.prototype.init = function(type) { this._type = type; this._fixtures.length = 0; this._points.length = 0; this._normals.length = 0; this._fractions.length = 0; }; PhysicsRayCastCallback.prototype.ReportFixture = function(fixture, point, normal, fraction) { if (0 === this._type) { this._fixtures[0] = fixture; this._points[0] = point; this._normals[0] = normal; this._fractions[0] = fraction; return fraction; } this._fixtures.push(fixture); this._points.push(cc.v2(point)); this._normals.push(cc.v2(normal)); this._fractions.push(fraction); if (1 === this._type) return 0; if (this._type >= 2) return 1; return fraction; }; PhysicsRayCastCallback.prototype.getFixtures = function() { return this._fixtures; }; PhysicsRayCastCallback.prototype.getPoints = function() { return this._points; }; PhysicsRayCastCallback.prototype.getNormals = function() { return this._normals; }; PhysicsRayCastCallback.prototype.getFractions = function() { return this._fractions; }; cc.PhysicsRayCastCallback = module.exports = PhysicsRayCastCallback; }), {} ], 158: [ (function(require, module, exports) { function getWorldRotation(node) { var rot = node.rotationX; var parent = node.parent; while (parent.parent) { rot += parent.rotationX; parent = parent.parent; } return rot; } function getWorldScale(node) { var scaleX = node.scaleX; var scaleY = node.scaleY; var parent = node.parent; while (parent.parent) { scaleX *= parent.scaleX; scaleY *= parent.scaleY; parent = parent.parent; } return cc.v2(scaleX, scaleY); } function convertToNodeRotation(node, rotation) { rotation -= node.rotationX; var parent = node.parent; while (parent.parent) { rotation -= parent.rotationX; parent = parent.parent; } return rotation; } module.exports = { getWorldRotation: getWorldRotation, getWorldScale: getWorldScale, convertToNodeRotation: convertToNodeRotation }; }), {} ], 159: [ (function(require, module, exports) { var js; var macro; var sys; var eventManager; var TOUCH_TIMEOUT; var bkInputManager; false; }), { "../event-manager": 101, "../platform/js": 181, "./CCMacro": 166, "./CCSys": 170 } ], 160: [ (function(require, module, exports) { var Asset = require("../assets/CCAsset"); var callInNextTick = require("./utils").callInNextTick; var Loader = require("../load-pipeline/CCLoader"); var PackDownloader = require("../load-pipeline/pack-downloader"); var AutoReleaseUtils = require("../load-pipeline/auto-release-utils"); var decodeUuid = require("../utils/decode-uuid"); var MD5Pipe = require("../load-pipeline/md5-pipe"); var SubPackPipe = require("../load-pipeline/subpackage-pipe"); var js = require("./js"); var _libraryBase = ""; var _rawAssetsBase = ""; var _uuidToRawAsset = js.createMap(true); function isScene(asset) { return asset && (asset.constructor === cc.SceneAsset || asset instanceof cc.Scene); } function RawAssetEntry(url, type) { this.url = url; this.type = type; } var AssetLibrary = { loadAsset: function(uuid, callback, options) { if ("string" !== (__typeofVal = typeof uuid, "object" === __typeofVal ? __realTypeOfObj(uuid) : __typeofVal)) return callInNextTick(callback, new Error("[AssetLibrary] uuid must be string"), null); var item = { uuid: uuid, type: "uuid" }; options && options.existingAsset && (item.existingAsset = options.existingAsset); Loader.load(item, (function(error, asset) { if (error || !asset) error = new Error("[AssetLibrary] loading JSON or dependencies failed: " + (error ? error.message : "Unknown error")); else { if (asset.constructor === cc.SceneAsset) { false; var key = cc.loader._getReferenceKey(uuid); asset.scene.dependAssets = AutoReleaseUtils.getDependsRecursively(key); } if (false, isScene(asset)) { var id = cc.loader._getReferenceKey(uuid); Loader.removeItem(id); } } callback && callback(error, asset); })); }, getLibUrlNoExt: function(uuid, inRawAssetsDir) { true; uuid = decodeUuid(uuid); var base = (true, inRawAssetsDir ? _rawAssetsBase + "assets/" : _libraryBase); return base + uuid.slice(0, 2) + "/" + uuid; }, _queryAssetInfoInEditor: function(uuid, callback) { false; }, _getAssetInfoInRuntime: function(uuid, result) { result = result || { url: null, raw: false }; var info = _uuidToRawAsset[uuid]; if (info && !js.isChildClassOf(info.type, cc.Asset)) { result.url = _rawAssetsBase + info.url; result.raw = true; } else { result.url = this.getLibUrlNoExt(uuid) + ".json"; result.raw = false; } return result; }, _uuidInSettings: function(uuid) { return uuid in _uuidToRawAsset; }, queryAssetInfo: function(uuid, callback) { false; var info = this._getAssetInfoInRuntime(uuid); callback(null, info.url, info.raw); }, parseUuidInEditor: function(url) { var uuid; var isImported; var dir; var dirBasename; var isAssetUrl; var index; false; }, loadJson: function(json, callback) { var randomUuid = "" + (new Date().getTime() + Math.random()); var item = { uuid: randomUuid, type: "uuid", content: json, skips: [ Loader.assetLoader.id, Loader.downloader.id ] }; Loader.load(item, (function(error, asset) { if (error) error = new Error("[AssetLibrary] loading JSON or dependencies failed: " + error.message); else { if (asset.constructor === cc.SceneAsset) { var key = cc.loader._getReferenceKey(randomUuid); asset.scene.dependAssets = AutoReleaseUtils.getDependsRecursively(key); } if (false, isScene(asset)) { var id = cc.loader._getReferenceKey(randomUuid); Loader.removeItem(id); } } asset._uuid = ""; callback && callback(error, asset); })); }, getAssetByUuid: function(uuid) { return AssetLibrary._uuidToAsset[uuid] || null; }, init: function(options) { false; var libraryPath = options.libraryPath; libraryPath = libraryPath.replace(/\\/g, "/"); _libraryBase = cc.path.stripSep(libraryPath) + "/"; _rawAssetsBase = options.rawAssetsBase; if (options.subpackages) { var subPackPipe = new SubPackPipe(options.subpackages); cc.loader.insertPipeAfter(cc.loader.assetLoader, subPackPipe); cc.loader.subPackPipe = subPackPipe; } var md5AssetsMap = options.md5AssetsMap; if (md5AssetsMap && md5AssetsMap.import) { var i = 0, uuid = 0; var md5ImportMap = js.createMap(true); var md5Entries = md5AssetsMap.import; for (i = 0; i < md5Entries.length; i += 2) { uuid = decodeUuid(md5Entries[i]); md5ImportMap[uuid] = md5Entries[i + 1]; } var md5RawAssetsMap = js.createMap(true); md5Entries = md5AssetsMap["raw-assets"]; for (i = 0; i < md5Entries.length; i += 2) { uuid = decodeUuid(md5Entries[i]); md5RawAssetsMap[uuid] = md5Entries[i + 1]; } var md5Pipe = new MD5Pipe(md5ImportMap, md5RawAssetsMap, _libraryBase); cc.loader.insertPipeAfter(cc.loader.assetLoader, md5Pipe); cc.loader.md5Pipe = md5Pipe; } var resources = Loader._resources; resources.reset(); var rawAssets = options.rawAssets; if (rawAssets) for (var mountPoint in rawAssets) { var assets = rawAssets[mountPoint]; for (var uuid in assets) { var info = assets[uuid]; var url = info[0]; var typeId = info[1]; var type = cc.js._getClassById(typeId); if (!type) { cc.error("Cannot get", typeId); continue; } _uuidToRawAsset[uuid] = new RawAssetEntry(mountPoint + "/" + url, type); if ("assets" === mountPoint) { var ext = cc.path.extname(url); ext && (url = url.slice(0, -ext.length)); var isSubAsset = 1 === info[2]; resources.add(url, uuid, type, !isSubAsset); } } } options.packedAssets && PackDownloader.initPacks(options.packedAssets); cc.url._init(options.mountPaths && options.mountPaths.assets || _rawAssetsBase + "assets"); } }; AssetLibrary._uuidToAsset = {}; module.exports = cc.AssetLibrary = AssetLibrary; }), { "../assets/CCAsset": 34, "../load-pipeline/CCLoader": 112, "../load-pipeline/auto-release-utils": 116, "../load-pipeline/md5-pipe": 123, "../load-pipeline/pack-downloader": 124, "../load-pipeline/subpackage-pipe": 127, "../utils/decode-uuid": 238, "./js": 181, "./utils": 185 } ], 161: [ (function(require, module, exports) { 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 getTypeChecker = Attr.getTypeChecker; 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(data) { if (this.datas) this.datas.push(data); else { this.datas = [ data ]; var self = this; setTimeout((function() { self.init(); }), 0); } }, init: function() { 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" === (__typeofVal = typeof properties, "object" === __typeofVal ? __realTypeOfObj(properties) : __typeofVal) && (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); } var tmpArray = []; function defineProp(cls, className, propName, val, es6) { var defaultValue = val.default; false; Attr.setClassAttr(cls, propName, "default", defaultValue); appendProp(cls, propName); var attrs = parseAttributes(cls, val, className, propName, false); if (attrs) { var onAfterProp = tmpArray; for (var i = 0; i < attrs.length; i++) { var attr = attrs[i]; Attr.attr(cls, propName, attr); attr._onAfterProp && onAfterProp.push(attr._onAfterProp); } for (var c = 0; c < onAfterProp.length; c++) onAfterProp[c](cls, propName); tmpArray.length = 0; attrs.length = 0; } } 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; var attrs = parseAttributes(cls, val, name, propName, true); for (var i = 0; i < attrs.length; i++) Attr.attr(cls, propName, attrs[i]); attrs.length = 0; 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" === (__typeofVal = typeof defaultVal, "object" === __typeofVal ? __realTypeOfObj(defaultVal) : __typeofVal)) { 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).constructor.prototype, Attr.getClassAttrs(mixin).constructor.prototype); } 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" === (__typeofVal = typeof def, "object" === __typeofVal ? __realTypeOfObj(def) : __typeofVal) && def) expression = def instanceof cc.ValueType ? getNewValueTypeCodeJit(def) : Array.isArray(def) ? "[]" : "{}"; else if ("function" === (__typeofVal = typeof def, "object" === __typeofVal ? __realTypeOfObj(def) : __typeofVal)) { var index = F.length; F.push(def); expression = "F[" + index + "]()"; false; } else expression = "string" === (__typeofVal = typeof def, "object" === __typeofVal ? __realTypeOfObj(def) : __typeofVal) ? 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 advancedProps = []; var advancedValues = []; var simpleProps = []; var simpleValues = []; 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" === (__typeofVal = typeof def, "object" === __typeofVal ? __realTypeOfObj(def) : __typeofVal) && def || "function" === (__typeofVal = typeof def, "object" === __typeofVal ? __realTypeOfObj(def) : __typeofVal)) { advancedProps.push(prop); advancedValues.push(def); } else { simpleProps.push(prop); simpleValues.push(def); } } } return function() { for (var _i = 0; _i < simpleProps.length; ++_i) this[simpleProps[_i]] = simpleValues[_i]; for (var _i2 = 0; _i2 < advancedProps.length; _i2++) { var _prop = advancedProps[_i2]; var expression; var def = advancedValues[_i2]; if ("object" === (__typeofVal = typeof def, "object" === __typeofVal ? __realTypeOfObj(def) : __typeofVal)) expression = def instanceof cc.ValueType ? def.clone() : Array.isArray(def) ? [] : {}; else { false; expression = def(); } this[_prop] = expression; } }; } 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" !== (__typeofVal = typeof func, "object" === __typeofVal ? __realTypeOfObj(func) : __typeofVal)) continue; var pd = js.getPropertyDescriptor(baseClass.prototype, funcName); if (pd) { var superFunc = pd.value; if ("function" === (__typeofVal = typeof superFunc, "object" === __typeofVal ? __realTypeOfObj(superFunc) : __typeofVal)) { 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" === (__typeofVal = typeof properties, "object" === __typeofVal ? __realTypeOfObj(properties) : __typeofVal) || 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 && !!js.isChildClassOf(base, cc.Component) && 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 attrProtos = Attr.getClassAttrsProto(constructor); for (var i = 0; i < props.length; i++) { var key = props[i]; attrProtos[key + DELIMETER + "visible"] = false; attrProtos[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 tmpAttrs = []; function parseAttributes(cls, attrs, className, propName, usedInGetter) { var ERR_Type = ""; var attrsProto = null; var attrsProtoKey = ""; function getAttrsProto() { attrsProtoKey = propName + DELIMETER; return attrsProto = Attr.getClassAttrsProto(cls); } tmpAttrs.length = 0; var result = tmpAttrs; var type = attrs.type; if (type) { var primitiveType = PrimitiveTypes[type]; if (primitiveType) result.push({ type: type, _onAfterProp: getTypeChecker(primitiveType, "cc." + type) }); else if ("Object" === type) false; else if (type === Attr.ScriptUuid) { var attr = Attr.ObjectType(cc.ScriptAsset); attr.type = "Script"; result.push(attr); } else "object" === (__typeofVal = typeof type, "object" === __typeofVal ? __realTypeOfObj(type) : __typeofVal) ? !!Enum.isEnum(type) && result.push({ type: "Enum", enumList: Enum.getList(type) }) : "function" === (__typeofVal = typeof type, "object" === __typeofVal ? __realTypeOfObj(type) : __typeofVal) && (attrs.url ? result.push({ type: "Object", ctor: type, _onAfterProp: getTypeChecker("String", "cc.String") }) : result.push(attrs._short ? { type: "Object", ctor: type } : Attr.ObjectType(type))); } function parseSimpleAttr(attrName, expectType) { if (attrName in attrs) { var val = attrs[attrName]; (__typeofVal = typeof val, "object" === __typeofVal ? __realTypeOfObj(val) : __typeofVal) === expectType && ((attrsProto || getAttrsProto())[attrsProtoKey + attrName] = val); } } if (attrs.editorOnly) { false; (attrsProto || getAttrsProto())[attrsProtoKey + "editorOnly"] = true; } false; attrs.url && ((attrsProto || getAttrsProto())[attrsProtoKey + "saveUrlAsAsset"] = true); if (false === attrs.serializable) { false; (attrsProto || getAttrsProto())[attrsProtoKey + "serializable"] = false; } parseSimpleAttr("formerlySerializedAs", "string"); false; var visible; var startsWithUS; false; var range = attrs.range; if (range) if (Array.isArray(range)) if (range.length >= 2) { (attrsProto || getAttrsProto())[attrsProtoKey + "min"] = range[0]; attrsProto[attrsProtoKey + "max"] = range[1]; range.length > 2 && (attrsProto[attrsProtoKey + "step"] = range[2]); } else false; else false; parseSimpleAttr("min", "number"); parseSimpleAttr("max", "number"); parseSimpleAttr("step", "number"); return result; } cc.Class = CCClass; module.exports = { isArray: function(defaultVal) { defaultVal = getDefault(defaultVal); return Array.isArray(defaultVal); }, fastDefine: CCClass._fastDefine, getNewValueTypeCode: (true, getNewValueTypeCodeJit), IDENTIFIER_RE: IDENTIFIER_RE, escapeForJS: escapeForJS, getDefault: getDefault }; false; }), { "./CCEnum": 163, "./attribute": 173, "./js": 181, "./preprocess-class": 182, "./requiring-frame": 183, "./utils": 185 } ], 162: [ (function(require, module, exports) { 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" === (__typeofVal = typeof target, "object" === __typeofVal ? __realTypeOfObj(target) : __typeofVal)) 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" !== (__typeofVal = typeof value, "object" === __typeofVal ? __realTypeOfObj(value) : __typeofVal) || 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; if (options) { fullOptions = Preprocess.getFullFormOfProperty(options); fullOptions = fullOptions || options; } var existsProperty = properties[propName]; var prop = js.mixin(existsProperty || {}, fullOptions || {}); var isGetset = desc && (desc.get || desc.set); 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; 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" === (__typeofVal = typeof propName, "object" === __typeofVal ? __realTypeOfObj(propName) : __typeofVal)) { 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"); 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": 161, "./js": 181, "./preprocess-class": 182, "./utils": 185 } ], 163: [ (function(require, module, exports) { 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" === (__typeofVal = typeof val, "object" === __typeofVal ? __realTypeOfObj(val) : __typeofVal)) lastIndex = val; else if ("string" === (__typeofVal = typeof val, "object" === __typeofVal ? __realTypeOfObj(val) : __typeofVal) && 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": 181 } ], 164: [ (function(require, module, exports) { 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 = void 0; 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); } true; jsb.device.setMotionEnabled(isEnable); }; inputManager.setAccelerometerInterval = function(interval) { if (this._accelInterval !== interval) { this._accelInterval = interval; true; jsb.device.setMotionInterval(interval); } }; 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 = void 0, y = void 0, z = void 0; 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": 101, "./CCInputManager": 165 } ], 165: [ (function(require, module, exports) { var macro = require("./CCMacro"); var sys = require("./CCSys"); var eventManager = require("../event-manager"); var TOUCH_TIMEOUT = macro.TOUCH_TIMEOUT; var _vec2 = cc.v2(); var inputManager = { _mousePressed: false, _isRegisterEvent: false, _preTouchPoint: cc.v2(0, 0), _prevMousePoint: cc.v2(0, 0), _preTouchPool: [], _preTouchPoolPointer: 0, _touches: [], _touchesIntegerDict: {}, _indexBitsUsed: 0, _maxTouches: 8, _accelEnabled: false, _accelInterval: .2, _accelMinus: 1, _accelCurTime: 0, _acceleration: null, _accelDeviceEvent: null, _getUnUsedIndex: function() { var temp = this._indexBitsUsed; var now = cc.sys.now(); for (var i = 0; i < this._maxTouches; i++) { if (!(1 & temp)) { this._indexBitsUsed |= 1 << i; return i; } var touch = this._touches[i]; if (now - touch._lastModified > TOUCH_TIMEOUT) { this._removeUsedIndexBit(i); delete this._touchesIntegerDict[touch.getID()]; return i; } temp >>= 1; } return -1; }, _removeUsedIndexBit: function(index) { if (index < 0 || index >= this._maxTouches) return; var temp = 1 << index; temp = ~temp; this._indexBitsUsed &= temp; }, _glView: null, handleTouchesBegin: function(touches) { var selTouch = void 0, index = void 0, curTouch = void 0, touchID = void 0, handleTouches = [], locTouchIntDict = this._touchesIntegerDict, now = sys.now(); for (var i = 0, len = touches.length; i < len; i++) { selTouch = touches[i]; touchID = selTouch.getID(); index = locTouchIntDict[touchID]; if (null == index) { var unusedIndex = this._getUnUsedIndex(); if (-1 === unusedIndex) { cc.logID(2300, unusedIndex); continue; } curTouch = this._touches[unusedIndex] = new cc.Touch(selTouch._point.x, selTouch._point.y, selTouch.getID()); curTouch._lastModified = now; curTouch._setPrevPoint(selTouch._prevPoint); locTouchIntDict[touchID] = unusedIndex; handleTouches.push(curTouch); } } if (handleTouches.length > 0) { this._glView._convertTouchesWithScale(handleTouches); var touchEvent = new cc.Event.EventTouch(handleTouches); touchEvent._eventCode = cc.Event.EventTouch.BEGAN; eventManager.dispatchEvent(touchEvent); } }, handleTouchesMove: function(touches) { var selTouch = void 0, index = void 0, touchID = void 0, handleTouches = [], locTouches = this._touches, now = sys.now(); for (var i = 0, len = touches.length; i < len; i++) { selTouch = touches[i]; touchID = selTouch.getID(); index = this._touchesIntegerDict[touchID]; if (null == index) continue; if (locTouches[index]) { locTouches[index]._setPoint(selTouch._point); locTouches[index]._setPrevPoint(selTouch._prevPoint); locTouches[index]._lastModified = now; handleTouches.push(locTouches[index]); } } if (handleTouches.length > 0) { this._glView._convertTouchesWithScale(handleTouches); var touchEvent = new cc.Event.EventTouch(handleTouches); touchEvent._eventCode = cc.Event.EventTouch.MOVED; eventManager.dispatchEvent(touchEvent); } }, handleTouchesEnd: function(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(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.CANCELLED; eventManager.dispatchEvent(touchEvent); } this._preTouchPool.length = 0; }, getSetOfTouchesEndOrCancel: function(touches) { var selTouch = void 0, index = void 0, touchID = void 0, handleTouches = [], locTouches = this._touches, locTouchesIntDict = this._touchesIntegerDict; for (var i = 0, len = touches.length; i < len; i++) { selTouch = touches[i]; touchID = selTouch.getID(); index = locTouchesIntDict[touchID]; if (null == index) continue; if (locTouches[index]) { locTouches[index]._setPoint(selTouch._point); locTouches[index]._setPrevPoint(selTouch._prevPoint); handleTouches.push(locTouches[index]); this._removeUsedIndexBit(index); delete locTouchesIntDict[touchID]; } } return handleTouches; }, getHTMLElementPosition: function(element) { false; var docElem = document.documentElement; var leftOffset = window.pageXOffset - docElem.clientLeft; var topOffset = window.pageYOffset - docElem.clientTop; if (element.getBoundingClientRect) { var box = element.getBoundingClientRect(); return { left: box.left + leftOffset, top: box.top + topOffset, width: box.width, height: box.height }; } return element instanceof HTMLCanvasElement ? { left: leftOffset, top: topOffset, width: element.width, height: element.height } : { left: leftOffset, top: topOffset, width: parseInt(element.style.width), height: parseInt(element.style.height) }; }, getPreTouch: function(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(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(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(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(event, pos) { if (null != event.pageX) return { x: event.pageX, y: event.pageY }; false; pos.left -= document.body.scrollLeft; pos.top -= document.body.scrollTop; return { x: event.clientX, y: event.clientY }; }, getTouchesByEvent: function(event, pos) { var touchArr = [], locView = this._glView; var touch_event = void 0, touch = void 0, preLocation = void 0; 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(element) { if (this._isRegisterEvent) return; this._glView = cc.view; var selfPointer = this; var prohibition = sys.isMobile; var supportMouse = "mouse" in sys.capabilities; var supportTouches = "touches" in sys.capabilities; false; 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 pos = selfPointer.getHTMLElementPosition(element); var location = selfPointer.getPointByEvent(event, pos); if (!cc.rect(pos.left, pos.top, pos.width, pos.height).contains(location)) { selfPointer.handleTouchesEnd([ selfPointer.getTouchByXY(location.x, location.y, pos) ]); var mouseEvent = selfPointer.getMouseEvent(location, pos, 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, pos) { selfPointer._mousePressed = true; selfPointer.handleTouchesBegin([ selfPointer.getTouchByXY(location.x, location.y, pos) ]); element.focus(); } ], !prohibition && [ "mouseup", EventMouse.UP, function(event, mouseEvent, location, pos) { selfPointer._mousePressed = false; selfPointer.handleTouchesEnd([ selfPointer.getTouchByXY(location.x, location.y, pos) ]); } ], !prohibition && [ "mousemove", EventMouse.MOVE, function(event, mouseEvent, location, pos) { selfPointer.handleTouchesMove([ selfPointer.getTouchByXY(location.x, location.y, pos) ]); 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 pos = selfPointer.getHTMLElementPosition(element); var location = selfPointer.getPointByEvent(event, pos); var mouseEvent = selfPointer.getMouseEvent(location, pos, type); mouseEvent.setButton(event.button); handler(event, mouseEvent, location, pos); eventManager.dispatchEvent(mouseEvent); event.stopPropagation(); event.preventDefault(); }), false); })(); } } if (window.navigator.msPointerEnabled) { var _pointerEventsMap = { MSPointerDown: selfPointer.handleTouchesBegin, MSPointerMove: selfPointer.handleTouchesMove, MSPointerUp: selfPointer.handleTouchesEnd, MSPointerCancel: selfPointer.handleTouchesCancel }; var _loop = function(eventName) { var touchEvent = _pointerEventsMap[eventName]; element.addEventListener(eventName, (function(event) { var pos = selfPointer.getHTMLElementPosition(element); pos.left -= document.documentElement.scrollLeft; pos.top -= document.documentElement.scrollTop; touchEvent.call(selfPointer, [ selfPointer.getTouchByXY(event.clientX, event.clientY, pos) ]); event.stopPropagation(); }), false); }; for (var eventName in _pointerEventsMap) _loop(eventName); } supportTouches && (function() { var _touchEventsMap = { touchstart: function(touchesToHandle) { selfPointer.handleTouchesBegin(touchesToHandle); true; element.focus(); }, touchmove: function(touchesToHandle) { selfPointer.handleTouchesMove(touchesToHandle); }, touchend: function(touchesToHandle) { selfPointer.handleTouchesEnd(touchesToHandle); }, touchcancel: function(touchesToHandle) { selfPointer.handleTouchesCancel(touchesToHandle); } }; var registerTouchEvent = void 0; if (cc.sys.browserType === cc.sys.BROWSER_TYPE_WECHAT_GAME_SUB) { _touchEventsMap = { onTouchStart: _touchEventsMap.touchstart, onTouchMove: _touchEventsMap.touchmove, onTouchEnd: _touchEventsMap.touchend, onTouchCancel: _touchEventsMap.touchcancel }; registerTouchEvent = function(eventName) { var handler = _touchEventsMap[eventName]; wx[eventName]((function(event) { if (!event.changedTouches) return; var pos = selfPointer.getHTMLElementPosition(element); var body = document.body; pos.left -= body.scrollLeft || 0; pos.top -= body.scrollTop || 0; handler(selfPointer.getTouchesByEvent(event, pos)); })); }; } else registerTouchEvent = function(eventName) { var handler = _touchEventsMap[eventName]; element.addEventListener(eventName, (function(event) { if (!event.changedTouches) return; var pos = selfPointer.getHTMLElementPosition(element); var body = document.body; pos.left -= body.scrollLeft || 0; pos.top -= body.scrollTop || 0; handler(selfPointer.getTouchesByEvent(event, pos)); event.stopPropagation(); event.preventDefault(); }), false); }; for (var eventName in _touchEventsMap) registerTouchEvent(eventName); })(); cc.sys.browserType !== cc.sys.BROWSER_TYPE_WECHAT_GAME_SUB && this._registerKeyboardEvent(); this._isRegisterEvent = true; }, _registerKeyboardEvent: function() {}, _registerAccelerometerEvent: function() {}, update: function(dt) { if (this._accelCurTime > this._accelInterval) { this._accelCurTime -= this._accelInterval; eventManager.dispatchEvent(new cc.Event.EventAcceleration(this._acceleration)); } this._accelCurTime += dt; } }; module.exports = _cc.inputManager = inputManager; }), { "../event-manager": 101, "./CCMacro": 166, "./CCSys": 170 } ], 166: [ (function(require, module, exports) { var js = require("./js"); 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, DOWNLOAD_MAX_CONCURRENT: 64, ENABLE_TRANSPARENT_CANVAS: false, ENABLE_WEBGL_ANTIALIAS: false, ENABLE_CULLING: false, CLEANUP_IMAGE_CACHE: false }; js.getset(cc.macro, "ENABLE_3D", (function() { return cc._polyfill3D.enabled; }), (function(enabled) { enabled ? cc._polyfill3D.enable() : cc._polyfill3D.disable(); })); 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; }), { "./js": 181 } ], 167: [ (function(require, module, exports) { 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 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, 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 (__typeofVal = typeof obj[key], "object" === __typeofVal ? __realTypeOfObj(obj[key]) : __typeofVal) { 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 (__typeofVal = typeof attrs[attrKey], "object" === __typeofVal ? __realTypeOfObj(attrs[attrKey]) : __typeofVal) { 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" === (__typeofVal = typeof value, "object" === __typeofVal ? __realTypeOfObj(value) : __typeofVal) ? !!value && !(value._objFlags & (strictMode ? Destroyed | ToDestroy : Destroyed)) : "undefined" !== (__typeofVal = typeof value, "object" === __typeofVal ? __realTypeOfObj(value) : __typeofVal); }; false, false; cc.Object = module.exports = CCObject; }), { "./CCClass": 161, "./js": 181 } ], 168: [ (function(require, module, exports) { 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(xmlTxt) { return this._parseXML(xmlTxt); }, _parseXML: function(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(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(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(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(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": 181 } ], 169: [ (function(require, module, exports) { cc.screen = { _supportsFullScreen: false, _preOnFullScreenChange: null, _touchEvent: "", _fn: null, _fnMap: [ [ "requestFullscreen", "exitFullscreen", "fullscreenchange", "fullscreenEnabled", "fullscreenElement" ], [ "requestFullScreen", "exitFullScreen", "fullScreenchange", "fullScreenEnabled", "fullScreenElement" ], [ "webkitRequestFullScreen", "webkitCancelFullScreen", "webkitfullscreenchange", "webkitIsFullScreen", "webkitCurrentFullScreenElement" ], [ "mozRequestFullScreen", "mozCancelFullScreen", "mozfullscreenchange", "mozFullScreen", "mozFullScreenElement" ], [ "msRequestFullscreen", "msExitFullscreen", "MSFullscreenChange", "msFullscreenEnabled", "msFullscreenElement" ] ], init: function() { 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" !== (__typeofVal = typeof document[val[1]], "object" === __typeofVal ? __realTypeOfObj(document[val[1]]) : __typeofVal)) { 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 = "ontouchstart" in window ? "touchstart" : "mousedown"; }, fullScreen: function() { return !!this._supportsFullScreen && !!(document[this._fn.fullscreenElement] || document[this._fn.webkitFullscreenElement] || document[this._fn.mozFullScreenElement]); }, requestFullScreen: function(element, onFullScreenChange) { 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._preOnFullScreenChange && document.removeEventListener(eventName, this._preOnFullScreenChange); this._preOnFullScreenChange = onFullScreenChange; document.addEventListener(eventName, onFullScreenChange, false); } return element[this._fn.requestFullscreen](); }, exitFullScreen: function(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(element, onFullScreenChange) { element = element || document.body; var touchTarget = cc.game.canvas || element; var theScreen = this; function callback() { touchTarget.removeEventListener(theScreen._touchEvent, callback); theScreen.requestFullScreen(element, onFullScreenChange); } this.requestFullScreen(element, onFullScreenChange); touchTarget.addEventListener(this._touchEvent, callback); } }; cc.screen.init(); }), {} ], 170: [ (function(require, module, exports) { var settingPlatform = void 0; true; settingPlatform = window._CCSettings ? _CCSettings.platform : void 0; var isBaiduGame = "baidugame" === settingPlatform || "baidugame-subcontext" === settingPlatform; var isVivoGame = "qgame" === settingPlatform; var isOppoGame = "quickgame" === settingPlatform; 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.BROWSER_TYPE_WECHAT = "wechat"; sys.BROWSER_TYPE_WECHAT_GAME = "wechatgame"; sys.BROWSER_TYPE_WECHAT_GAME_SUB = "wechatgamesub"; sys.BROWSER_TYPE_BAIDU_GAME = "baidugame"; sys.BROWSER_TYPE_BAIDU_GAME_SUB = "baidugamesub"; sys.BROWSER_TYPE_QQ_PLAY = "qqplay"; sys.BROWSER_TYPE_ANDROID = "androidbrowser"; sys.BROWSER_TYPE_IE = "ie"; 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_UNKNOWN = "unknown"; sys.isNative = true; sys.isBrowser = "object" === (__typeofVal = typeof window, "object" === __typeofVal ? __realTypeOfObj(window) : __typeofVal) && "object" === (__typeofVal = typeof document, "object" === __typeofVal ? __realTypeOfObj(document) : __typeofVal) && false; false; var env; var system; var version; var w; var h; var ratio; var _supportWebGL; var _canvas; var env; var w; var h; var ratio; var _env; var win, nav, doc, docEle; var ua; var currLanguage; var isAndroid, iOS, osVersion, osMainVersion; var uaResult; var osName; var w; var h; var ratio; var _tmpCanvas1; var create3DContext; var localStorage; var warn; var _supportWebp; var _supportCanvas; var _supportWebGL; var capabilities; var __audioSupport; var formatSupport; true; var platform = void 0; platform = isVivoGame ? sys.VIVO_GAME : isOppoGame ? sys.OPPO_GAME : __getPlatform(); sys.platform = platform; sys.isMobile = platform === sys.ANDROID || platform === sys.IPAD || platform === sys.IPHONE || platform === sys.WP8 || platform === sys.TIZEN || platform === sys.BLACKBERRY || platform === sys.VIVO_GAME || platform === sys.OPPO_GAME; sys.os = __getOS(); sys.language = __getCurrentLanguage(); var languageCode; true; languageCode = __getCurrentLanguageCode(); sys.languageCode = languageCode ? languageCode.toLowerCase() : void 0; sys.osVersion = __getOSVersion(); sys.osMainVersion = parseInt(sys.osVersion); sys.browserType = null; sys.browserVersion = null; var w = window.innerWidth; var h = window.innerHeight; var ratio = window.devicePixelRatio || 1; sys.windowPixelResolution = { width: ratio * w, height: ratio * h }; sys.localStorage = window.localStorage; var capabilities; capabilities = sys.capabilities = { canvas: false, opengl: true, webp: true }; if (sys.isMobile) { capabilities["accelerometer"] = true; capabilities["touches"] = true; } else { capabilities["keyboard"] = true; capabilities["mouse"] = true; capabilities["touches"] = false; } sys.__audioSupport = { ONLY_ONE: false, WEB_AUDIO: false, DELAY_CREATE_CTX: false, format: [ ".mp3" ] }; 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.getSafeAreaRect = function() { var visibleSize = cc.view.getVisibleSize(); return cc.rect(0, 0, visibleSize.width, visibleSize.height); }; 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) { true; jsb.openURL(url); }; sys.now = function() { return Date.now ? Date.now() : +new Date(); }; return sys; } var sys = cc && cc.sys ? cc.sys : initSys(); module.exports = sys; }), {} ], 171: [ (function(require, module, exports) { var EventTarget = require("../event/event-target"); var js = require("../platform/js"); var renderer = require("../renderer"); require("../platform/CCClass"); var isBaiduGame = cc.sys.platform === cc.sys.BAIDU_GAME; var __BrowserGetter = { init: function() { (true, true) && !isBaiduGame && (this.html = document.getElementsByTagName("html")[0]); }, availWidth: function(frame) { return frame && frame !== this.html ? frame.clientWidth : window.innerWidth; }, availHeight: function(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); isBaiduGame && (cc.sys.browserType === cc.sys.BROWSER_TYPE_BAIDU_GAME_SUB ? __BrowserGetter.adaptationType = cc.sys.BROWSER_TYPE_BAIDU_GAME_SUB : __BrowserGetter.adaptationType = cc.sys.BROWSER_TYPE_BAIDU_GAME); false; false; switch (__BrowserGetter.adaptationType) { case cc.sys.BROWSER_TYPE_SAFARI: __BrowserGetter.meta["minimal-ui"] = "true"; case cc.sys.BROWSER_TYPE_SOUGOU: case cc.sys.BROWSER_TYPE_UC: __BrowserGetter.availWidth = function(frame) { return frame.clientWidth; }; __BrowserGetter.availHeight = function(frame) { return frame.clientHeight; }; break; case cc.sys.BROWSER_TYPE_WECHAT_GAME: __BrowserGetter.availWidth = function() { return window.innerWidth; }; __BrowserGetter.availHeight = function() { return window.innerHeight; }; break; case cc.sys.BROWSER_TYPE_WECHAT_GAME_SUB: var sharedCanvas = window.sharedCanvas || wx.getSharedCanvas(); __BrowserGetter.availWidth = function() { return sharedCanvas.width; }; __BrowserGetter.availHeight = function() { return sharedCanvas.height; }; } var _scissorRect = null; var View = function() { 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; _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() { this._initFrameSize(); this.enableAntiAlias(true); 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(forceOrEvent) { var view; view = this.setDesignResolutionSize ? this : cc.view; 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() { cc.view._orientationChanging = true; cc.view._resizeEvent(); }, resizeWithBrowserSize: function(enabled) { if (enabled) { if (!this._resizeWithBrowserSize) { this._resizeWithBrowserSize = true; window.addEventListener("resize", this._resizeEvent); window.addEventListener("orientationchange", this._orientationChange); } } else if (this._resizeWithBrowserSize) { this._resizeWithBrowserSize = false; window.removeEventListener("resize", this._resizeEvent); window.removeEventListener("orientationchange", this._orientationChange); } }, setResizeCallback: function(callback) { false; "function" !== (__typeofVal = typeof callback, "object" === __typeofVal ? __realTypeOfObj(callback) : __typeofVal) && null != callback || (this._resizeCallback = callback); }, setOrientation: function(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() { 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); }, _adjustSizeKeepCanvasSize: function() { var designWidth = this._originalDesignResolutionSize.width; var designHeight = this._originalDesignResolutionSize.height; designWidth > 0 && this.setDesignResolutionSize(designWidth, designHeight, this._resolutionPolicy); }, _setViewportMeta: function(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.replace(pattern, key + "=" + metas[key]); } /^,/.test(content) && (content = content.substr(1)); vp.content = content; currentVP && (currentVP.content = content); document.head.appendChild(vp); }, _adjustViewportMeta: function() { if (this._isAdjustViewport && false) { this._setViewportMeta(__BrowserGetter.meta, false); this._isAdjustViewport = false; } }, adjustViewportMeta: function(enabled) { this._isAdjustViewport = enabled; }, enableRetina: function(enabled) { this._retinaEnabled = !!enabled; }, isRetinaEnabled: function() { return this._retinaEnabled; }, enableAntiAlias: function(enabled) { if (this._antiAliasEnabled === enabled) return; this._antiAliasEnabled = enabled; if (cc.game.renderType === cc.game.RENDER_TYPE_WEBGL) { var cache = cc.loader._cache; for (var key in cache) { var item = cache[key]; var tex = item && item.content instanceof cc.Texture2D ? item.content : null; if (tex) { var Filter = cc.Texture2D.Filter; enabled ? tex.setFilters(Filter.LINEAR, Filter.LINEAR) : tex.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() { return this._antiAliasEnabled; }, enableAutoFullScreen: function(enabled) { if (enabled && enabled !== this._autoFullScreen && cc.sys.isMobile && cc.sys.browserType !== cc.sys.BROWSER_TYPE_WECHAT) { this._autoFullScreen = true; cc.screen.autoFullScreen(cc.game.frame); } else this._autoFullScreen = false; }, isAutoFullScreenEnabled: function() { return this._autoFullScreen; }, setCanvasSize: function(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() { return cc.size(cc.game.canvas.width, cc.game.canvas.height); }, getFrameSize: function() { return cc.size(this._frameSize.width, this._frameSize.height); }, setFrameSize: function(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() { return cc.size(this._visibleRect.width, this._visibleRect.height); }, getVisibleSizeInPixel: function() { return cc.size(this._visibleRect.width * this._scaleX, this._visibleRect.height * this._scaleY); }, getVisibleOrigin: function() { return cc.v2(this._visibleRect.x, this._visibleRect.y); }, getVisibleOriginInPixel: function() { return cc.v2(this._visibleRect.x * this._scaleX, this._visibleRect.y * this._scaleY); }, getResolutionPolicy: function() { return this._resolutionPolicy; }, setResolutionPolicy: function(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(width, height, resolutionPolicy) { if (!(width > 0 || height > 0)) { cc.logID(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(); this.emit("design-resolution-changed"); }, getDesignResolutionSize: function() { return cc.size(this._designResolutionSize.width, this._designResolutionSize.height); }, setRealPixelResolution: function(width, height, resolutionPolicy) { false; this.setDesignResolutionSize(width, height, resolutionPolicy); }, setViewportInPoints: function(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(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() { return cc.game._renderContext.isEnabled(gl.SCISSOR_TEST); }, getScissorRect: function() { 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() { return this._viewportRect; }, getScaleX: function() { return this._scaleX; }, getScaleY: function() { return this._scaleY; }, getDevicePixelRatio: function() { return this._devicePixelRatio; }, convertToLocationInView: function(tx, ty, relatedPos, out) { var result = out || cc.v2(); var x = this._devicePixelRatio * (tx - relatedPos.left); var y = this._devicePixelRatio * (relatedPos.top + 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(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(point) { var viewport = this._viewportRect; point.x = (point.x - viewport.x) / this._scaleX; point.y = (point.y - viewport.y) / this._scaleY; }, _convertTouchesWithScale: function(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(view) {}, apply: function(view, designedResolution) {}, postApply: function(view) {}, _setupContainer: function(view, w, h) { var locCanvas = cc.game.canvas, locContainer = cc.game.container; if (true, !isBaiduGame) { 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"; } var devicePixelRatio = view._devicePixelRatio = 1; if (view.isRetinaEnabled()) { false; devicePixelRatio = view._devicePixelRatio = Math.min(view._maxPixelRatio, window.devicePixelRatio || 1); } locCanvas.width = w * devicePixelRatio; locCanvas.height = h * devicePixelRatio; }, _fixContainer: function() { 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() { this._result = { scale: [ 1, 1 ], viewport: null }; }, _buildResult: function(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(view) {}, apply: function(view, designedResolution) { return { scale: [ 1, 1 ] }; }, postApply: function(view) {} }); (function() { var EqualToFrame = cc.Class({ name: "EqualToFrame", extends: cc.ContainerStrategy, apply: function(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(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(view) { this._super(view); cc.game.frame = document.documentElement; }, apply: function(view) { this._super(view); this._fixContainer(); } }); var ProportionalToWindow = cc.Class({ name: "ProportionalToWindow", extends: ProportionalToFrame, preApply: function(view) { this._super(view); cc.game.frame = document.documentElement; }, apply: function(view, designedResolution) { this._super(view, designedResolution); this._fixContainer(); } }); var OriginalContainer = cc.Class({ name: "OriginalContainer", extends: cc.ContainerStrategy, apply: function(view) { this._setupContainer(view, cc.game.canvas.width, cc.game.canvas.height); } }); 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(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(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(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(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(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(containerStg, contentStg) { this._containerStrategy = null; this._contentStrategy = null; this.setContainerStrategy(containerStg); this.setContentStrategy(contentStg); }, preApply: function(view) { this._containerStrategy.preApply(view); this._contentStrategy.preApply(view); }, apply: function(view, designedResolution) { this._containerStrategy.apply(view, designedResolution); return this._contentStrategy.apply(view, designedResolution); }, postApply: function(view) { this._containerStrategy.postApply(view); this._contentStrategy.postApply(view); }, setContainerStrategy: function(containerStg) { containerStg instanceof cc.ContainerStrategy && (this._containerStrategy = containerStg); }, setContentStrategy: function(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.v2(); module.exports = cc.view; }), { "../event/event-target": 103, "../platform/CCClass": 161, "../platform/js": 181, "../renderer": 202 } ], 172: [ (function(require, module, exports) { 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(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; } }; }), {} ], 173: [ (function(require, module, exports) { var js = require("./js"); var isPlainEmptyObj = require("./utils").isPlainEmptyObj_DEV; var DELIMETER = "$_$"; function createAttrsSingle(owner, ownerCtor, superAttrs) { var AttrsCtor; var ctorName; false; AttrsCtor = function() {}; superAttrs && js.extend(AttrsCtor, superAttrs.constructor); var attrs = new AttrsCtor(); js.value(owner, "__attrs__", attrs); return attrs; } function createAttrs(subclass) { 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, cls, superClass && superClass.__attrs__); } } superClass = chains[0]; createAttrsSingle(subclass, subclass, superClass && superClass.__attrs__); return subclass.__attrs__; } function attr(ctor, propName, newAttrs) { var attrs, setter, key; if ("function" === (__typeofVal = typeof ctor, "object" === __typeofVal ? __realTypeOfObj(ctor) : __typeofVal)) { attrs = getClassAttrs(ctor); setter = attrs.constructor.prototype; } else { var instance = ctor; attrs = instance.__attrs__; if (!attrs) { ctor = instance.constructor; var clsAttrs = getClassAttrs(ctor); attrs = createAttrsSingle(instance, ctor, clsAttrs); } setter = attrs; } if ("undefined" === (__typeofVal = typeof newAttrs, "object" === __typeofVal ? __realTypeOfObj(newAttrs) : __typeofVal)) { var prefix = propName + DELIMETER; var ret = {}; for (key in attrs) key.startsWith(prefix) && (ret[key.slice(prefix.length)] = attrs[key]); return ret; } if ("object" === (__typeofVal = typeof newAttrs, "object" === __typeofVal ? __realTypeOfObj(newAttrs) : __typeofVal)) for (key in newAttrs) 95 !== key.charCodeAt(0) && (setter[propName + DELIMETER + key] = newAttrs[key]); else false; } function getClassAttrs(ctor) { return ctor.hasOwnProperty("__attrs__") && ctor.__attrs__ || createAttrs(ctor); } function getClassAttrsProto(ctor) { return getClassAttrs(ctor).constructor.prototype; } function setClassAttr(ctor, propName, key, value) { var proto = getClassAttrsProto(ctor); proto[propName + DELIMETER + key] = value; } cc.Integer = "Integer"; cc.Float = "Float"; false; cc.Boolean = "Boolean"; cc.String = "String"; function getTypeChecker(type, attrName) { false; } function ObjectType(typeCtor) { return { type: "Object", ctor: typeCtor, _onAfterProp: false }; } module.exports = { attr: attr, getClassAttrs: getClassAttrs, getClassAttrsProto: getClassAttrsProto, setClassAttr: setClassAttr, DELIMETER: DELIMETER, getTypeChecker: getTypeChecker, ObjectType: ObjectType, ScriptUuid: {} }; }), { "./CCClass": 161, "./js": 181, "./utils": 185 } ], 174: [ (function(require, module, exports) { var js = require("./js"); var fastRemoveAt = js.array.fastRemoveAt; function CallbackList() { this.callbacks = []; this.targets = []; this.isInvoking = false; this.containCanceled = false; } var proto = CallbackList.prototype; proto.removeBy = function(array, value) { var callbacks = this.callbacks; var targets = this.targets; for (var i = 0; i < array.length; ++i) if (array[i] === value) { fastRemoveAt(callbacks, i); fastRemoveAt(targets, i); --i; } }; proto.cancel = function(index) { this.callbacks[index] = this.targets[index] = null; this.containCanceled = true; }; proto.cancelAll = function() { var callbacks = this.callbacks; var targets = this.targets; for (var i = 0; i < callbacks.length; i++) callbacks[i] = targets[i] = null; this.containCanceled = true; }; proto.purgeCanceled = function() { this.removeBy(this.callbacks, null); this.containCanceled = false; }; var MAX_SIZE = 16; var callbackListPool = new js.Pool(function(list) { list.callbacks.length = 0; list.targets.length = 0; list.isInvoking = false; list.containCanceled = false; }, MAX_SIZE); callbackListPool.get = function() { return this._get() || new CallbackList(); }; function CallbacksHandler() { this._callbackTable = js.createMap(true); } proto = CallbacksHandler.prototype; proto.add = function(key, callback, target) { var list = this._callbackTable[key]; list || (list = this._callbackTable[key] = callbackListPool.get()); list.callbacks.push(callback); list.targets.push(target || null); }; proto.hasEventListener = function(key, callback, target) { var list = this._callbackTable[key]; if (!list) return false; var callbacks = list.callbacks; if (!callback) { if (list.isInvoking) { for (var i = 0; i < callbacks.length; i++) if (callbacks[i]) return true; return false; } return callbacks.length > 0; } target = target || null; var targets = list.targets; for (var _i = 0; _i < callbacks.length; ++_i) if (callbacks[_i] === callback && targets[_i] === target) return true; return false; }; proto.removeAll = function(keyOrTarget) { if ("string" === (__typeofVal = typeof keyOrTarget, "object" === __typeofVal ? __realTypeOfObj(keyOrTarget) : __typeofVal)) { var list = this._callbackTable[keyOrTarget]; if (list) if (list.isInvoking) list.cancelAll(); else { 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 targets = _list.targets; for (var i = 0; i < targets.length; ++i) targets[i] === keyOrTarget && _list.cancel(i); } else _list.removeBy(_list.targets, keyOrTarget); } }; proto.remove = function(key, callback, target) { var list = this._callbackTable[key]; if (list) { target = target || null; var callbacks = list.callbacks; var targets = list.targets; for (var i = 0; i < callbacks.length; ++i) if (callbacks[i] === callback && targets[i] === target) { if (list.isInvoking) list.cancel(i); else { fastRemoveAt(callbacks, i); fastRemoveAt(targets, i); } break; } } }; var CallbacksInvoker = function() { CallbacksHandler.call(this); }; js.extend(CallbacksInvoker, CallbacksHandler); false; CallbacksInvoker.prototype.invoke = function(key, p1, p2, p3, p4, p5) { var list = this._callbackTable[key]; if (list) { var rootInvoker = !list.isInvoking; list.isInvoking = true; var callbacks = list.callbacks; var targets = list.targets; for (var i = 0, len = callbacks.length; i < len; ++i) { var callback = callbacks[i]; if (callback) { var target = targets[i]; target ? callback.call(target, p1, p2, p3, p4, p5) : callback(p1, p2, p3, p4, p5); } } if (rootInvoker) { list.isInvoking = false; list.containCanceled && list.purgeCanceled(); } } }; CallbacksInvoker.CallbacksHandler = CallbacksHandler; module.exports = CallbacksInvoker; }), { "./js": 181 } ], 175: [ (function(require, module, exports) { 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 }; }), {} ], 176: [ (function(require, module, exports) { var js = require("./js"); var Attr = require("./attribute"); var CCClass = require("./CCClass"); var misc = require("../utils/misc"); var Details = function() { this.uuidList = []; this.uuidObjList = []; this.uuidPropList = []; this._stillUseUrl = js.createMap(true); }; Details.prototype.reset = function() { this.uuidList.length = 0; this.uuidObjList.length = 0; this.uuidPropList.length = 0; js.clear(this._stillUseUrl); }; false, false; Details.prototype.push = function(obj, propName, uuid, _stillUseUrl) { _stillUseUrl && (this._stillUseUrl[this.uuidList.length] = true); this.uuidList.push(uuid); this.uuidObjList.push(obj); this.uuidPropList.push(propName); }; Details.pool = new js.Pool(function(obj) { obj.reset(); }, 10); Details.pool.get = function() { return this._get() || new Details(); }; var _Deserializer = (function() { function _Deserializer(result, target, classFinder, customEnv, ignoreEditorOnly) { this.result = result; this.customEnv = customEnv; this.deserializedList = []; this.deserializedData = null; this._classFinder = classFinder; false; this._idList = []; this._idObjList = []; this._idPropList = []; } function _dereference(self) { var deserializedList = self.deserializedList; var idPropList = self._idPropList; var idList = self._idList; var idObjList = self._idObjList; var onDereferenced = self._classFinder && self._classFinder.onDereferenced; var i, propName, id; false; for (i = 0; i < idList.length; i++) { propName = idPropList[i]; id = idList[i]; idObjList[i][propName] = deserializedList[id]; } } var prototype = _Deserializer.prototype; prototype.deserialize = function(jsonObj) { if (Array.isArray(jsonObj)) { var jsonArray = jsonObj; var refCount = jsonArray.length; this.deserializedList.length = refCount; for (var i = 0; i < refCount; i++) if (jsonArray[i]) { var mainTarget; false, false; this.deserializedList[i] = this._deserializeObject(jsonArray[i], false); } this.deserializedData = refCount > 0 ? this.deserializedList[0] : []; } else { this.deserializedList.length = 1; false, false; this.deserializedData = jsonObj ? this._deserializeObject(jsonObj, false) : null; this.deserializedList[0] = this.deserializedData; } _dereference(this); return this.deserializedData; }; prototype._deserializeObject = function(serialized, _stillUseUrl, target, owner, propName) { var prop; var obj = null; var klass = null; var type = serialized.__type__; if (type) { klass = this._classFinder(type, serialized, owner, propName); if (!klass) { var notReported = this._classFinder === js._getClassById; notReported && cc.deserialize.reportMissingClass(type); return null; } if ((false, false) && target) { target instanceof klass || cc.warnID(5300, js.getClassName(target), klass); obj = target; } else obj = new klass(); if (obj._deserialize) { obj._deserialize(serialized.content, this); return obj; } cc.Class._isCCClass(klass) ? _deserializeFireClass(this, obj, serialized, klass, target) : this._deserializeTypedObject(obj, serialized, klass); } else if (Array.isArray(serialized)) { if ((false, false) && target) { target.length = serialized.length; obj = target; } else obj = new Array(serialized.length); for (var i = 0; i < serialized.length; i++) { prop = serialized[i]; if ("object" === (__typeofVal = typeof prop, "object" === __typeofVal ? __realTypeOfObj(prop) : __typeofVal) && prop) { false, false; this._deserializeObjField(obj, prop, "" + i, null, _stillUseUrl); } else obj[i] = prop; } } else { obj = (false, false) && target || {}; this._deserializePrimitiveObject(obj, serialized); } return obj; }; prototype._deserializeObjField = function(obj, jsonObj, propName, target, _stillUseUrl) { var id = jsonObj.__id__; if (void 0 === id) { var uuid = jsonObj.__uuid__; if (uuid) this.result.push(obj, propName, uuid, _stillUseUrl); else { false, false; obj[propName] = this._deserializeObject(jsonObj, _stillUseUrl); } } else { var dObj = this.deserializedList[id]; if (dObj) obj[propName] = dObj; else { this._idList.push(id); this._idObjList.push(obj); this._idPropList.push(propName); } } }; prototype._deserializePrimitiveObject = function(instance, serialized) { var self = this; for (var propName in serialized) if (serialized.hasOwnProperty(propName)) { var prop = serialized[propName]; if ("object" !== (__typeofVal = typeof prop, "object" === __typeofVal ? __realTypeOfObj(prop) : __typeofVal)) "__type__" !== propName && (instance[propName] = prop); else if (prop) { false, false; self._deserializeObjField(instance, prop, propName); } else instance[propName] = null; } }; prototype._deserializeTypedObject = function(instance, serialized, klass) { if (klass === cc.Vec2) { instance.x = serialized.x || 0; instance.y = serialized.y || 0; return; } if (klass === cc.Vec3) { instance.x = serialized.x || 0; instance.y = serialized.y || 0; instance.z = serialized.z || 0; return; } if (klass === cc.Color) { instance.r = serialized.r || 0; instance.g = serialized.g || 0; instance.b = serialized.b || 0; var a = serialized.a; instance.a = void 0 === a ? 255 : a; return; } if (klass === cc.Size) { instance.width = serialized.width || 0; instance.height = serialized.height || 0; return; } var DEFAULT = Attr.DELIMETER + "default"; var attrs = Attr.getClassAttrs(klass); var fastDefinedProps = klass.__props__ || Object.keys(instance); for (var i = 0; i < fastDefinedProps.length; i++) { var propName = fastDefinedProps[i]; var value = serialized[propName]; void 0 !== value && serialized.hasOwnProperty(propName) || (value = CCClass.getDefault(attrs[propName + DEFAULT])); if ("object" !== (__typeofVal = typeof value, "object" === __typeofVal ? __realTypeOfObj(value) : __typeofVal)) instance[propName] = value; else if (value) { false, false; this._deserializeObjField(instance, value, propName); } else instance[propName] = null; } }; function compileObjectTypeJit(sources, defaultValue, accessorToSet, propNameLiteralToSet, assumeHavePropIfIsValue, stillUseUrl) { if (defaultValue instanceof cc.ValueType) { assumeHavePropIfIsValue || sources.push("if(prop){"); var ctorCode = js.getClassName(defaultValue); sources.push("s._deserializeTypedObject(o" + accessorToSet + ",prop," + ctorCode + ");"); assumeHavePropIfIsValue || sources.push("}else o" + accessorToSet + "=null;"); } else { sources.push("if(prop){"); sources.push("s._deserializeObjField(o,prop," + propNameLiteralToSet + (false, ",null,") + !!stillUseUrl + ");"); sources.push("}else o" + accessorToSet + "=null;"); } } var compileDeserialize = function(self, klass) { var TYPE = Attr.DELIMETER + "type"; var EDITOR_ONLY = Attr.DELIMETER + "editorOnly"; var DEFAULT = Attr.DELIMETER + "default"; var SAVE_URL_AS_ASSET = Attr.DELIMETER + "saveUrlAsAsset"; var FORMERLY_SERIALIZED_AS = Attr.DELIMETER + "formerlySerializedAs"; var attrs = Attr.getClassAttrs(klass); var props = klass.__values__; var sources = [ "var prop;" ]; var fastMode = misc.BUILTIN_CLASSID_RE.test(js._getClassId(klass)); for (var p = 0; p < props.length; p++) { var propName = props[p]; if ((false, false) && attrs[propName + EDITOR_ONLY]) continue; var accessorToSet, propNameLiteralToSet; if (CCClass.IDENTIFIER_RE.test(propName)) { propNameLiteralToSet = '"' + propName + '"'; accessorToSet = "." + propName; } else { propNameLiteralToSet = CCClass.escapeForJS(propName); accessorToSet = "[" + propNameLiteralToSet + "]"; } var accessorToGet = accessorToSet; if (attrs[propName + FORMERLY_SERIALIZED_AS]) { var propNameToRead = attrs[propName + FORMERLY_SERIALIZED_AS]; accessorToGet = CCClass.IDENTIFIER_RE.test(propNameToRead) ? "." + propNameToRead : "[" + CCClass.escapeForJS(propNameToRead) + "]"; } sources.push("prop=d" + accessorToGet + ";"); sources.push('if(typeof (prop)!=="undefined"){'); var stillUseUrl = attrs[propName + SAVE_URL_AS_ASSET]; var defaultValue = CCClass.getDefault(attrs[propName + DEFAULT]); if (fastMode) { var isPrimitiveType; var userType = attrs[propName + TYPE]; if (void 0 === defaultValue && userType) isPrimitiveType = userType === cc.String || userType === cc.Integer || userType === cc.Float || userType === cc.Boolean; else { var defaultType = (__typeofVal = typeof defaultValue, "object" === __typeofVal ? __realTypeOfObj(defaultValue) : __typeofVal); isPrimitiveType = "string" === defaultType && !stillUseUrl || "number" === defaultType || "boolean" === defaultType; } isPrimitiveType ? sources.push("o" + accessorToSet + "=prop;") : compileObjectTypeJit(sources, defaultValue, accessorToSet, propNameLiteralToSet, true, stillUseUrl); } else { sources.push('if(typeof (prop)!=="object"){o' + accessorToSet + "=prop;}else{"); compileObjectTypeJit(sources, defaultValue, accessorToSet, propNameLiteralToSet, false, stillUseUrl); sources.push("}"); } sources.push("}"); } if (cc.js.isChildClassOf(klass, cc._BaseNode) || cc.js.isChildClassOf(klass, cc.Component)) { var mayUsedInPersistRoot; false, false; sources.push("d._id&&(o._id=d._id);"); } if ("_$erialized" === props[props.length - 1]) { sources.push("o._$erialized=JSON.parse(JSON.stringify(d));"); sources.push("s._deserializePrimitiveObject(o._$erialized,d);"); } return Function("s", "o", "d", "k", "t", sources.join("")); }; function unlinkUnusedPrefab(self, serialized, obj) { var uuid = serialized["asset"] && serialized["asset"].__uuid__; if (uuid) { var last = self.result.uuidList.length - 1; if (self.result.uuidList[last] === uuid && self.result.uuidObjList[last] === obj && "asset" === self.result.uuidPropList[last]) { self.result.uuidList.pop(); self.result.uuidObjList.pop(); self.result.uuidPropList.pop(); } else { var debugEnvOnlyInfo = "Failed to skip prefab asset while deserializing PrefabInfo"; cc.warn(debugEnvOnlyInfo); } } } function _deserializeFireClass(self, obj, serialized, klass, target) { var deserialize; if (klass.hasOwnProperty("__deserialize__")) deserialize = klass.__deserialize__; else { deserialize = compileDeserialize(self, klass); js.value(klass, "__deserialize__", deserialize, true); } deserialize(self, obj, serialized, klass, target); false, false; } _Deserializer.pool = new js.Pool(function(obj) { obj.result = null; obj.customEnv = null; obj.deserializedList.length = 0; obj.deserializedData = null; obj._classFinder = null; false; obj._idList.length = 0; obj._idObjList.length = 0; obj._idPropList.length = 0; }, 1); _Deserializer.pool.get = function(result, target, classFinder, customEnv, ignoreEditorOnly) { var cache = this._get(); if (cache) { cache.result = result; cache.customEnv = customEnv; cache._classFinder = classFinder; false; return cache; } return new _Deserializer(result, target, classFinder, customEnv, ignoreEditorOnly); }; return _Deserializer; })(); cc.deserialize = function(data, details, options) { options = options || {}; var classFinder = options.classFinder || js._getClassById; var createAssetRefs = options.createAssetRefs || cc.sys.platform === cc.sys.EDITOR_CORE; var target = (false, false) && options.target; var customEnv = options.customEnv; var ignoreEditorOnly = options.ignoreEditorOnly; false; "string" === (__typeofVal = typeof data, "object" === __typeofVal ? __realTypeOfObj(data) : __typeofVal) && (data = JSON.parse(data)); var tempDetails = !details; details = details || Details.pool.get(); var deserializer = _Deserializer.pool.get(details, target, classFinder, customEnv, ignoreEditorOnly); cc.game._isCloning = true; var res = deserializer.deserialize(data); cc.game._isCloning = false; _Deserializer.pool.put(deserializer); createAssetRefs && details.assignAssetsBy(Editor.serialize.asAsset); tempDetails && Details.pool.put(details); return res; }; cc.deserialize.Details = Details; cc.deserialize.reportMissingClass = function(id) { false; cc.warnID(5302, id); }; }), { "../utils/misc": 243, "./CCClass": 161, "./attribute": 173, "./js": 181 } ], 177: [ (function(require, module, exports) { 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; }), {} ], 178: [ (function(require, module, exports) { require("./js"); require("./CCClass"); require("./CCClassDecorator"); require("./CCEnum"); require("./CCObject"); require("./callbacks-invoker"); require("./url"); require("./deserialize"); require("./instantiate"); require("./instantiate-jit"); require("./requiring-frame"); require("./CCSys"); require("./CCMacro"); true; require("./CCAssetLibrary"); require("./CCVisibleRect"); }), { "./CCAssetLibrary": 160, "./CCClass": 161, "./CCClassDecorator": 162, "./CCEnum": 163, "./CCMacro": 166, "./CCObject": 167, "./CCSys": 170, "./CCVisibleRect": 172, "./callbacks-invoker": 174, "./deserialize": 176, "./instantiate": 180, "./instantiate-jit": 179, "./js": 181, "./requiring-frame": 183, "./url": 184 } ], 179: [ (function(require, module, exports) { 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 }; 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" === (__typeofVal = typeof def, "object" === __typeofVal ? __realTypeOfObj(def) : __typeofVal)) try { def = def(); } catch (e) { return false; } if (def === value) return true; if (def && value) { if (def instanceof cc.ValueType && def.equals(value)) return true; if (Array.isArray(def) && Array.isArray(value) || def.constructor === Object && value.constructor === Object) try { return Array.isArray(def) && Array.isArray(value) && 0 === def.length && 0 === value.length; } catch (e) {} } 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" === (__typeofVal = typeof val, "object" === __typeofVal ? __realTypeOfObj(val) : __typeofVal) && 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.enumerateField = function(obj, key, value) { if ("object" === (__typeofVal = typeof value, "object" === __typeofVal ? __realTypeOfObj(value) : __typeofVal) && 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 Array.isArray(value) ? this.instantiateArray(value) : this.instantiateObj(value); } if ("function" === (__typeofVal = typeof value, "object" === __typeofVal ? __realTypeOfObj(value) : __typeofVal)) return this.getFuncModule(value); if ("string" === (__typeofVal = typeof value, "object" === __typeofVal ? __realTypeOfObj(value) : __typeofVal)) 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" === (__typeofVal = typeof value, "object" === __typeofVal ? __realTypeOfObj(value) : __typeofVal) && 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 && !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": 161, "./CCObject": 167, "./attribute": 173, "./compiler": 175, "./js": 181 } ], 180: [ (function(require, module, exports) { 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" !== (__typeofVal = typeof original, "object" === __typeofVal ? __realTypeOfObj(original) : __typeofVal) || 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(); 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" === (__typeofVal = typeof value, "object" === __typeofVal ? __realTypeOfObj(value) : __typeofVal) && 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" === (__typeofVal = typeof value, "object" === __typeofVal ? __realTypeOfObj(value) : __typeofVal) && 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 (Array.isArray(obj)) { var len = obj.length; clone = new Array(len); js.value(obj, "_iN$t", clone, true); for (var i = 0; i < len; ++i) { var value = obj[i]; "object" === (__typeofVal = typeof value, "object" === __typeofVal ? __realTypeOfObj(value) : __typeofVal) && value ? clone[i] = value._iN$t || instantiateObj(value, parent) : clone[i] = value; } objsToClearTmpVar.push(obj); 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 && !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": 258, "./CCObject": 167, "./js": 181, "./utils": 185 } ], 181: [ (function(require, module, exports) { 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(obj) { return "number" === (__typeofVal = typeof obj, "object" === __typeofVal ? __realTypeOfObj(obj) : __typeofVal) || obj instanceof Number; }, isString: function(obj) { return "string" === (__typeofVal = typeof obj, "object" === __typeofVal ? __realTypeOfObj(obj) : __typeofVal) || obj instanceof String; }, addon: function(obj) { "use strict"; obj = obj || {}; for (var i = 1, length = arguments.length; i < length; i++) { var source = arguments[i]; if (source) { if ("object" !== (__typeofVal = typeof source, "object" === __typeofVal ? __realTypeOfObj(source) : __typeofVal)) { cc.errorID(5402, source); continue; } for (var name in source) name in obj || _copyprop(name, source, obj); } } return obj; }, mixin: function(obj) { "use strict"; obj = obj || {}; for (var i = 1, length = arguments.length; i < length; i++) { var source = arguments[i]; if (source) { if ("object" !== (__typeofVal = typeof source, "object" === __typeofVal ? __realTypeOfObj(source) : __typeofVal)) { cc.errorID(5403, source); continue; } for (var name in source) _copyprop(name, source, obj); } } return obj; }, extend: function(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(ctor) { var proto = ctor.prototype; var dunderProto = proto && Object.getPrototypeOf(proto); return dunderProto && dunderProto.constructor; }, isChildClassOf: function(subclass, superclass) { if (subclass && superclass) { if ("function" !== (__typeofVal = typeof subclass, "object" === __typeofVal ? __realTypeOfObj(subclass) : __typeofVal)) return false; if ("function" !== (__typeofVal = typeof superclass, "object" === __typeofVal ? __realTypeOfObj(superclass) : __typeofVal)) { 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(obj) { var keys = Object.keys(obj); for (var i = 0; i < keys.length; i++) delete obj[keys[i]]; }, isEmptyObject: function(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) { if ("function" !== (__typeofVal = typeof setter, "object" === __typeofVal ? __realTypeOfObj(setter) : __typeofVal)) { enumerable = setter; setter = void 0; } tmpGetSetDesc.get = getter; tmpGetSetDesc.set = setter; tmpGetSetDesc.enumerable = enumerable; 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" === (__typeofVal = typeof objOrCtor, "object" === __typeofVal ? __realTypeOfObj(objOrCtor) : __typeofVal)) { 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" !== (__typeofVal = typeof id, "object" === __typeofVal ? __realTypeOfObj(id) : __typeofVal) || 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" === (__typeofVal = typeof allowTempId, "object" === __typeofVal ? __realTypeOfObj(allowTempId) : __typeofVal) || allowTempId; var res; if ("function" === (__typeofVal = typeof obj, "object" === __typeofVal ? __realTypeOfObj(obj) : __typeofVal) && 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" === (__typeofVal = typeof msg, "object" === __typeofVal ? __realTypeOfObj(msg) : __typeofVal) && REGEXP_NUM_OR_STR.test(msg); if (hasSubstitution) for (var i = 1; i < argLen; ++i) { var arg = arguments[i]; var regExpToTest = "number" === (__typeofVal = typeof arg, "object" === __typeofVal ? __realTypeOfObj(arg) : __typeofVal) ? REGEXP_NUM_OR_STR : REGEXP_STR; regExpToTest.test(msg) ? msg = msg.replace(regExpToTest, arg) : 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; } var indexOf = Array.prototype.indexOf; 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, indexOf: indexOf, 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": 244, "./id-generater": 177 } ], 182: [ (function(require, module, exports) { var js = require("./js"); var SerializableAttrs = { url: { canUsedInGet: true }, 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 checkUrl(val, className, propName, url) { Array.isArray(url) && url.length > 0 && (url = url[0]); false; val.type = url; } function parseType(val, type, className, propName) { if (Array.isArray(type)) { var isArray; false; if (!(type.length > 0)) return cc.errorID(5508, className, propName); if (cc.RawAsset.isRawAssetType(type[0])) { val.url = type[0]; delete val.type; return; } val.type = type = type[0]; } false; } function postCheckType(val, type, className, propName) { false; } function getBaseClassWherePropertyDefined_DEV(propName, cls) { var res; false; } exports.getFullFormOfProperty = function(options, propname_dev, classname_dev) { var isLiteral = options && options.constructor === Object; if (!isLiteral) { if (Array.isArray(options) && options.length > 0) { var type = options[0]; false; return { default: [], type: options, _short: true }; } if ("function" === (__typeofVal = typeof options, "object" === __typeofVal ? __realTypeOfObj(options) : __typeofVal)) { var type = options; if (!cc.RawAsset.isRawAssetType(type)) { if (!cc.RawAsset.wasRawAssetType(type)) return { default: js.isChildClassOf(type, cc.ValueType) ? new type() : null, type: type, _short: true }; false; } return { default: "", url: type, _short: true }; } return { default: options, _short: true }; } return null; }; exports.preprocessAttrs = function(properties, className, cls, es6) { for (var propName in properties) { var val = properties[propName]; var fullForm = exports.getFullFormOfProperty(val, propName, className); 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); "url" in val && checkUrl(val, className, propName, val.url); "type" in val && postCheckType(val, val.type, className, propName); } } }; false; exports.validateMethodWithProps = function(func, funcName, className, cls, base) { false; if ("function" !== (__typeofVal = typeof func, "object" === __typeofVal ? __realTypeOfObj(func) : __typeofVal) && null !== func) { var overrided; var baseFuc; var subFuc; var correct; false; return false; } false; return true; }; }), { "./CCClass": 161, "./js": 181 } ], 183: [ (function(require, module, exports) { var requiringFrames = []; cc._RF = { push: function(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() { 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() { return requiringFrames[requiringFrames.length - 1]; } }; false; }), {} ], 184: [ (function(require, module, exports) { cc.url = { _rawAssets: "", normalize: function(url) { url && (46 === url.charCodeAt(0) && 47 === url.charCodeAt(1) ? url = url.slice(2) : 47 === url.charCodeAt(0) && (url = url.slice(1))); return url; }, raw: function(url) { false; url = this.normalize(url); if (url.startsWith("resources/")) { var uuid = cc.loader._getResUuid(url.slice(10), cc.Asset, true); if (uuid) return cc.AssetLibrary.getLibUrlNoExt(uuid, true) + cc.path.extname(url); } else cc.errorID(7002, url); return this._rawAssets + url; }, _init: function(assets) { this._rawAssets = cc.path.stripSep(assets) + "/"; } }; module.exports = cc.url; }), {} ], 185: [ (function(require, module, exports) { var js = require("./js"); module.exports = { contains: function(refNode, otherNode) { if ("function" == (__typeofVal = typeof refNode.contains, "object" === __typeofVal ? __realTypeOfObj(refNode.contains) : __typeofVal)) return refNode.contains(otherNode); if ("function" == (__typeofVal = typeof refNode.compareDocumentPosition, "object" === __typeofVal ? __realTypeOfObj(refNode.compareDocumentPosition) : __typeofVal)) 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" === (__typeofVal = typeof window, "object" === __typeofVal ? __realTypeOfObj(window) : __typeofVal) && ("function" === (__typeofVal = typeof Node, "object" === __typeofVal ? __realTypeOfObj(Node) : __typeofVal) ? function(obj) { return obj instanceof Node; } : function(obj) { return obj && "object" === (__typeofVal = typeof obj, "object" === __typeofVal ? __realTypeOfObj(obj) : __typeofVal) && "number" === (__typeofVal = typeof obj.nodeType, "object" === __typeofVal ? __realTypeOfObj(obj.nodeType) : __typeofVal) && "string" === (__typeofVal = typeof obj.nodeName, "object" === __typeofVal ? __realTypeOfObj(obj.nodeName) : __typeofVal); }), callInNextTick: function(callback, p1, p2) { callback && setTimeout((function() { callback(p1, p2); }), 0); } }; false; false; }), { "./js": 181 } ], 186: [ (function(require, module, exports) { require("./platform/js"); require("./value-types"); require("./utils"); require("./platform/CCInputManager"); require("./platform/CCInputExtension"); require("./event"); require("./platform/CCSys"); require("./platform/CCMacro"); require("./load-pipeline"); require("./CCDirector"); require("./renderer"); true; require("./platform/CCView"); require("./platform/CCScreen"); require("./CCScheduler"); require("./event-manager"); }), { "./CCDirector": 28, "./CCScheduler": 33, "./event": 105, "./event-manager": 101, "./load-pipeline": 120, "./platform/CCInputExtension": 164, "./platform/CCInputManager": 165, "./platform/CCMacro": 166, "./platform/CCScreen": 169, "./platform/CCSys": 170, "./platform/CCView": 171, "./platform/js": 181, "./renderer": 202, "./utils": 241, "./value-types": 253 } ], 187: [ (function(require, module, exports) { var ForwardRenderer = function() {}; ForwardRenderer.prototype = { constructor: ForwardRenderer, _reset: function() {}, render: function() {} }; module.exports = ForwardRenderer; }), {} ], 188: [ (function(require, module, exports) { module.exports = { ForwardRenderer: require("./forward-renderer"), RenderComponentHandle: require("./render-component-handle"), _renderers: require("./renderers") }; }), { "./forward-renderer": 187, "./render-component-handle": 189, "./renderers": 192 } ], 189: [ (function(require, module, exports) { require("./renderers"); var RenderComponentHandle = function(device, defaultCamera) { this._device = device; this._camera = defaultCamera; this.parentOpacity = 1; this.parentOpacityDirty = 0; this.worldMatDirty = 0; this.walking = false; }; RenderComponentHandle.prototype = { constructor: RenderComponentHandle, reset: function() { var ctx = this._device._ctx; var canvas = this._device._canvas; var color = cc.Camera.main ? cc.Camera.main.backgroundColor : cc.color(); var rgba = "rgba(" + color.r + ", " + color.g + ", " + color.b + ", " + color.a / 255 + ")"; ctx.fillStyle = rgba; ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.fillRect(0, 0, canvas.width, canvas.height); this._device._stats.drawcalls = 0; }, terminate: function() { this.walking = false; }, _commitComp: function(comp, assembler) { var ctx = this._device._ctx; var cam = this._camera; ctx.setTransform(cam.a, cam.b, cam.c, cam.d, cam.tx, cam.ty); ctx.scale(1, -1); assembler.draw(ctx, comp); } }; module.exports = RenderComponentHandle; }), { "./renderers": 192 } ], 190: [ (function(require, module, exports) { var Helper = require("../../../../graphics/helper"); var Types = require("../../../../graphics/types"); var js = require("../../../../platform/js"); var PointFlags = Types.PointFlags; var LineJoin = Types.LineJoin; var LineCap = Types.LineCap; function Impl() { this.cmds = []; this.style = { strokeStyle: "black", fillStyle: "white", lineCap: "butt", lineJoin: "miter", miterLimit: 10 }; } var _proto = Impl.prototype; js.mixin(_proto, { moveTo: function(x, y) { this.cmds.push([ "moveTo", [ x, y ] ]); }, lineTo: function(x, y) { this.cmds.push([ "lineTo", [ x, y ] ]); }, bezierCurveTo: function(c1x, c1y, c2x, c2y, x, y) { this.cmds.push([ "bezierCurveTo", [ c1x, c1y, c2x, c2y, x, y ] ]); }, quadraticCurveTo: function(cx, cy, x, y) { this.cmds.push([ "quadraticCurveTo", [ cx, cy, x, y ] ]); }, arc: function(cx, cy, r, startAngle, endAngle, counterclockwise) { Helper.arc(this, cx, cy, r, startAngle, endAngle, counterclockwise); }, ellipse: function(cx, cy, rx, ry) { Helper.ellipse(this, cx, cy, rx, ry); }, circle: function(cx, cy, r) { Helper.ellipse(this, cx, cy, r, r); }, rect: function(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(); }, roundRect: function(x, y, w, h, r) { Helper.roundRect(this, x, y, w, h, r); }, clear: function(comp, clean) { this.cmds.length = 0; }, close: function() { this.cmds.push([ "closePath", [] ]); }, stroke: function() { this.cmds.push([ "stroke", [] ]); }, fill: function() { this.cmds.push([ "fill", [] ]); } }); js.set(_proto, "strokeColor", (function(v) { var strokeStyle = "rgba(" + (0 | v.r) + "," + (0 | v.g) + "," + (0 | v.b) + "," + v.a / 255 + ")"; this.cmds.push([ "strokeStyle", strokeStyle ]); this.style.strokeStyle = strokeStyle; })); js.set(_proto, "fillColor", (function(v) { var fillStyle = "rgba(" + (0 | v.r) + "," + (0 | v.g) + "," + (0 | v.b) + "," + v.a / 255 + ")"; this.cmds.push([ "fillStyle", fillStyle ]); this.style.fillStyle = fillStyle; })); js.set(_proto, "lineWidth", (function(v) { this.cmds.push([ "lineWidth", v ]); this.style.lineWidth = v; })); js.set(_proto, "lineCap", (function(v) { var lineCap = "butt"; v === LineCap.BUTT ? lineCap = "butt" : v === LineCap.ROUND ? lineCap = "round" : v === LineCap.SQUARE && (lineCap = "square"); this.cmds.push([ "lineCap", lineCap ]); this.style.lineCap = lineCap; })); js.set(_proto, "lineJoin", (function(v) { var lineJoin = "bevel"; v === LineJoin.BEVEL ? lineJoin = "bevel" : v === LineJoin.ROUND ? lineJoin = "round" : v === LineJoin.MITER && (lineJoin = "miter"); this.cmds.push([ "lineJoin", lineJoin ]); this.style.lineJoin = lineJoin; })); js.set(_proto, "miterLimit", (function(v) { this.cmds.push([ "miterLimit", v ]); this.style.miterLimit = v; })); module.exports = Impl; }), { "../../../../graphics/helper": 108, "../../../../graphics/types": 110, "../../../../platform/js": 181 } ], 191: [ (function(require, module, exports) { var Impl = require("./impl"); module.exports = { createImpl: function() { return new Impl(); }, draw: function(ctx, comp) { var node = comp.node; var matrix = node._worldMatrix; var a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, tx = matrix.m12, ty = matrix.m13; ctx.transform(a, b, c, d, tx, ty); ctx.save(); ctx.globalAlpha = node.opacity / 255; var style = comp._impl.style; ctx.strokeStyle = style.strokeStyle; ctx.fillStyle = style.fillStyle; ctx.lineWidth = style.lineWidth; ctx.lineJoin = style.lineJoin; ctx.miterLimit = style.miterLimit; var endPath = true; var cmds = comp._impl.cmds; for (var i = 0, l = cmds.length; i < l; i++) { var cmd = cmds[i]; var ctxCmd = cmd[0], args = cmd[1]; if ("moveTo" === ctxCmd && endPath) { ctx.beginPath(); endPath = false; } else "fill" !== ctxCmd && "stroke" !== ctxCmd && "fillRect" !== ctxCmd || (endPath = true); "function" === (__typeofVal = typeof ctx[ctxCmd], "object" === __typeofVal ? __realTypeOfObj(ctx[ctxCmd]) : __typeofVal) ? ctx[ctxCmd].apply(ctx, args) : ctx[ctxCmd] = args; } ctx.restore(); return 1; }, stroke: function(comp) { comp._impl.stroke(); }, fill: function(comp) { comp._impl.fill(); } }; }), { "./impl": 190 } ], 192: [ (function(require, module, exports) { var js = require("../../../platform/js"); var Sprite = require("../../../components/CCSprite"); var Label = require("../../../components/CCLabel"); var Mask = require("../../../components/CCMask"); var Graphics = require("../../../graphics/graphics"); var spriteRenderer = require("./sprite"); var labelRenderer = require("./label"); var graphicsRenderer = require("./graphics"); var maskRenderer = require("./mask"); var map = {}; var postMap = {}; function addRenderer(Component, handler, postHandler) { var name = js.getClassName(Component); map[name] = handler; postHandler && (postMap[name] = postHandler); Component._assembler = handler; Component._postAssembler = postHandler; } addRenderer(Sprite, spriteRenderer); addRenderer(Label, labelRenderer); Mask && addRenderer(Mask, maskRenderer.beforeHandler, maskRenderer.afterHandler); Graphics && addRenderer(Graphics, graphicsRenderer); module.exports = { map: map, postMap: postMap, addRenderer: addRenderer }; }), { "../../../components/CCLabel": 70, "../../../components/CCMask": 73, "../../../components/CCSprite": 83, "../../../graphics/graphics": 107, "../../../platform/js": 181, "./graphics": 191, "./label": 194, "./mask": 196, "./sprite": 197 } ], 193: [ (function(require, module, exports) { var bmfontUtils = require("../../../utils/label/bmfont"); var js = require("../../../../platform/js"); var utils = require("../utils"); module.exports = js.addon({ createData: function(comp) { return comp.requestRenderData(); }, appendQuad: function(renderData, texture, rect, rotated, x, y, scale) { var dataOffset = renderData.dataLength; renderData.dataLength += 2; var data = renderData._data; var texw = texture.width, texh = texture.height; var rectWidth = rect.width, rectHeight = rect.height; var l = void 0, b = void 0, r = void 0, t = void 0; if (rotated) { l = rect.x; r = rect.x + rectHeight; b = rect.y; t = rect.y + rectWidth; data[dataOffset].u = l; data[dataOffset].v = t; data[dataOffset + 1].u = l; data[dataOffset + 1].v = b; } else { l = rect.x; r = rect.x + rectWidth; b = rect.y; t = rect.y + rectHeight; data[dataOffset].u = l; data[dataOffset].v = b; data[dataOffset + 1].u = r; data[dataOffset + 1].v = t; } data[dataOffset].x = x; data[dataOffset].y = y - rectHeight * scale; data[dataOffset + 1].x = x + rectWidth * scale; data[dataOffset + 1].y = y; }, draw: function(ctx, comp) { var node = comp.node; var matrix = node._worldMatrix; var a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, tx = matrix.m12, ty = matrix.m13; ctx.transform(a, b, c, d, tx, ty); ctx.scale(1, -1); ctx.globalAlpha = node.opacity / 255; var tex = comp._frame._texture, data = comp._renderData._data; var image = utils.getColorizedImage(tex, node._color); for (var i = 0, l = data.length; i < l; i += 2) { var x = data[i].x; var y = data[i].y; var w = data[i + 1].x - x; var h = data[i + 1].y - y; y = -y - h; var sx = data[i].u; var sy = data[i].v; var sw = data[i + 1].u - sx; var sh = data[i + 1].v - sy; ctx.drawImage(image, sx, sy, sw, sh, x, y, w, h); } return 1; } }, bmfontUtils); }), { "../../../../platform/js": 181, "../../../utils/label/bmfont": 207, "../utils": 201 } ], 194: [ (function(require, module, exports) { var Label = require("../../../../components/CCLabel"); var ttf = require("./ttf"); var bmfont = require("./bmfont"); var canvasPool = { pool: [], get: function() { var data = this.pool.pop(); if (!data) { var canvas = document.createElement("canvas"); var context = canvas.getContext("2d"); data = { canvas: canvas, context: context }; } return data; }, put: function(canvas) { if (this.pool.length >= 32) return; this.pool.push(canvas); } }; Label._canvasPool = canvasPool; module.exports = { getAssembler: function(comp) { var assembler = ttf; comp.font instanceof cc.BitmapFont && (assembler = bmfont); return assembler; }, createData: function(comp) { return comp._assembler.createData(comp); }, draw: function(ctx, comp) { if (!comp._texture) return 0; var assembler = comp._assembler; if (!assembler) return 0; assembler.updateRenderData(comp); return assembler.draw(ctx, comp); } }; }), { "../../../../components/CCLabel": 70, "./bmfont": 193, "./ttf": 195 } ], 195: [ (function(require, module, exports) { var ttfUtils = require("../../../utils/label/ttf"); var js = require("../../../../platform/js"); var utils = require("../utils"); module.exports = js.addon({ createData: function(sprite) { var renderData = sprite.requestRenderData(); renderData.dataLength = 2; return renderData; }, _updateVerts: function(comp) { var renderData = comp._renderData; var node = comp.node, width = node.width, height = node.height, appx = node.anchorX * width, appy = node.anchorY * height; var data = renderData._data; data[0].x = -appx; data[0].y = -appy; data[1].x = width - appx; data[1].y = height - appy; }, _updateTexture: function(comp) { ttfUtils._updateTexture(comp); var texture = comp._frame._texture; utils.dropColorizedImage(texture, comp.node.color); }, draw: function(ctx, comp) { var node = comp.node; var matrix = node._worldMatrix; var a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, tx = matrix.m12, ty = matrix.m13; ctx.transform(a, b, c, d, tx, ty); ctx.scale(1, -1); ctx.globalAlpha = node.opacity / 255; var tex = comp._frame._texture, data = comp._renderData._data; var image = tex.getHtmlElementObj(); var x = data[0].x; var y = data[0].y; var w = data[1].x - x; var h = data[1].y - y; y = -y - h; ctx.drawImage(image, x, y, w, h); return 1; } }, ttfUtils); }), { "../../../../platform/js": 181, "../../../utils/label/ttf": 210, "../utils": 201 } ], 196: [ (function(require, module, exports) { var Mask = require("../../../components/CCMask"); var graphicsHandler = require("./graphics"); var beforeHandler = { updateRenderData: function(comp) {}, draw: function(ctx, mask) { ctx.save(); graphicsHandler.draw(ctx, mask._graphics); ctx.clip(); } }; var afterHandler = { updateRenderData: function(comp) {}, draw: function(ctx, mask) { ctx.restore(); } }; module.exports = { beforeHandler: beforeHandler, afterHandler: afterHandler }; }), { "../../../components/CCMask": 73, "./graphics": 191 } ], 197: [ (function(require, module, exports) { var Sprite = require("../../../../components/CCSprite"); var SpriteType = Sprite.Type; var FillType = Sprite.FillType; var simple = require("./simple"); var sliced = require("./sliced"); var tiled = require("./tiled"); false; module.exports = { getAssembler: function(sprite) { switch (sprite.type) { case SpriteType.SIMPLE: return simple; case SpriteType.SLICED: return sliced; case SpriteType.TILED: return tiled; case SpriteType.FILLED: return sprite._fillType === FillType.RADIAL, null; } }, createData: function(sprite) { return sprite._assembler.createData(sprite); } }; }), { "../../../../components/CCSprite": 83, "../../../webgl/assemblers/sprite/index.js": 222, "./simple": 198, "./sliced": 199, "./tiled": 200 } ], 198: [ (function(require, module, exports) { var utils = require("../utils"); var renderer = { createData: function(sprite) { var renderData = sprite.requestRenderData(); renderData.dataLength = 2; return renderData; }, updateRenderData: function(sprite) { sprite._material || sprite._activateMaterial(); var renderData = sprite._renderData; renderData.uvDirty && this.updateUVs(sprite); renderData.vertDirty && this.updateVerts(sprite); }, updateUVs: function(sprite) { var frame = sprite.spriteFrame; var renderData = sprite._renderData; var data = renderData._data; var rect = frame._rect; var texture = frame._texture; if (frame._rotated) { var l = rect.x; var r = rect.height; var b = rect.y; var t = rect.width; data[0].u = l; data[0].v = t; data[1].u = r; data[1].v = b; } else { var _l = rect.x; var _r = rect.width; var _b = rect.y; var _t = rect.height; data[0].u = _l; data[0].v = _b; data[1].u = _r; data[1].v = _t; } renderData.uvDirty = false; }, updateVerts: function(sprite) { var renderData = sprite._renderData, node = sprite.node, data = renderData._data, cw = node.width, ch = node.height, appx = node.anchorX * cw, appy = node.anchorY * ch, l = void 0, b = void 0, r = void 0, t = void 0; if (sprite.trim) { l = -appx; b = -appy; r = cw; t = ch; } 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; t = ch; } data[0].x = l; data[0].y = b; data[1].x = r; data[1].y = t; renderData.vertDirty = false; }, draw: function(ctx, comp) { var node = comp.node; var matrix = node._worldMatrix; var a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, tx = matrix.m12, ty = matrix.m13; ctx.transform(a, b, c, d, tx, ty); ctx.scale(1, -1); ctx.globalAlpha = node.opacity / 255; var tex = comp._spriteFrame._texture, data = comp._renderData._data; var image = utils.getColorizedImage(tex, node._color); var x = data[0].x; var y = data[0].y; var w = data[1].x; var h = data[1].y; y = -y - h; var sx = data[0].u; var sy = data[0].v; var sw = data[1].u; var sh = data[1].v; ctx.drawImage(image, sx, sy, sw, sh, x, y, w, h); return 1; } }; module.exports = renderer; }), { "../utils": 201 } ], 199: [ (function(require, module, exports) { var utils = require("../utils"); var simple = require("./simple"); var renderer = { createData: function(sprite) { var renderData = sprite.requestRenderData(); renderData.dataLength = 4; return renderData; }, updateRenderData: simple.updateRenderData, updateUVs: function(sprite) { var frame = sprite.spriteFrame; var renderData = sprite._renderData; var rect = frame._rect; var texture = frame._texture; var leftWidth = frame.insetLeft; var rightWidth = frame.insetRight; var centerWidth = rect.width - leftWidth - rightWidth; var topHeight = frame.insetTop; var bottomHeight = frame.insetBottom; var centerHeight = rect.height - topHeight - bottomHeight; var data = renderData._data; if (frame._rotated) { data[0].u = rect.x; data[1].u = bottomHeight + rect.x; data[2].u = bottomHeight + centerHeight + rect.x; data[3].u = rect.x + rect.height; data[3].v = rect.y; data[2].v = leftWidth + rect.y; data[1].v = leftWidth + centerWidth + rect.y; data[0].v = rect.y + rect.width; } else { data[0].u = rect.x; data[1].u = leftWidth + rect.x; data[2].u = leftWidth + centerWidth + rect.x; data[3].u = rect.x + rect.width; data[3].v = rect.y; data[2].v = topHeight + rect.y; data[1].v = topHeight + centerHeight + rect.y; data[0].v = rect.y + rect.height; } renderData.uvDirty = false; }, updateVerts: function(sprite) { var renderData = sprite._renderData, data = renderData._data, node = sprite.node, width = node.width, height = node.height, appx = node.anchorX * width, appy = node.anchorY * height; var frame = sprite.spriteFrame; var rect = frame._rect; 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; data[0].x = -appx; data[0].y = -appy; data[1].x = leftWidth * xScale - appx; data[1].y = bottomHeight * yScale - appy; data[2].x = data[1].x + sizableWidth; data[2].y = data[1].y + sizableHeight; data[3].x = width - appx; data[3].y = height - appy; renderData.vertDirty = false; }, draw: function(ctx, comp) { var node = comp.node; var matrix = node._worldMatrix; var a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, tx = matrix.m12, ty = matrix.m13; ctx.transform(a, b, c, d, tx, ty); ctx.scale(1, -1); ctx.globalAlpha = node.opacity / 255; var tex = comp._spriteFrame._texture, data = comp._renderData._data; var image = utils.getColorizedImage(tex, node._color); var drawCall = 0; var off = void 0, ld = void 0, rd = void 0, td = void 0, bd = void 0, x = void 0, y = void 0, w = void 0, h = void 0, sx = void 0, sy = void 0, sw = void 0, sh = void 0; for (var r = 0; r < 3; ++r) { bd = data[r]; td = data[r + 1]; for (var _c = 0; _c < 3; ++_c) { ld = data[_c]; rd = data[_c + 1]; x = ld.x; y = bd.y; w = rd.x - x; h = td.y - y; y = -y - h; sx = ld.u; sy = td.v; sw = rd.u - sx; sh = bd.v - sy; if (sw > 0 && sh > 0 && w > 0 && h > 0) { ctx.drawImage(image, sx, sy, sw, sh, x, y, w, h); drawCall++; } } } return drawCall; } }; module.exports = renderer; }), { "../utils": 201, "./simple": 198 } ], 200: [ (function(require, module, exports) { var utils = require("../utils"); var simple = require("./simple"); var renderer = { createData: function(sprite) { var renderData = sprite.requestRenderData(); return renderData; }, updateRenderData: function(sprite) { sprite._material || sprite._activateMaterial(); }, draw: function(ctx, sprite) { var node = sprite.node; var matrix = node._worldMatrix; var a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, tx = matrix.m12, ty = matrix.m13; ctx.transform(a, b, c, d, tx, ty); ctx.scale(1, -1); ctx.globalAlpha = node.opacity / 255; var frame = sprite.spriteFrame; var rect = frame._rect; var tex = frame._texture; var sx = rect.x; var sy = rect.y; var sw = frame._rotated ? rect.height : rect.width; var sh = frame._rotated ? rect.width : rect.height; var image = utils.getFrameCache(tex, node._color, sx, sy, sw, sh); var w = node.width, h = node.height, x = -node.anchorX * w, y = -node.anchorY * h; y = -y - h; ctx.translate(x, y); ctx.fillStyle = ctx.createPattern(image, "repeat"); ctx.fillRect(0, 0, w, h); return 1; } }; module.exports = renderer; }), { "../utils": 201, "./simple": 198 } ], 201: [ (function(require, module, exports) { var WHITE = 16777215; var MAX_CANVAS_COUNT = 32; function colorizedFrame(canvas, texture, color, sx, sy, sw, sh) { var image = texture._image; var ctx = canvas.getContext("2d"); canvas.width = sw; canvas.height = sh; ctx.globalCompositeOperation = "source-over"; ctx.fillStyle = "rgb(" + color.r + "," + color.g + "," + color.b + ")"; ctx.fillRect(0, 0, sw, sh); ctx.globalCompositeOperation = "multiply"; ctx.drawImage(image, sx, sy, sw, sh, 0, 0, sw, sh); ctx.globalCompositeOperation = "destination-atop"; ctx.drawImage(image, sx, sy, sw, sh, 0, 0, sw, sh); return canvas; } var canvasMgr = { canvasMap: {}, canvasUsed: {}, canvasPool: [], checking: false, check: function() { var exist = false; for (var key in this.canvasUsed) { exist = true; if (this.canvasUsed[key]) this.canvasUsed[key] = false; else { var canvas = this.canvasMap[key]; canvas.width = 0; canvas.height = 0; this.canvasPool.length < 32 && this.canvasPool.push(canvas); delete this.canvasMap[key]; delete this.canvasUsed[key]; } } if (!exist) { cc.director.off(cc.Director.EVENT_AFTER_DRAW, this.check, this); this.checking = false; } }, startCheck: function() { cc.director.on(cc.Director.EVENT_AFTER_DRAW, this.check, this); this.checking = true; }, getCanvas: function(key) { this.canvasUsed[key] = true; return this.canvasMap[key]; }, cacheCanvas: function(canvas, key) { this.canvasMap[key] = canvas; this.canvasUsed[key] = true; this.checking || this.startCheck(); }, dropImage: function(key) { this.canvasMap[key] && delete this.canvasMap[key]; } }; module.exports = { getColorizedImage: function(texture, color) { if (!texture) return null; if (0 === texture.width || 0 === texture.height) return texture._image; var cval = 16777215 & color._val; if (cval === WHITE) return texture._image; var key = texture.url + cval; var cache = canvasMgr.getCanvas(key); if (!cache) { cache = canvasMgr.canvasPool.pop() || document.createElement("canvas"); colorizedFrame(cache, texture, color, 0, 0, texture.width, texture.height); canvasMgr.cacheCanvas(cache, key); } return cache; }, getFrameCache: function(texture, color, sx, sy, sw, sh) { if (!texture || !texture.url || sx < 0 || sy < 0 || sw <= 0 || sh <= 0) return null; var key = texture.url; var generate = false; var cval = 16777215 & color._val; if (cval !== WHITE) { key += cval; generate = true; } if (0 !== sx || 0 !== sy && sw !== texture.width && sh !== texture.height) { key += "_" + sx + "_" + sy + "_" + sw + "_" + sh; generate = true; } if (!generate) return texture._image; var cache = canvasMgr.getCanvas(key); if (!cache) { cache = canvasMgr.canvasPool.pop() || document.createElement("canvas"); colorizedFrame(cache, texture, color, sx, sy, sw, sh); canvasMgr.cacheCanvas(cache, key); } return cache; }, dropColorizedImage: function(texture, color) { var key = texture.url + (16777215 & color._val); canvasMgr.dropImage(key); } }; }), {} ], 202: [ (function(require, module, exports) { var renderEngine = require("./render-engine"); var RenderFlow = require("./render-flow"); var vec3 = cc.vmath.vec3; var _pos = vec3.create(); function _initBuiltins(device) { var defaultTexture = new renderEngine.Texture2D(device, { images: [], width: 128, height: 128, wrapS: renderEngine.gfx.WRAP_REPEAT, wrapT: renderEngine.gfx.WRAP_REPEAT, format: renderEngine.gfx.TEXTURE_FMT_RGB8, mipmap: false }); return { defaultTexture: defaultTexture, programTemplates: renderEngine.shaders.templates, programChunks: renderEngine.shaders.chunks }; } cc.renderer = module.exports = { renderEngine: renderEngine, Texture2D: null, canvas: null, device: null, scene: null, drawCalls: 0, _handle: null, _cameraNode: null, _camera: null, _forward: null, initWebGL: function(canvas, opts) { require("./webgl/assemblers"); var ModelBatcher = require("./webgl/model-batcher"); this.Texture2D = renderEngine.Texture2D; this.canvas = canvas; true, false; this.device = new renderEngine.Device(canvas, opts); this.scene = new renderEngine.Scene(); this._handle = new ModelBatcher(this.device, this.scene); RenderFlow.init(this._handle); var view; false; var builtins = _initBuiltins(this.device); this._forward = new renderEngine.ForwardRenderer(this.device, builtins); }, initCanvas: function(canvas) { var canvasRenderer = require("./canvas"); renderEngine.Texture2D = renderEngine.canvas.Texture2D; renderEngine.Device = renderEngine.canvas.Device; this.Texture2D = renderEngine.Texture2D; this.canvas = canvas; this.device = new renderEngine.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); RenderFlow.init(this._handle); this._forward = new canvasRenderer.ForwardRenderer(); }, updateCameraViewport: function() { if (true, cc.director) { var ecScene = cc.director.getScene(); ecScene.scaleX = ecScene.scaleY = 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; } else { var canvas; var scaleX; var scaleY; var node; false; } }, render: function(ecScene) { this.device._stats.drawcalls = 0; if (ecScene) { RenderFlow.visit(ecScene); this._forward.render(this.scene); this.drawCalls = this.device._stats.drawcalls; } }, clear: function() { this._handle.reset(); this._forward._reset(); } }; }), { "./canvas": 188, "./render-engine": 203, "./render-flow": 204, "./webgl/assemblers": 214, "./webgl/model-batcher": 229 } ], 203: [ (function(require, module, exports) { "use strict"; var _d2r = Math.PI / 180; var _r2d = 180 / Math.PI; var EPSILON = 1e-6; 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; function randomRange(min, max) { return Math.random() * (max - min) + min; } function randomRangeInt(min, max) { return Math.floor(randomRange(min, max)); } function nextPow2(val) { --val; val |= val >> 1; val |= val >> 2; val |= val >> 4; val |= val >> 8; val |= val >> 16; ++val; return val; } var INT_BITS = 32; var INT_MAX = 2147483647; var INT_MIN = -1 << INT_BITS - 1; function sign(v) { return (v > 0) - (v < 0); } function abs(v) { var mask = v >> INT_BITS - 1; return (v ^ mask) - mask; } function min(x, y) { return y ^ (x ^ y) & -(x < y); } function max(x, y) { return x ^ (x ^ y) & -(x < y); } function isPow2(v) { return !(v & v - 1) && !!v; } 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 log10(v) { return v >= 1e9 ? 9 : v >= 1e8 ? 8 : v >= 1e7 ? 7 : v >= 1e6 ? 6 : v >= 1e5 ? 5 : v >= 1e4 ? 4 : v >= 1e3 ? 3 : v >= 100 ? 2 : v >= 10 ? 1 : 0; } function popCount(v) { v -= v >>> 1 & 1431655765; v = (858993459 & v) + (v >>> 2 & 858993459); return 16843009 * (v + (v >>> 4) & 252645135) >>> 24; } function countTrailingZeros(v) { var c = 32; v &= -v; v && c--; 65535 & v && (c -= 16); 16711935 & v && (c -= 8); 252645135 & v && (c -= 4); 858993459 & v && (c -= 2); 1431655765 & v && (c -= 1); return c; } function nextPow2$1(v) { v += 0 === v; --v; v |= v >>> 1; v |= v >>> 2; v |= v >>> 4; v |= v >>> 8; v |= v >>> 16; return v + 1; } function prevPow2(v) { v |= v >>> 1; v |= v >>> 2; v |= v >>> 4; v |= v >>> 8; v |= v >>> 16; return v - (v >>> 1); } function parity(v) { v ^= v >>> 16; v ^= v >>> 8; v ^= v >>> 4; v &= 15; return 27030 >>> v & 1; } var REVERSE_TABLE = new Array(256); (function(tab) { for (var i = 0; i < 256; ++i) { var v = i, r = i, s = 7; for (v >>>= 1; v; v >>>= 1) { r <<= 1; r |= 1 & v; --s; } tab[i] = r << s & 255; } })(REVERSE_TABLE); function reverse(v) { return REVERSE_TABLE[255 & v] << 24 | REVERSE_TABLE[v >>> 8 & 255] << 16 | REVERSE_TABLE[v >>> 16 & 255] << 8 | REVERSE_TABLE[v >>> 24 & 255]; } function interleave2(x, y) { x &= 65535; x = 16711935 & (x | x << 8); x = 252645135 & (x | x << 4); x = 858993459 & (x | x << 2); x = 1431655765 & (x | x << 1); y &= 65535; 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 deinterleave2(v, n) { v = v >>> n & 1431655765; v = 858993459 & (v | v >>> 1); v = 252645135 & (v | v >>> 2); v = 16711935 & (v | v >>> 4); v = 65535 & (v | v >>> 16); return v << 16 >> 16; } function interleave3(x, y, z) { x &= 1023; x = 4278190335 & (x | x << 16); x = 251719695 & (x | x << 8); x = 3272356035 & (x | x << 4); x = 1227133513 & (x | x << 2); y &= 1023; y = 4278190335 & (y | y << 16); y = 251719695 & (y | y << 8); y = 3272356035 & (y | y << 4); y = 1227133513 & (y | y << 2); x |= y << 1; z &= 1023; z = 4278190335 & (z | z << 16); z = 251719695 & (z | z << 8); z = 3272356035 & (z | z << 4); z = 1227133513 & (z | z << 2); return x | z << 2; } function deinterleave3(v, n) { v = v >>> n & 1227133513; v = 3272356035 & (v | v >>> 2); v = 251719695 & (v | v >>> 4); v = 4278190335 & (v | v >>> 8); v = 1023 & (v | v >>> 16); return v << 22 >> 22; } function nextCombination(v) { var t = v | v - 1; return t + 1 | (~t & -~t) - 1 >>> countTrailingZeros(v) + 1; } var bits_ = Object.freeze({ INT_BITS: INT_BITS, INT_MAX: INT_MAX, INT_MIN: INT_MIN, sign: sign, abs: abs, min: min, max: max, isPow2: isPow2, log2: log2, log10: log10, popCount: popCount, countTrailingZeros: countTrailingZeros, nextPow2: nextPow2$1, prevPow2: prevPow2, parity: parity, reverse: reverse, interleave2: interleave2, deinterleave2: deinterleave2, interleave3: interleave3, deinterleave3: deinterleave3, nextCombination: nextCombination }); var _tmp = new Array(2); var _vec2 = function _vec2(x, y) { this.x = x; this.y = y; }; _vec2.prototype.toJSON = function toJSON() { _tmp[0] = this.x; _tmp[1] = this.y; return _tmp; }; var vec2 = {}; vec2.create = function() { return new _vec2(0, 0); }; vec2.new = function(x, y) { return new _vec2(x, y); }; vec2.clone = function(a) { return new _vec2(a.x, a.y); }; vec2.copy = function(out, a) { out.x = a.x; out.y = a.y; return out; }; vec2.set = function(out, x, y) { out.x = x; out.y = y; return out; }; vec2.add = function(out, a, b) { out.x = a.x + b.x; out.y = a.y + b.y; return out; }; vec2.subtract = function(out, a, b) { out.x = a.x - b.x; out.y = a.y - b.y; return out; }; vec2.sub = vec2.subtract; vec2.multiply = function(out, a, b) { out.x = a.x * b.x; out.y = a.y * b.y; return out; }; vec2.mul = vec2.multiply; vec2.divide = function(out, a, b) { out.x = a.x / b.x; out.y = a.y / b.y; return out; }; vec2.div = vec2.divide; vec2.ceil = function(out, a) { out.x = Math.ceil(a.x); out.y = Math.ceil(a.y); return out; }; vec2.floor = function(out, a) { out.x = Math.floor(a.x); out.y = Math.floor(a.y); return out; }; vec2.min = function(out, a, b) { out.x = Math.min(a.x, b.x); out.y = Math.min(a.y, b.y); return out; }; vec2.max = function(out, a, b) { out.x = Math.max(a.x, b.x); out.y = Math.max(a.y, b.y); return out; }; vec2.round = function(out, a) { out.x = Math.round(a.x); out.y = Math.round(a.y); return out; }; vec2.scale = function(out, a, b) { out.x = a.x * b; out.y = a.y * b; return out; }; vec2.scaleAndAdd = function(out, a, b, scale) { out.x = a.x + b.x * scale; out.y = a.y + b.y * scale; return out; }; vec2.distance = function(a, b) { var x = b.x - a.x, y = b.y - a.y; return Math.sqrt(x * x + y * y); }; vec2.dist = vec2.distance; vec2.squaredDistance = function(a, b) { var x = b.x - a.x, y = b.y - a.y; return x * x + y * y; }; vec2.sqrDist = vec2.squaredDistance; vec2.length = function(a) { var x = a.x, y = a.y; return Math.sqrt(x * x + y * y); }; vec2.len = vec2.length; vec2.squaredLength = function(a) { var x = a.x, y = a.y; return x * x + y * y; }; vec2.sqrLen = vec2.squaredLength; vec2.negate = function(out, a) { out.x = -a.x; out.y = -a.y; return out; }; vec2.inverse = function(out, a) { out.x = 1 / a.x; out.y = 1 / a.y; return out; }; vec2.inverseSafe = function(out, a) { var x = a.x, y = a.y; Math.abs(x) < EPSILON ? out.x = 0 : out.x = 1 / x; Math.abs(y) < EPSILON ? out.y = 0 : out.y = 1 / a.y; return out; }; vec2.normalize = function(out, a) { var x = a.x, y = a.y; var len = x * x + y * y; if (len > 0) { len = 1 / Math.sqrt(len); out.x = a.x * len; out.y = a.y * len; } return out; }; vec2.dot = function(a, b) { return a.x * b.x + a.y * b.y; }; vec2.cross = function(out, a, b) { var z = a.x * b.y - a.y * b.x; out.x = out.y = 0; out.z = z; return out; }; vec2.lerp = function(out, a, b, t) { var ax = a.x, ay = a.y; out.x = ax + t * (b.x - ax); out.y = ay + t * (b.y - ay); return out; }; vec2.random = function(out, scale) { scale = scale || 1; var r = 2 * random() * Math.PI; out.x = Math.cos(r) * scale; out.y = Math.sin(r) * scale; return out; }; vec2.transformMat2 = function(out, a, m) { var x = a.x, y = a.y; out.x = m.m00 * x + m.m02 * y; out.y = m.m01 * x + m.m03 * y; return out; }; vec2.transformMat23 = function(out, a, m) { var x = a.x, y = a.y; out.x = m.m00 * x + m.m02 * y + m.m04; out.y = m.m01 * x + m.m03 * y + m.m05; return out; }; vec2.transformMat3 = function(out, a, m) { var x = a.x, y = a.y; out.x = m.m00 * x + m.m03 * y + m.m06; out.y = m.m01 * x + m.m04 * y + m.m07; return out; }; vec2.transformMat4 = function(out, a, m) { var x = a.x, y = a.y; out.x = m.m00 * x + m.m04 * y + m.m12; out.y = m.m01 * x + m.m05 * y + m.m13; return out; }; vec2.forEach = (function() { var vec = vec2.create(); return function(a, stride, offset, count, fn, arg) { var i, l; stride || (stride = 2); offset || (offset = 0); l = count ? Math.min(count * stride + offset, a.length) : a.length; for (i = offset; i < l; i += stride) { vec.x = a[i]; vec.y = a[i + 1]; fn(vec, vec, arg); a[i] = vec.x; a[i + 1] = vec.y; } return a; }; })(); vec2.str = function(a) { return "vec2(" + a.x + ", " + a.y + ")"; }; vec2.array = function(out, v) { out[0] = v.x; out[1] = v.y; return out; }; vec2.exactEquals = function(a, b) { return a.x === b.x && a.y === b.y; }; vec2.equals = function(a, b) { var a0 = a.x, a1 = a.y; var b0 = b.x, b1 = b.y; 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)); }; var _tmp$1 = new Array(3); var _vec3 = function _vec3(x, y, z) { this.x = x; this.y = y; this.z = z; }; _vec3.prototype.toJSON = function toJSON() { _tmp$1[0] = this.x; _tmp$1[1] = this.y; _tmp$1[2] = this.z; return _tmp$1; }; var vec3 = {}; vec3.create = function() { return new _vec3(0, 0, 0); }; vec3.new = function(x, y, z) { return new _vec3(x, y, z); }; vec3.clone = function(a) { return new _vec3(a.x, a.y, a.z); }; vec3.copy = function(out, a) { out.x = a.x; out.y = a.y; out.z = a.z; return out; }; vec3.set = function(out, x, y, z) { out.x = x; out.y = y; out.z = z; return out; }; vec3.add = function(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(out, a, b) { out.x = a.x - b.x; out.y = a.y - b.y; out.z = a.z - b.z; return out; }; vec3.sub = vec3.subtract; vec3.multiply = function(out, a, b) { out.x = a.x * b.x; out.y = a.y * b.y; out.z = a.z * b.z; return out; }; vec3.mul = vec3.multiply; vec3.divide = function(out, a, b) { out.x = a.x / b.x; out.y = a.y / b.y; out.z = a.z / b.z; return out; }; vec3.div = vec3.divide; vec3.ceil = function(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(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(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(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(out, a) { out.x = Math.round(a.x); out.y = Math.round(a.y); out.z = Math.round(a.z); return out; }; vec3.scale = function(out, a, b) { out.x = a.x * b; out.y = a.y * b; out.z = a.z * b; return out; }; vec3.scaleAndAdd = function(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(a, b) { var 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.dist = vec3.distance; vec3.squaredDistance = function(a, b) { var x = b.x - a.x, y = b.y - a.y, z = b.z - a.z; return x * x + y * y + z * z; }; vec3.sqrDist = vec3.squaredDistance; vec3.length = function(a) { var x = a.x, y = a.y, z = a.z; return Math.sqrt(x * x + y * y + z * z); }; vec3.len = vec3.length; vec3.squaredLength = function(a) { var x = a.x, y = a.y, z = a.z; return x * x + y * y + z * z; }; vec3.sqrLen = vec3.squaredLength; vec3.negate = function(out, a) { out.x = -a.x; out.y = -a.y; out.z = -a.z; return out; }; vec3.inverse = function(out, a) { out.x = 1 / a.x; out.y = 1 / a.y; out.z = 1 / a.z; return out; }; vec3.inverseSafe = function(out, a) { var x = a.x, y = a.y, z = a.z; Math.abs(x) < EPSILON ? out.x = 0 : out.x = 1 / x; Math.abs(y) < EPSILON ? out.y = 0 : out.y = 1 / y; Math.abs(z) < EPSILON ? out.z = 0 : out.z = 1 / z; return out; }; vec3.normalize = function(out, a) { var 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(a, b) { return a.x * b.x + a.y * b.y + a.z * b.z; }; vec3.cross = function(out, a, b) { var ax = a.x, ay = a.y, az = a.z, 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(out, a, b, t) { var ax = a.x, ay = a.y, az = a.z; out.x = ax + t * (b.x - ax); out.y = ay + t * (b.y - ay); out.z = az + t * (b.z - az); return out; }; vec3.hermite = function(out, a, b, c, d, t) { var factorTimes2 = t * t, factor1 = factorTimes2 * (2 * t - 3) + 1, factor2 = factorTimes2 * (t - 2) + t, factor3 = factorTimes2 * (t - 1), factor4 = factorTimes2 * (3 - 2 * t); out.x = a.x * factor1 + b.x * factor2 + c.x * factor3 + d.x * factor4; out.y = a.y * factor1 + b.y * factor2 + c.y * factor3 + d.y * factor4; out.z = a.z * factor1 + b.z * factor2 + c.z * factor3 + d.z * factor4; return out; }; vec3.bezier = function(out, a, b, c, d, t) { var inverseFactor = 1 - t, inverseFactorTimesTwo = inverseFactor * inverseFactor, factorTimes2 = t * t, factor1 = inverseFactorTimesTwo * inverseFactor, factor2 = 3 * t * inverseFactorTimesTwo, factor3 = 3 * factorTimes2 * inverseFactor, factor4 = factorTimes2 * t; out.x = a.x * factor1 + b.x * factor2 + c.x * factor3 + d.x * factor4; out.y = a.y * factor1 + b.y * factor2 + c.y * factor3 + d.y * factor4; out.z = a.z * factor1 + b.z * factor2 + c.z * factor3 + d.z * factor4; return out; }; vec3.random = function(out, scale) { scale = scale || 1; var r = 2 * random() * Math.PI; var z = 2 * random() - 1; var zScale = Math.sqrt(1 - z * z) * scale; out.x = Math.cos(r) * zScale; out.y = Math.sin(r) * zScale; out.z = z * scale; return out; }; vec3.transformMat4 = function(out, a, m) { var x = a.x, y = a.y, z = a.z, w = m.m03 * x + m.m07 * y + m.m11 * z + m.m15; w = w || 1; out.x = (m.m00 * x + m.m04 * y + m.m08 * z + m.m12) / w; out.y = (m.m01 * x + m.m05 * y + m.m09 * z + m.m13) / w; out.z = (m.m02 * x + m.m06 * y + m.m10 * z + m.m14) / w; return out; }; vec3.transformMat3 = function(out, a, m) { var x = a.x, y = a.y, z = a.z; out.x = x * m.m00 + y * m.m03 + z * m.m06; out.y = x * m.m01 + y * m.m04 + z * m.m07; out.z = x * m.m02 + y * m.m05 + z * m.m08; return out; }; vec3.transformQuat = function(out, a, q) { var x = a.x, y = a.y, z = a.z; var qx = q.x, qy = q.y, qz = q.z, qw = q.w; var ix = qw * x + qy * z - qz * y; var iy = qw * y + qz * x - qx * z; var iz = qw * z + qx * y - qy * x; var iw = -qx * x - qy * y - qz * z; out.x = ix * qw + iw * -qx + iy * -qz - iz * -qy; out.y = iy * qw + iw * -qy + iz * -qx - ix * -qz; out.z = iz * qw + iw * -qz + ix * -qy - iy * -qx; return out; }; vec3.rotateX = function(out, a, b, c) { var p = [], r = []; p.x = a.x - b.x; p.y = a.y - b.y; p.z = a.z - b.z; r.x = p.x; r.y = p.y * Math.cos(c) - p.z * Math.sin(c); r.z = p.y * Math.sin(c) + p.z * Math.cos(c); out.x = r.x + b.x; out.y = r.y + b.y; out.z = r.z + b.z; return out; }; vec3.rotateY = function(out, a, b, c) { var p = [], r = []; p.x = a.x - b.x; p.y = a.y - b.y; p.z = a.z - b.z; r.x = p.z * Math.sin(c) + p.x * Math.cos(c); r.y = p.y; r.z = p.z * Math.cos(c) - p.x * Math.sin(c); out.x = r.x + b.x; out.y = r.y + b.y; out.z = r.z + b.z; return out; }; vec3.rotateZ = function(out, a, b, c) { var p = [], r = []; p.x = a.x - b.x; p.y = a.y - b.y; p.z = a.z - b.z; r.x = p.x * Math.cos(c) - p.y * Math.sin(c); r.y = p.x * Math.sin(c) + p.y * Math.cos(c); r.z = p.z; out.x = r.x + b.x; out.y = r.y + b.y; out.z = r.z + b.z; return out; }; vec3.forEach = (function() { var vec = vec3.create(); return function(a, stride, offset, count, fn, arg) { var i, l; stride || (stride = 3); offset || (offset = 0); l = count ? Math.min(count * stride + offset, a.length) : a.length; for (i = offset; i < l; i += stride) { vec.x = a[i]; vec.y = a[i + 1]; vec.z = a[i + 2]; fn(vec, vec, arg); a[i] = vec.x; a[i + 1] = vec.y; a[i + 2] = vec.z; } return a; }; })(); vec3.angle = (function() { var tempA = vec3.create(); var tempB = vec3.create(); return function(a, b) { vec3.copy(tempA, a); vec3.copy(tempB, b); vec3.normalize(tempA, tempA); vec3.normalize(tempB, tempB); var cosine = vec3.dot(tempA, tempB); if (cosine > 1) return 0; if (cosine < -1) return Math.PI; return Math.acos(cosine); }; })(); vec3.str = function(a) { return "vec3(" + a.x + ", " + a.y + ", " + a.z + ")"; }; vec3.array = function(out, v) { out[0] = v.x; out[1] = v.y; out[2] = v.z; return out; }; vec3.exactEquals = function(a, b) { return a.x === b.x && a.y === b.y && a.z === b.z; }; vec3.equals = function(a, b) { 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)); }; var _tmp$2 = new Array(4); var _vec4 = function _vec4(x, y, z, w) { this.x = x; this.y = y; this.z = z; this.w = w; }; _vec4.prototype.toJSON = function toJSON() { _tmp$2[0] = this.x; _tmp$2[1] = this.y; _tmp$2[2] = this.z; _tmp$2[3] = this.w; return _tmp$2; }; var vec4 = {}; vec4.create = function() { return new _vec4(0, 0, 0, 0); }; vec4.new = function(x, y, z, w) { return new _vec4(x, y, z, w); }; vec4.clone = function(a) { return new _vec4(a.x, a.y, a.z, a.w); }; vec4.copy = function(out, a) { out.x = a.x; out.y = a.y; out.z = a.z; out.w = a.w; return out; }; vec4.set = function(out, x, y, z, w) { out.x = x; out.y = y; out.z = z; out.w = w; return out; }; vec4.add = function(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(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.sub = vec4.subtract; vec4.multiply = function(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.mul = vec4.multiply; vec4.divide = function(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.div = vec4.divide; vec4.ceil = function(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(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(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(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(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.scale = function(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(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(a, b) { var x = b.x - a.x, y = b.y - a.y, z = b.z - a.z, w = b.w - a.w; return Math.sqrt(x * x + y * y + z * z + w * w); }; vec4.dist = vec4.distance; vec4.squaredDistance = function(a, b) { var x = b.x - a.x, y = b.y - a.y, z = b.z - a.z, w = b.w - a.w; return x * x + y * y + z * z + w * w; }; vec4.sqrDist = vec4.squaredDistance; vec4.length = function(a) { var x = a.x, y = a.y, z = a.z, w = a.w; return Math.sqrt(x * x + y * y + z * z + w * w); }; vec4.len = vec4.length; vec4.squaredLength = function(a) { var x = a.x, y = a.y, z = a.z, w = a.w; return x * x + y * y + z * z + w * w; }; vec4.sqrLen = vec4.squaredLength; vec4.negate = function(out, a) { out.x = -a.x; out.y = -a.y; out.z = -a.z; out.w = -a.w; return out; }; vec4.inverse = function(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(out, a) { var x = a.x, y = a.y, z = a.z, w = a.w; Math.abs(x) < EPSILON ? out.x = 0 : out.x = 1 / x; Math.abs(y) < EPSILON ? out.y = 0 : out.y = 1 / y; Math.abs(z) < EPSILON ? out.z = 0 : out.z = 1 / z; Math.abs(w) < EPSILON ? out.w = 0 : out.w = 1 / w; return out; }; vec4.normalize = function(out, a) { var 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(a, b) { return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; }; vec4.lerp = function(out, a, b, t) { var ax = a.x, ay = a.y, az = a.z, aw = a.w; out.x = ax + t * (b.x - ax); out.y = ay + t * (b.y - ay); out.z = az + t * (b.z - az); out.w = aw + t * (b.w - aw); return out; }; vec4.random = function(out, scale) { scale = scale || 1; out.x = random(); out.y = random(); out.z = random(); out.w = random(); vec4.normalize(out, out); vec4.scale(out, out, scale); return out; }; vec4.transformMat4 = function(out, a, m) { var x = a.x, y = a.y, z = a.z, w = a.w; out.x = m.m00 * x + m.m04 * y + m.m08 * z + m.m12 * w; out.y = m.m01 * x + m.m05 * y + m.m09 * z + m.m13 * w; out.z = m.m02 * x + m.m06 * y + m.m10 * z + m.m14 * w; out.w = m.m03 * x + m.m07 * y + m.m11 * z + m.m15 * w; return out; }; vec4.transformQuat = function(out, a, q) { var x = a.x, y = a.y, z = a.z; var qx = q.x, qy = q.y, qz = q.z, qw = q.w; var ix = qw * x + qy * z - qz * y; var iy = qw * y + qz * x - qx * z; var iz = qw * z + qx * y - qy * x; var iw = -qx * x - qy * y - qz * z; out.x = ix * qw + iw * -qx + iy * -qz - iz * -qy; out.y = iy * qw + iw * -qy + iz * -qx - ix * -qz; out.z = iz * qw + iw * -qz + ix * -qy - iy * -qx; out.w = a.w; return out; }; vec4.forEach = (function() { var vec = vec4.create(); return function(a, stride, offset, count, fn, arg) { var i, l; stride || (stride = 4); offset || (offset = 0); l = count ? Math.min(count * stride + offset, a.length) : a.length; for (i = offset; i < l; i += stride) { vec.x = a[i]; vec.y = a[i + 1]; vec.z = a[i + 2]; vec.w = a[i + 3]; fn(vec, vec, arg); a[i] = vec.x; a[i + 1] = vec.y; a[i + 2] = vec.z; a[i + 3] = vec.w; } return a; }; })(); vec4.str = function(a) { return "vec4(" + a.x + ", " + a.y + ", " + a.z + ", " + a.w + ")"; }; vec4.array = function(out, v) { out[0] = v.x; out[1] = v.y; out[2] = v.z; out[3] = v.w; return out; }; vec4.exactEquals = function(a, b) { return a.x === b.x && a.y === b.y && a.z === b.z && a.w === b.w; }; vec4.equals = function(a, b) { var a0 = a.x, a1 = a.y, a2 = a.z, a3 = a.w; var b0 = b.x, b1 = b.y, b2 = b.z, b3 = b.w; 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)) && Math.abs(a3 - b3) <= EPSILON * Math.max(1, Math.abs(a3), Math.abs(b3)); }; var _tmp$3 = new Array(9); var _mat3 = function _mat3(m00, m01, m02, m03, m04, m05, m06, m07, m08) { this.m00 = m00; this.m01 = m01; this.m02 = m02; this.m03 = m03; this.m04 = m04; this.m05 = m05; this.m06 = m06; this.m07 = m07; this.m08 = m08; }; _mat3.prototype.toJSON = function toJSON() { _tmp$3[0] = this.m00; _tmp$3[1] = this.m01; _tmp$3[2] = this.m02; _tmp$3[3] = this.m03; _tmp$3[4] = this.m04; _tmp$3[5] = this.m05; _tmp$3[6] = this.m06; _tmp$3[7] = this.m07; _tmp$3[8] = this.m08; return _tmp$3; }; var mat3 = {}; mat3.create = function() { return new _mat3(1, 0, 0, 0, 1, 0, 0, 0, 1); }; mat3.new = function(m00, m01, m02, m10, m11, m12, m20, m21, m22) { return new _mat3(m00, m01, m02, m10, m11, m12, m20, m21, m22); }; mat3.clone = function(a) { return new _mat3(a.m00, a.m01, a.m02, a.m03, a.m04, a.m05, a.m06, a.m07, a.m08); }; mat3.copy = function(out, a) { out.m00 = a.m00; out.m01 = a.m01; out.m02 = a.m02; out.m03 = a.m03; out.m04 = a.m04; out.m05 = a.m05; out.m06 = a.m06; out.m07 = a.m07; out.m08 = a.m08; return out; }; mat3.set = function(out, m00, m01, m02, m10, m11, m12, m20, m21, m22) { out.m00 = m00; out.m01 = m01; out.m02 = m02; out.m03 = m10; out.m04 = m11; out.m05 = m12; out.m06 = m20; out.m07 = m21; out.m08 = m22; return out; }; mat3.identity = function(out) { out.m00 = 1; out.m01 = 0; out.m02 = 0; out.m03 = 0; out.m04 = 1; out.m05 = 0; out.m06 = 0; out.m07 = 0; out.m08 = 1; return out; }; mat3.transpose = function(out, a) { if (out === a) { var a01 = a.m01, a02 = a.m02, a12 = a.m05; out.m01 = a.m03; out.m02 = a.m06; out.m03 = a01; out.m05 = a.m07; out.m06 = a02; out.m07 = a12; } else { out.m00 = a.m00; out.m01 = a.m03; out.m02 = a.m06; out.m03 = a.m01; out.m04 = a.m04; out.m05 = a.m07; out.m06 = a.m02; out.m07 = a.m05; out.m08 = a.m08; } return out; }; mat3.invert = function(out, a) { var a00 = a.m00, a01 = a.m01, a02 = a.m02, a10 = a.m03, a11 = a.m04, a12 = a.m05, a20 = a.m06, a21 = a.m07, a22 = a.m08; 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 null; det = 1 / det; out.m00 = b01 * det; out.m01 = (-a22 * a01 + a02 * a21) * det; out.m02 = (a12 * a01 - a02 * a11) * det; out.m03 = b11 * det; out.m04 = (a22 * a00 - a02 * a20) * det; out.m05 = (-a12 * a00 + a02 * a10) * det; out.m06 = b21 * det; out.m07 = (-a21 * a00 + a01 * a20) * det; out.m08 = (a11 * a00 - a01 * a10) * det; return out; }; mat3.adjoint = function(out, a) { var a00 = a.m00, a01 = a.m01, a02 = a.m02, a10 = a.m03, a11 = a.m04, a12 = a.m05, a20 = a.m06, a21 = a.m07, a22 = a.m08; out.m00 = a11 * a22 - a12 * a21; out.m01 = a02 * a21 - a01 * a22; out.m02 = a01 * a12 - a02 * a11; out.m03 = a12 * a20 - a10 * a22; out.m04 = a00 * a22 - a02 * a20; out.m05 = a02 * a10 - a00 * a12; out.m06 = a10 * a21 - a11 * a20; out.m07 = a01 * a20 - a00 * a21; out.m08 = a00 * a11 - a01 * a10; return out; }; mat3.determinant = function(a) { var a00 = a.m00, a01 = a.m01, a02 = a.m02, a10 = a.m03, a11 = a.m04, a12 = a.m05, a20 = a.m06, a21 = a.m07, a22 = a.m08; return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20); }; mat3.multiply = function(out, a, b) { var a00 = a.m00, a01 = a.m01, a02 = a.m02, a10 = a.m03, a11 = a.m04, a12 = a.m05, a20 = a.m06, a21 = a.m07, a22 = a.m08; var b00 = b.m00, b01 = b.m01, b02 = b.m02; var b10 = b.m03, b11 = b.m04, b12 = b.m05; var b20 = b.m06, b21 = b.m07, b22 = b.m08; out.m00 = b00 * a00 + b01 * a10 + b02 * a20; out.m01 = b00 * a01 + b01 * a11 + b02 * a21; out.m02 = b00 * a02 + b01 * a12 + b02 * a22; out.m03 = b10 * a00 + b11 * a10 + b12 * a20; out.m04 = b10 * a01 + b11 * a11 + b12 * a21; out.m05 = b10 * a02 + b11 * a12 + b12 * a22; out.m06 = b20 * a00 + b21 * a10 + b22 * a20; out.m07 = b20 * a01 + b21 * a11 + b22 * a21; out.m08 = b20 * a02 + b21 * a12 + b22 * a22; return out; }; mat3.mul = mat3.multiply; mat3.translate = function(out, a, v) { var a00 = a.m00, a01 = a.m01, a02 = a.m02, a10 = a.m03, a11 = a.m04, a12 = a.m05, a20 = a.m06, a21 = a.m07, a22 = a.m08; var x = v.x, y = v.y; out.m00 = a00; out.m01 = a01; out.m02 = a02; out.m03 = a10; out.m04 = a11; out.m05 = a12; out.m06 = x * a00 + y * a10 + a20; out.m07 = x * a01 + y * a11 + a21; out.m08 = x * a02 + y * a12 + a22; return out; }; mat3.rotate = function(out, a, rad) { var a00 = a.m00, a01 = a.m01, a02 = a.m02, a10 = a.m03, a11 = a.m04, a12 = a.m05, a20 = a.m06, a21 = a.m07, a22 = a.m08; var s = Math.sin(rad); var c = Math.cos(rad); out.m00 = c * a00 + s * a10; out.m01 = c * a01 + s * a11; out.m02 = c * a02 + s * a12; out.m03 = c * a10 - s * a00; out.m04 = c * a11 - s * a01; out.m05 = c * a12 - s * a02; out.m06 = a20; out.m07 = a21; out.m08 = a22; return out; }; mat3.scale = function(out, a, v) { var x = v.x, y = v.y; out.m00 = x * a.m00; out.m01 = x * a.m01; out.m02 = x * a.m02; out.m03 = y * a.m03; out.m04 = y * a.m04; out.m05 = y * a.m05; out.m06 = a.m06; out.m07 = a.m07; out.m08 = a.m08; return out; }; mat3.fromMat4 = function(out, a) { out.m00 = a.m00; out.m01 = a.m01; out.m02 = a.m02; out.m03 = a.m04; out.m04 = a.m05; out.m05 = a.m06; out.m06 = a.m08; out.m07 = a.m09; out.m08 = a.m10; return out; }; mat3.fromTranslation = function(out, v) { out.m00 = 1; out.m01 = 0; out.m02 = 0; out.m03 = 0; out.m04 = 1; out.m05 = 0; out.m06 = v.x; out.m07 = v.y; out.m08 = 1; return out; }; mat3.fromRotation = function(out, rad) { var s = Math.sin(rad), c = Math.cos(rad); out.m00 = c; out.m01 = s; out.m02 = 0; out.m03 = -s; out.m04 = c; out.m05 = 0; out.m06 = 0; out.m07 = 0; out.m08 = 1; return out; }; mat3.fromScaling = function(out, v) { out.m00 = v.x; out.m01 = 0; out.m02 = 0; out.m03 = 0; out.m04 = v.y; out.m05 = 0; out.m06 = 0; out.m07 = 0; out.m08 = 1; return out; }; mat3.fromMat2d = function(out, a) { out.m00 = a.m00; out.m01 = a.m01; out.m02 = 0; out.m03 = a.m02; out.m04 = a.m03; out.m05 = 0; out.m06 = a.m04; out.m07 = a.m05; out.m08 = 1; return out; }; mat3.fromQuat = function(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; out.m00 = 1 - yy - zz; out.m03 = yx - wz; out.m06 = zx + wy; out.m01 = yx + wz; out.m04 = 1 - xx - zz; out.m07 = zy - wx; out.m02 = zx - wy; out.m05 = zy + wx; out.m08 = 1 - xx - yy; return out; }; mat3.fromViewUp = (function() { var default_up = vec3.new(0, 1, 0); var x = vec3.create(); var y = vec3.create(); return function(out, view, up) { if (vec3.sqrLen(view) < EPSILON * EPSILON) { mat3.identity(out); return out; } up = up || default_up; vec3.cross(x, up, view); if (vec3.sqrLen(x) < EPSILON * EPSILON) { mat3.identity(out); return out; } vec3.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; }; })(); mat3.normalFromMat4 = function(out, a) { var a00 = a.m00, a01 = a.m01, a02 = a.m02, a03 = a.m03, a10 = a.m04, a11 = a.m05, a12 = a.m06, a13 = a.m07, a20 = a.m08, a21 = a.m09, a22 = a.m10, a23 = a.m11, a30 = a.m12, a31 = a.m13, a32 = a.m14, a33 = a.m15; 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; out.m00 = (a11 * b11 - a12 * b10 + a13 * b09) * det; out.m01 = (a12 * b08 - a10 * b11 - a13 * b07) * det; out.m02 = (a10 * b10 - a11 * b08 + a13 * b06) * det; out.m03 = (a02 * b10 - a01 * b11 - a03 * b09) * det; out.m04 = (a00 * b11 - a02 * b08 + a03 * b07) * det; out.m05 = (a01 * b08 - a00 * b10 - a03 * b06) * det; out.m06 = (a31 * b05 - a32 * b04 + a33 * b03) * det; out.m07 = (a32 * b02 - a30 * b05 - a33 * b01) * det; out.m08 = (a30 * b04 - a31 * b02 + a33 * b00) * det; return out; }; mat3.str = function(a) { return "mat3(" + a.m00 + ", " + a.m01 + ", " + a.m02 + ", " + a.m03 + ", " + a.m04 + ", " + a.m05 + ", " + a.m06 + ", " + a.m07 + ", " + a.m08 + ")"; }; mat3.array = function(out, m) { out[0] = m.m00; out[1] = m.m01; out[2] = m.m02; out[3] = m.m03; out[4] = m.m04; out[5] = m.m05; out[6] = m.m06; out[7] = m.m07; out[8] = m.m08; return out; }; mat3.frob = function(a) { return Math.sqrt(Math.pow(a.m00, 2) + Math.pow(a.m01, 2) + Math.pow(a.m02, 2) + Math.pow(a.m03, 2) + Math.pow(a.m04, 2) + Math.pow(a.m05, 2) + Math.pow(a.m06, 2) + Math.pow(a.m07, 2) + Math.pow(a.m08, 2)); }; mat3.add = function(out, a, b) { out.m00 = a.m00 + b.m00; out.m01 = a.m01 + b.m01; out.m02 = a.m02 + b.m02; out.m03 = a.m03 + b.m03; out.m04 = a.m04 + b.m04; out.m05 = a.m05 + b.m05; out.m06 = a.m06 + b.m06; out.m07 = a.m07 + b.m07; out.m08 = a.m08 + b.m08; return out; }; mat3.subtract = function(out, a, b) { out.m00 = a.m00 - b.m00; out.m01 = a.m01 - b.m01; out.m02 = a.m02 - b.m02; out.m03 = a.m03 - b.m03; out.m04 = a.m04 - b.m04; out.m05 = a.m05 - b.m05; out.m06 = a.m06 - b.m06; out.m07 = a.m07 - b.m07; out.m08 = a.m08 - b.m08; return out; }; mat3.sub = mat3.subtract; mat3.multiplyScalar = function(out, a, b) { out.m00 = a.m00 * b; out.m01 = a.m01 * b; out.m02 = a.m02 * b; out.m03 = a.m03 * b; out.m04 = a.m04 * b; out.m05 = a.m05 * b; out.m06 = a.m06 * b; out.m07 = a.m07 * b; out.m08 = a.m08 * b; return out; }; mat3.multiplyScalarAndAdd = function(out, a, b, scale) { out.m00 = a.m00 + b.m00 * scale; out.m01 = a.m01 + b.m01 * scale; out.m02 = a.m02 + b.m02 * scale; out.m03 = a.m03 + b.m03 * scale; out.m04 = a.m04 + b.m04 * scale; out.m05 = a.m05 + b.m05 * scale; out.m06 = a.m06 + b.m06 * scale; out.m07 = a.m07 + b.m07 * scale; out.m08 = a.m08 + b.m08 * scale; return out; }; mat3.exactEquals = function(a, b) { return a.m00 === b.m00 && a.m01 === b.m01 && a.m02 === b.m02 && a.m03 === b.m03 && a.m04 === b.m04 && a.m05 === b.m05 && a.m06 === b.m06 && a.m07 === b.m07 && a.m08 === b.m08; }; mat3.equals = function(a, b) { var a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03, a4 = a.m04, a5 = a.m05, a6 = a.m06, a7 = a.m07, a8 = a.m08; var b0 = b.m00, b1 = b.m01, b2 = b.m02, b3 = b.m03, b4 = b.m04, b5 = b.m05, b6 = b.m06, b7 = b.m07, b8 = b.m08; 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)) && Math.abs(a3 - b3) <= EPSILON * Math.max(1, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= EPSILON * Math.max(1, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= EPSILON * Math.max(1, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= EPSILON * Math.max(1, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= EPSILON * Math.max(1, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= EPSILON * Math.max(1, Math.abs(a8), Math.abs(b8)); }; var _tmp$4 = new Array(4); var _quat = function _quat(x, y, z, w) { this.x = x; this.y = y; this.z = z; this.w = w; }; _quat.prototype.toJSON = function toJSON() { _tmp$4[0] = this.x; _tmp$4[1] = this.y; _tmp$4[2] = this.z; _tmp$4[3] = this.w; return _tmp$4; }; var quat = {}; quat.create = function() { return new _quat(0, 0, 0, 1); }; quat.new = function(x, y, z, w) { return new _quat(x, y, z, w); }; quat.clone = function(a) { return new _quat(a.x, a.y, a.z, a.w); }; quat.copy = vec4.copy; quat.set = vec4.set; quat.identity = function(out) { out.x = 0; out.y = 0; out.z = 0; out.w = 1; return out; }; quat.rotationTo = (function() { var tmpvec3 = vec3.create(); var xUnitVec3 = vec3.new(1, 0, 0); var yUnitVec3 = vec3.new(0, 1, 0); return function(out, a, b) { var dot = vec3.dot(a, b); if (dot < -.999999) { vec3.cross(tmpvec3, xUnitVec3, a); vec3.length(tmpvec3) < 1e-6 && vec3.cross(tmpvec3, yUnitVec3, a); vec3.normalize(tmpvec3, tmpvec3); quat.fromAxisAngle(out, tmpvec3, Math.PI); return out; } if (dot > .999999) { out.x = 0; out.y = 0; out.z = 0; out.w = 1; return out; } vec3.cross(tmpvec3, a, b); out.x = tmpvec3.x; out.y = tmpvec3.y; out.z = tmpvec3.z; out.w = 1 + dot; return quat.normalize(out, out); }; })(); quat.getAxisAngle = function(out_axis, q) { var rad = 2 * Math.acos(q.w); var s = Math.sin(rad / 2); if (0 != s) { out_axis.x = q.x / s; out_axis.y = q.y / s; out_axis.z = q.z / s; } else { out_axis.x = 1; out_axis.y = 0; out_axis.z = 0; } return rad; }; quat.multiply = function(out, a, b) { var ax = a.x, ay = a.y, az = a.z, aw = a.w, bx = b.x, by = b.y, bz = b.z, bw = b.w; out.x = ax * bw + aw * bx + ay * bz - az * by; out.y = ay * bw + aw * by + az * bx - ax * bz; out.z = az * bw + aw * bz + ax * by - ay * bx; out.w = aw * bw - ax * bx - ay * by - az * bz; return out; }; quat.mul = quat.multiply; quat.scale = vec4.scale; quat.rotateX = function(out, a, rad) { rad *= .5; var ax = a.x, ay = a.y, az = a.z, aw = a.w, bx = Math.sin(rad), bw = Math.cos(rad); out.x = ax * bw + aw * bx; out.y = ay * bw + az * bx; out.z = az * bw - ay * bx; out.w = aw * bw - ax * bx; return out; }; quat.rotateY = function(out, a, rad) { rad *= .5; var ax = a.x, ay = a.y, az = a.z, aw = a.w, by = Math.sin(rad), bw = Math.cos(rad); out.x = ax * bw - az * by; out.y = ay * bw + aw * by; out.z = az * bw + ax * by; out.w = aw * bw - ay * by; return out; }; quat.rotateZ = function(out, a, rad) { rad *= .5; var ax = a.x, ay = a.y, az = a.z, aw = a.w, bz = Math.sin(rad), bw = Math.cos(rad); out.x = ax * bw + ay * bz; out.y = ay * bw - ax * bz; out.z = az * bw + aw * bz; out.w = aw * bw - az * bz; return out; }; quat.rotateAround = (function() { var v3_tmp = vec3.create(); var q_tmp = quat.create(); return function(out, rot, axis, rad) { quat.invert(q_tmp, rot); vec3.transformQuat(v3_tmp, axis, q_tmp); quat.fromAxisAngle(q_tmp, v3_tmp, rad); quat.mul(out, rot, q_tmp); return out; }; })(); quat.rotateAroundLocal = (function() { var q_tmp = quat.create(); return function(out, rot, axis, rad) { quat.fromAxisAngle(q_tmp, axis, rad); quat.mul(out, rot, q_tmp); return out; }; })(); quat.calculateW = function(out, a) { var x = a.x, y = a.y, z = a.z; out.x = x; out.y = y; out.z = z; out.w = Math.sqrt(Math.abs(1 - x * x - y * y - z * z)); return out; }; quat.dot = vec4.dot; quat.lerp = vec4.lerp; quat.slerp = function(out, a, b, t) { var ax = a.x, ay = a.y, az = a.z, aw = a.w, bx = b.x, by = b.y, bz = b.z, bw = b.w; var omega, cosom, sinom, scale0, scale1; cosom = ax * bx + ay * by + az * bz + aw * bw; if (cosom < 0) { cosom = -cosom; bx = -bx; by = -by; bz = -bz; bw = -bw; } if (1 - cosom > 1e-6) { omega = Math.acos(cosom); 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 * ax + scale1 * bx; out.y = scale0 * ay + scale1 * by; out.z = scale0 * az + scale1 * bz; out.w = scale0 * aw + scale1 * bw; return out; }; quat.sqlerp = (function() { var temp1 = quat.create(); var temp2 = quat.create(); return function(out, a, b, c, d, t) { quat.slerp(temp1, a, d, t); quat.slerp(temp2, b, c, t); quat.slerp(out, temp1, temp2, 2 * t * (1 - t)); return out; }; })(); quat.invert = function(out, a) { var a0 = a.x, a1 = a.y, a2 = a.z, a3 = a.w; var dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3; var invDot = dot ? 1 / dot : 0; out.x = -a0 * invDot; out.y = -a1 * invDot; out.z = -a2 * invDot; out.w = a3 * invDot; return out; }; quat.conjugate = function(out, a) { out.x = -a.x; out.y = -a.y; out.z = -a.z; out.w = a.w; return out; }; quat.length = vec4.length; quat.len = quat.length; quat.squaredLength = vec4.squaredLength; quat.sqrLen = quat.squaredLength; quat.normalize = vec4.normalize; quat.fromAxes = (function() { var matr = mat3.create(); return function(out, xAxis, yAxis, zAxis) { mat3.set(matr, 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, matr)); }; })(); quat.fromViewUp = (function() { var matr = mat3.create(); return function(out, view, up) { mat3.fromViewUp(matr, view, up); if (!matr) return null; return quat.normalize(out, quat.fromMat3(out, matr)); }; })(); quat.fromAxisAngle = function(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.fromMat3 = function(out, m) { var m00 = m.m00, m01 = m.m03, m02 = m.m06, m10 = m.m01, m11 = m.m04, m12 = m.m07, m20 = m.m02, m21 = m.m05, m22 = m.m08; 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$1 = 2 * Math.sqrt(1 + m00 - m11 - m22); out.w = (m21 - m12) / s$1; out.x = .25 * s$1; out.y = (m01 + m10) / s$1; out.z = (m02 + m20) / s$1; } else if (m11 > m22) { var s$2 = 2 * Math.sqrt(1 + m11 - m00 - m22); out.w = (m02 - m20) / s$2; out.x = (m01 + m10) / s$2; out.y = .25 * s$2; out.z = (m12 + m21) / s$2; } else { var s$3 = 2 * Math.sqrt(1 + m22 - m00 - m11); out.w = (m10 - m01) / s$3; out.x = (m02 + m20) / s$3; out.y = (m12 + m21) / s$3; out.z = .25 * s$3; } return out; }; quat.fromEuler = function(out, x, y, z) { var halfToRad = .5 * Math.PI / 180; 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.str = function(a) { return "quat(" + a.x + ", " + a.y + ", " + a.z + ", " + a.w + ")"; }; quat.array = function(out, q) { out[0] = q.x; out[1] = q.y; out[2] = q.z; out[3] = q.w; return out; }; quat.exactEquals = vec4.exactEquals; quat.equals = vec4.equals; var _tmp$5 = new Array(4); var _mat2 = function _mat2(m00, m01, m02, m03) { this.m00 = m00; this.m01 = m01; this.m02 = m02; this.m03 = m03; }; _mat2.prototype.toJSON = function toJSON() { _tmp$5[0] = this.m00; _tmp$5[1] = this.m01; _tmp$5[2] = this.m02; _tmp$5[3] = this.m03; return _tmp$5; }; var mat2 = {}; mat2.create = function() { return new _mat2(1, 0, 0, 1); }; mat2.new = function(m00, m01, m10, m11) { return new _mat2(m00, m01, m10, m11); }; mat2.clone = function(a) { return new _mat2(a.m00, a.m01, a.m02, a.m03); }; mat2.copy = function(out, a) { out.m00 = a.m00; out.m01 = a.m01; out.m02 = a.m02; out.m03 = a.m03; return out; }; mat2.identity = function(out) { out.m00 = 1; out.m01 = 0; out.m02 = 0; out.m03 = 1; return out; }; mat2.set = function(out, m00, m01, m10, m11) { out.m00 = m00; out.m01 = m01; out.m02 = m10; out.m03 = m11; return out; }; mat2.transpose = function(out, a) { if (out === a) { var a1 = a.m01; out.m01 = a.m02; out.m02 = a1; } else { out.m00 = a.m00; out.m01 = a.m02; out.m02 = a.m01; out.m03 = a.m03; } return out; }; mat2.invert = function(out, a) { var a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03; var det = a0 * a3 - a2 * a1; if (!det) return null; det = 1 / det; out.m00 = a3 * det; out.m01 = -a1 * det; out.m02 = -a2 * det; out.m03 = a0 * det; return out; }; mat2.adjoint = function(out, a) { var a0 = a.m00; out.m00 = a.m03; out.m01 = -a.m01; out.m02 = -a.m02; out.m03 = a0; return out; }; mat2.determinant = function(a) { return a.m00 * a.m03 - a.m02 * a.m01; }; mat2.multiply = function(out, a, b) { var a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03; var b0 = b.m00, b1 = b.m01, b2 = b.m02, b3 = b.m03; out.m00 = a0 * b0 + a2 * b1; out.m01 = a1 * b0 + a3 * b1; out.m02 = a0 * b2 + a2 * b3; out.m03 = a1 * b2 + a3 * b3; return out; }; mat2.mul = mat2.multiply; mat2.rotate = function(out, a, rad) { var a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03, s = Math.sin(rad), c = Math.cos(rad); out.m00 = a0 * c + a2 * s; out.m01 = a1 * c + a3 * s; out.m02 = a0 * -s + a2 * c; out.m03 = a1 * -s + a3 * c; return out; }; mat2.scale = function(out, a, v) { var a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03, v0 = v.x, v1 = v.y; out.m00 = a0 * v0; out.m01 = a1 * v0; out.m02 = a2 * v1; out.m03 = a3 * v1; return out; }; mat2.fromRotation = function(out, rad) { var s = Math.sin(rad), c = Math.cos(rad); out.m00 = c; out.m01 = s; out.m02 = -s; out.m03 = c; return out; }; mat2.fromScaling = function(out, v) { out.m00 = v.x; out.m01 = 0; out.m02 = 0; out.m03 = v.y; return out; }; mat2.str = function(a) { return "mat2(" + a.m00 + ", " + a.m01 + ", " + a.m02 + ", " + a.m03 + ")"; }; mat2.array = function(out, m) { out[0] = m.m00; out[1] = m.m01; out[2] = m.m02; out[3] = m.m03; return out; }; mat2.frob = function(a) { return Math.sqrt(Math.pow(a.m00, 2) + Math.pow(a.m01, 2) + Math.pow(a.m02, 2) + Math.pow(a.m03, 2)); }; mat2.LDU = function(L, D, U, a) { L.m02 = a.m02 / a.m00; U.m00 = a.m00; U.m01 = a.m01; U.m03 = a.m03 - L.m02 * U.m01; }; mat2.add = function(out, a, b) { out.m00 = a.m00 + b.m00; out.m01 = a.m01 + b.m01; out.m02 = a.m02 + b.m02; out.m03 = a.m03 + b.m03; return out; }; mat2.subtract = function(out, a, b) { out.m00 = a.m00 - b.m00; out.m01 = a.m01 - b.m01; out.m02 = a.m02 - b.m02; out.m03 = a.m03 - b.m03; return out; }; mat2.sub = mat2.subtract; mat2.exactEquals = function(a, b) { return a.m00 === b.m00 && a.m01 === b.m01 && a.m02 === b.m02 && a.m03 === b.m03; }; mat2.equals = function(a, b) { var a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03; var b0 = b.m00, b1 = b.m01, b2 = b.m02, b3 = b.m03; 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)) && Math.abs(a3 - b3) <= EPSILON * Math.max(1, Math.abs(a3), Math.abs(b3)); }; mat2.multiplyScalar = function(out, a, b) { out.m00 = a.m00 * b; out.m01 = a.m01 * b; out.m02 = a.m02 * b; out.m03 = a.m03 * b; return out; }; mat2.multiplyScalarAndAdd = function(out, a, b, scale) { out.m00 = a.m00 + b.m00 * scale; out.m01 = a.m01 + b.m01 * scale; out.m02 = a.m02 + b.m02 * scale; out.m03 = a.m03 + b.m03 * scale; return out; }; var _tmp$6 = new Array(6); var _mat23 = function _mat23(m00, m01, m02, m03, m04, m05) { this.m00 = m00; this.m01 = m01; this.m02 = m02; this.m03 = m03; this.m04 = m04; this.m05 = m05; }; _mat23.prototype.toJSON = function toJSON() { _tmp$6[0] = this.m00; _tmp$6[1] = this.m01; _tmp$6[2] = this.m02; _tmp$6[3] = this.m03; _tmp$6[4] = this.m04; _tmp$6[5] = this.m05; return _tmp$6; }; var mat23 = {}; mat23.create = function() { return new _mat23(1, 0, 0, 1, 0, 0); }; mat23.new = function(a, b, c, d, tx, ty) { return new _mat23(a, b, c, d, tx, ty); }; mat23.clone = function(a) { return new _mat23(a.m00, a.m01, a.m02, a.m03, a.m04, a.m05); }; mat23.copy = function(out, a) { out.m00 = a.m00; out.m01 = a.m01; out.m02 = a.m02; out.m03 = a.m03; out.m04 = a.m04; out.m05 = a.m05; return out; }; mat23.identity = function(out) { out.m00 = 1; out.m01 = 0; out.m02 = 0; out.m03 = 1; out.m04 = 0; out.m05 = 0; return out; }; mat23.set = function(out, a, b, c, d, tx, ty) { out.m00 = a; out.m01 = b; out.m02 = c; out.m03 = d; out.m04 = tx; out.m05 = ty; return out; }; mat23.invert = function(out, a) { var aa = a.m00, ab = a.m01, ac = a.m02, ad = a.m03, atx = a.m04, aty = a.m05; var det = aa * ad - ab * ac; if (!det) return null; det = 1 / det; out.m00 = ad * det; out.m01 = -ab * det; out.m02 = -ac * det; out.m03 = aa * det; out.m04 = (ac * aty - ad * atx) * det; out.m05 = (ab * atx - aa * aty) * det; return out; }; mat23.determinant = function(a) { return a.m00 * a.m03 - a.m01 * a.m02; }; mat23.multiply = function(out, a, b) { var a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03, a4 = a.m04, a5 = a.m05, b0 = b.m00, b1 = b.m01, b2 = b.m02, b3 = b.m03, b4 = b.m04, b5 = b.m05; out.m00 = a0 * b0 + a2 * b1; out.m01 = a1 * b0 + a3 * b1; out.m02 = a0 * b2 + a2 * b3; out.m03 = a1 * b2 + a3 * b3; out.m04 = a0 * b4 + a2 * b5 + a4; out.m05 = a1 * b4 + a3 * b5 + a5; return out; }; mat23.mul = mat23.multiply; mat23.rotate = function(out, a, rad) { var a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03, a4 = a.m04, a5 = a.m05, s = Math.sin(rad), c = Math.cos(rad); out.m00 = a0 * c + a2 * s; out.m01 = a1 * c + a3 * s; out.m02 = a0 * -s + a2 * c; out.m03 = a1 * -s + a3 * c; out.m04 = a4; out.m05 = a5; return out; }; mat23.scale = function(out, a, v) { var a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03, a4 = a.m04, a5 = a.m05, v0 = v.x, v1 = v.y; out.m00 = a0 * v0; out.m01 = a1 * v0; out.m02 = a2 * v1; out.m03 = a3 * v1; out.m04 = a4; out.m05 = a5; return out; }; mat23.translate = function(out, a, v) { var a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03, a4 = a.m04, a5 = a.m05, v0 = v.x, v1 = v.y; out.m00 = a0; out.m01 = a1; out.m02 = a2; out.m03 = a3; out.m04 = a0 * v0 + a2 * v1 + a4; out.m05 = a1 * v0 + a3 * v1 + a5; return out; }; mat23.fromRotation = function(out, rad) { var s = Math.sin(rad), c = Math.cos(rad); out.m00 = c; out.m01 = s; out.m02 = -s; out.m03 = c; out.m04 = 0; out.m05 = 0; return out; }; mat23.fromScaling = function(out, v) { out.m00 = v.m00; out.m01 = 0; out.m02 = 0; out.m03 = v.m01; out.m04 = 0; out.m05 = 0; return out; }; mat23.fromTranslation = function(out, v) { out.m00 = 1; out.m01 = 0; out.m02 = 0; out.m03 = 1; out.m04 = v.x; out.m05 = v.y; return out; }; mat23.str = function(a) { return "mat23(" + a.m00 + ", " + a.m01 + ", " + a.m02 + ", " + a.m03 + ", " + a.m04 + ", " + a.m05 + ")"; }; mat23.array = function(out, m) { out[0] = m.m00; out[1] = m.m01; out[2] = m.m02; out[3] = m.m03; out[4] = m.m04; out[5] = m.m05; return out; }; mat23.array4x4 = function(out, m) { out[0] = m.m00; out[1] = m.m01; out[2] = 0; out[3] = 0; out[4] = m.m02; out[5] = m.m03; out[6] = 0; out[7] = 0; out[8] = 0; out[9] = 0; out[10] = 1; out[11] = 0; out[12] = m.m04; out[13] = m.m05; out[14] = 0; out[15] = 1; return out; }; mat23.frob = function(a) { return Math.sqrt(Math.pow(a.m00, 2) + Math.pow(a.m01, 2) + Math.pow(a.m02, 2) + Math.pow(a.m03, 2) + Math.pow(a.m04, 2) + Math.pow(a.m05, 2) + 1); }; mat23.add = function(out, a, b) { out.m00 = a.m00 + b.m00; out.m01 = a.m01 + b.m01; out.m02 = a.m02 + b.m02; out.m03 = a.m03 + b.m03; out.m04 = a.m04 + b.m04; out.m05 = a.m05 + b.m05; return out; }; mat23.subtract = function(out, a, b) { out.m00 = a.m00 - b.m00; out.m01 = a.m01 - b.m01; out.m02 = a.m02 - b.m02; out.m03 = a.m03 - b.m03; out.m04 = a.m04 - b.m04; out.m05 = a.m05 - b.m05; return out; }; mat23.sub = mat23.subtract; mat23.multiplyScalar = function(out, a, b) { out.m00 = a.m00 * b; out.m01 = a.m01 * b; out.m02 = a.m02 * b; out.m03 = a.m03 * b; out.m04 = a.m04 * b; out.m05 = a.m05 * b; return out; }; mat23.multiplyScalarAndAdd = function(out, a, b, scale) { out.m00 = a.m00 + b.m00 * scale; out.m01 = a.m01 + b.m01 * scale; out.m02 = a.m02 + b.m02 * scale; out.m03 = a.m03 + b.m03 * scale; out.m04 = a.m04 + b.m04 * scale; out.m05 = a.m05 + b.m05 * scale; return out; }; mat23.exactEquals = function(a, b) { return a.m00 === b.m00 && a.m01 === b.m01 && a.m02 === b.m02 && a.m03 === b.m03 && a.m04 === b.m04 && a.m05 === b.m05; }; mat23.equals = function(a, b) { var a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03, a4 = a.m04, a5 = a.m05; var b0 = b.m00, b1 = b.m01, b2 = b.m02, b3 = b.m03, b4 = b.m04, b5 = b.m05; 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)) && Math.abs(a3 - b3) <= EPSILON * Math.max(1, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= EPSILON * Math.max(1, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= EPSILON * Math.max(1, Math.abs(a5), Math.abs(b5)); }; var _tmp$7 = new Array(16); var _mat4 = function _mat4(m00, m01, m02, m03, m04, m05, m06, m07, m08, m09, m10, m11, m12, m13, m14, m15) { this.m00 = m00; this.m01 = m01; this.m02 = m02; this.m03 = m03; this.m04 = m04; this.m05 = m05; this.m06 = m06; this.m07 = m07; this.m08 = m08; this.m09 = m09; this.m10 = m10; this.m11 = m11; this.m12 = m12; this.m13 = m13; this.m14 = m14; this.m15 = m15; }; _mat4.prototype.toJSON = function toJSON() { _tmp$7[0] = this.m00; _tmp$7[1] = this.m01; _tmp$7[2] = this.m02; _tmp$7[3] = this.m03; _tmp$7[4] = this.m04; _tmp$7[5] = this.m05; _tmp$7[6] = this.m06; _tmp$7[7] = this.m07; _tmp$7[8] = this.m08; _tmp$7[9] = this.m09; _tmp$7[10] = this.m10; _tmp$7[11] = this.m11; _tmp$7[12] = this.m12; _tmp$7[13] = this.m13; _tmp$7[14] = this.m14; _tmp$7[15] = this.m15; return _tmp$7; }; var mat4 = {}; mat4.create = function() { return new _mat4(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); }; mat4.new = function(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) { return new _mat4(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33); }; mat4.clone = function(a) { return new _mat4(a.m00, a.m01, a.m02, a.m03, a.m04, a.m05, a.m06, a.m07, a.m08, a.m09, a.m10, a.m11, a.m12, a.m13, a.m14, a.m15); }; mat4.copy = function(out, a) { out.m00 = a.m00; out.m01 = a.m01; out.m02 = a.m02; out.m03 = a.m03; out.m04 = a.m04; out.m05 = a.m05; out.m06 = a.m06; out.m07 = a.m07; out.m08 = a.m08; out.m09 = a.m09; out.m10 = a.m10; out.m11 = a.m11; out.m12 = a.m12; out.m13 = a.m13; out.m14 = a.m14; out.m15 = a.m15; return out; }; mat4.set = function(out, m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) { out.m00 = m00; out.m01 = m01; out.m02 = m02; out.m03 = m03; out.m04 = m10; out.m05 = m11; out.m06 = m12; out.m07 = m13; out.m08 = m20; out.m09 = m21; out.m10 = m22; out.m11 = m23; out.m12 = m30; out.m13 = m31; out.m14 = m32; out.m15 = m33; return out; }; mat4.identity = function(out) { out.m00 = 1; out.m01 = 0; out.m02 = 0; out.m03 = 0; out.m04 = 0; out.m05 = 1; out.m06 = 0; out.m07 = 0; out.m08 = 0; out.m09 = 0; out.m10 = 1; out.m11 = 0; out.m12 = 0; out.m13 = 0; out.m14 = 0; out.m15 = 1; return out; }; mat4.transpose = function(out, a) { if (out === a) { var a01 = a.m01, a02 = a.m02, a03 = a.m03, a12 = a.m06, a13 = a.m07, a23 = a.m11; out.m01 = a.m04; out.m02 = a.m08; out.m03 = a.m12; out.m04 = a01; out.m06 = a.m09; out.m07 = a.m13; out.m08 = a02; out.m09 = a12; out.m11 = a.m14; out.m12 = a03; out.m13 = a13; out.m14 = a23; } else { out.m00 = a.m00; out.m01 = a.m04; out.m02 = a.m08; out.m03 = a.m12; out.m04 = a.m01; out.m05 = a.m05; out.m06 = a.m09; out.m07 = a.m13; out.m08 = a.m02; out.m09 = a.m06; out.m10 = a.m10; out.m11 = a.m14; out.m12 = a.m03; out.m13 = a.m07; out.m14 = a.m11; out.m15 = a.m15; } return out; }; mat4.invert = function(out, a) { var a00 = a.m00, a01 = a.m01, a02 = a.m02, a03 = a.m03, a10 = a.m04, a11 = a.m05, a12 = a.m06, a13 = a.m07, a20 = a.m08, a21 = a.m09, a22 = a.m10, a23 = a.m11, a30 = a.m12, a31 = a.m13, a32 = a.m14, a33 = a.m15; 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; out.m00 = (a11 * b11 - a12 * b10 + a13 * b09) * det; out.m01 = (a02 * b10 - a01 * b11 - a03 * b09) * det; out.m02 = (a31 * b05 - a32 * b04 + a33 * b03) * det; out.m03 = (a22 * b04 - a21 * b05 - a23 * b03) * det; out.m04 = (a12 * b08 - a10 * b11 - a13 * b07) * det; out.m05 = (a00 * b11 - a02 * b08 + a03 * b07) * det; out.m06 = (a32 * b02 - a30 * b05 - a33 * b01) * det; out.m07 = (a20 * b05 - a22 * b02 + a23 * b01) * det; out.m08 = (a10 * b10 - a11 * b08 + a13 * b06) * det; out.m09 = (a01 * b08 - a00 * b10 - a03 * b06) * det; out.m10 = (a30 * b04 - a31 * b02 + a33 * b00) * det; out.m11 = (a21 * b02 - a20 * b04 - a23 * b00) * det; out.m12 = (a11 * b07 - a10 * b09 - a12 * b06) * det; out.m13 = (a00 * b09 - a01 * b07 + a02 * b06) * det; out.m14 = (a31 * b01 - a30 * b03 - a32 * b00) * det; out.m15 = (a20 * b03 - a21 * b01 + a22 * b00) * det; return out; }; mat4.adjoint = function(out, a) { var a00 = a.m00, a01 = a.m01, a02 = a.m02, a03 = a.m03, a10 = a.m04, a11 = a.m05, a12 = a.m06, a13 = a.m07, a20 = a.m08, a21 = a.m09, a22 = a.m10, a23 = a.m11, a30 = a.m12, a31 = a.m13, a32 = a.m14, a33 = a.m15; out.m00 = a11 * (a22 * a33 - a23 * a32) - a21 * (a12 * a33 - a13 * a32) + a31 * (a12 * a23 - a13 * a22); out.m01 = -(a01 * (a22 * a33 - a23 * a32) - a21 * (a02 * a33 - a03 * a32) + a31 * (a02 * a23 - a03 * a22)); out.m02 = a01 * (a12 * a33 - a13 * a32) - a11 * (a02 * a33 - a03 * a32) + a31 * (a02 * a13 - a03 * a12); out.m03 = -(a01 * (a12 * a23 - a13 * a22) - a11 * (a02 * a23 - a03 * a22) + a21 * (a02 * a13 - a03 * a12)); out.m04 = -(a10 * (a22 * a33 - a23 * a32) - a20 * (a12 * a33 - a13 * a32) + a30 * (a12 * a23 - a13 * a22)); out.m05 = a00 * (a22 * a33 - a23 * a32) - a20 * (a02 * a33 - a03 * a32) + a30 * (a02 * a23 - a03 * a22); out.m06 = -(a00 * (a12 * a33 - a13 * a32) - a10 * (a02 * a33 - a03 * a32) + a30 * (a02 * a13 - a03 * a12)); out.m07 = a00 * (a12 * a23 - a13 * a22) - a10 * (a02 * a23 - a03 * a22) + a20 * (a02 * a13 - a03 * a12); out.m08 = a10 * (a21 * a33 - a23 * a31) - a20 * (a11 * a33 - a13 * a31) + a30 * (a11 * a23 - a13 * a21); out.m09 = -(a00 * (a21 * a33 - a23 * a31) - a20 * (a01 * a33 - a03 * a31) + a30 * (a01 * a23 - a03 * a21)); out.m10 = a00 * (a11 * a33 - a13 * a31) - a10 * (a01 * a33 - a03 * a31) + a30 * (a01 * a13 - a03 * a11); out.m11 = -(a00 * (a11 * a23 - a13 * a21) - a10 * (a01 * a23 - a03 * a21) + a20 * (a01 * a13 - a03 * a11)); out.m12 = -(a10 * (a21 * a32 - a22 * a31) - a20 * (a11 * a32 - a12 * a31) + a30 * (a11 * a22 - a12 * a21)); out.m13 = a00 * (a21 * a32 - a22 * a31) - a20 * (a01 * a32 - a02 * a31) + a30 * (a01 * a22 - a02 * a21); out.m14 = -(a00 * (a11 * a32 - a12 * a31) - a10 * (a01 * a32 - a02 * a31) + a30 * (a01 * a12 - a02 * a11)); out.m15 = a00 * (a11 * a22 - a12 * a21) - a10 * (a01 * a22 - a02 * a21) + a20 * (a01 * a12 - a02 * a11); return out; }; mat4.determinant = function(a) { var a00 = a.m00, a01 = a.m01, a02 = a.m02, a03 = a.m03, a10 = a.m04, a11 = a.m05, a12 = a.m06, a13 = a.m07, a20 = a.m08, a21 = a.m09, a22 = a.m10, a23 = a.m11, a30 = a.m12, a31 = a.m13, a32 = a.m14, a33 = a.m15; 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(out, a, b) { var a00 = a.m00, a01 = a.m01, a02 = a.m02, a03 = a.m03, a10 = a.m04, a11 = a.m05, a12 = a.m06, a13 = a.m07, a20 = a.m08, a21 = a.m09, a22 = a.m10, a23 = a.m11, a30 = a.m12, a31 = a.m13, a32 = a.m14, a33 = a.m15; var b0 = b.m00, b1 = b.m01, b2 = b.m02, b3 = b.m03; out.m00 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; out.m01 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; out.m02 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; out.m03 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; b0 = b.m04; b1 = b.m05; b2 = b.m06; b3 = b.m07; out.m04 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; out.m05 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; out.m06 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; out.m07 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; b0 = b.m08; b1 = b.m09; b2 = b.m10; b3 = b.m11; out.m08 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; out.m09 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; out.m10 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; out.m11 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; b0 = b.m12; b1 = b.m13; b2 = b.m14; b3 = b.m15; out.m12 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; out.m13 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; out.m14 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; out.m15 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; return out; }; mat4.mul = mat4.multiply; mat4.translate = function(out, a, v) { var x = v.x, y = v.y, z = v.z, a00, a01, a02, a03, a10, a11, a12, a13, a20, a21, a22, a23; if (a === out) { out.m12 = a.m00 * x + a.m04 * y + a.m08 * z + a.m12; out.m13 = a.m01 * x + a.m05 * y + a.m09 * z + a.m13; out.m14 = a.m02 * x + a.m06 * y + a.m10 * z + a.m14; out.m15 = a.m03 * x + a.m07 * y + a.m11 * z + a.m15; } else { a00 = a.m00; a01 = a.m01; a02 = a.m02; a03 = a.m03; a10 = a.m04; a11 = a.m05; a12 = a.m06; a13 = a.m07; a20 = a.m08; a21 = a.m09; a22 = a.m10; a23 = a.m11; out.m00 = a00; out.m01 = a01; out.m02 = a02; out.m03 = a03; out.m04 = a10; out.m05 = a11; out.m06 = a12; out.m07 = a13; out.m08 = a20; out.m09 = a21; out.m10 = a22; out.m11 = a23; out.m12 = a00 * x + a10 * y + a20 * z + a.m12; out.m13 = a01 * x + a11 * y + a21 * z + a.m13; out.m14 = a02 * x + a12 * y + a22 * z + a.m14; out.m15 = a03 * x + a13 * y + a23 * z + a.m15; } return out; }; mat4.scale = function(out, a, v) { var x = v.x, y = v.y, z = v.z; out.m00 = a.m00 * x; out.m01 = a.m01 * x; out.m02 = a.m02 * x; out.m03 = a.m03 * x; out.m04 = a.m04 * y; out.m05 = a.m05 * y; out.m06 = a.m06 * y; out.m07 = a.m07 * y; out.m08 = a.m08 * z; out.m09 = a.m09 * z; out.m10 = a.m10 * z; out.m11 = a.m11 * z; out.m12 = a.m12; out.m13 = a.m13; out.m14 = a.m14; out.m15 = a.m15; return out; }; mat4.rotate = function(out, a, rad, axis) { var x = axis.x, y = axis.y, z = axis.z; var s, c, t, a00, a01, a02, a03, a10, a11, a12, a13, a20, a21, a22, a23, b00, b01, b02, b10, b11, b12, b20, b21, b22; var len = Math.sqrt(x * x + y * y + z * z); if (Math.abs(len) < EPSILON) return null; len = 1 / len; x *= len; y *= len; z *= len; s = Math.sin(rad); c = Math.cos(rad); t = 1 - c; a00 = a.m00; a01 = a.m01; a02 = a.m02; a03 = a.m03; a10 = a.m04; a11 = a.m05; a12 = a.m06; a13 = a.m07; a20 = a.m08; a21 = a.m09; a22 = a.m10; a23 = a.m11; b00 = x * x * t + c; b01 = y * x * t + z * s; b02 = z * x * t - y * s; b10 = x * y * t - z * s; b11 = y * y * t + c; b12 = z * y * t + x * s; b20 = x * z * t + y * s; b21 = y * z * t - x * s; b22 = z * z * t + c; out.m00 = a00 * b00 + a10 * b01 + a20 * b02; out.m01 = a01 * b00 + a11 * b01 + a21 * b02; out.m02 = a02 * b00 + a12 * b01 + a22 * b02; out.m03 = a03 * b00 + a13 * b01 + a23 * b02; out.m04 = a00 * b10 + a10 * b11 + a20 * b12; out.m05 = a01 * b10 + a11 * b11 + a21 * b12; out.m06 = a02 * b10 + a12 * b11 + a22 * b12; out.m07 = a03 * b10 + a13 * b11 + a23 * b12; out.m08 = a00 * b20 + a10 * b21 + a20 * b22; out.m09 = a01 * b20 + a11 * b21 + a21 * b22; out.m10 = a02 * b20 + a12 * b21 + a22 * b22; out.m11 = a03 * b20 + a13 * b21 + a23 * b22; if (a !== out) { out.m12 = a.m12; out.m13 = a.m13; out.m14 = a.m14; out.m15 = a.m15; } return out; }; mat4.rotateX = function(out, a, rad) { var s = Math.sin(rad), c = Math.cos(rad), a10 = a.m04, a11 = a.m05, a12 = a.m06, a13 = a.m07, a20 = a.m08, a21 = a.m09, a22 = a.m10, a23 = a.m11; if (a !== out) { out.m00 = a.m00; out.m01 = a.m01; out.m02 = a.m02; out.m03 = a.m03; out.m12 = a.m12; out.m13 = a.m13; out.m14 = a.m14; out.m15 = a.m15; } out.m04 = a10 * c + a20 * s; out.m05 = a11 * c + a21 * s; out.m06 = a12 * c + a22 * s; out.m07 = a13 * c + a23 * s; out.m08 = a20 * c - a10 * s; out.m09 = a21 * c - a11 * s; out.m10 = a22 * c - a12 * s; out.m11 = a23 * c - a13 * s; return out; }; mat4.rotateY = function(out, a, rad) { var s = Math.sin(rad), c = Math.cos(rad), a00 = a.m00, a01 = a.m01, a02 = a.m02, a03 = a.m03, a20 = a.m08, a21 = a.m09, a22 = a.m10, a23 = a.m11; if (a !== out) { out.m04 = a.m04; out.m05 = a.m05; out.m06 = a.m06; out.m07 = a.m07; out.m12 = a.m12; out.m13 = a.m13; out.m14 = a.m14; out.m15 = a.m15; } out.m00 = a00 * c - a20 * s; out.m01 = a01 * c - a21 * s; out.m02 = a02 * c - a22 * s; out.m03 = a03 * c - a23 * s; out.m08 = a00 * s + a20 * c; out.m09 = a01 * s + a21 * c; out.m10 = a02 * s + a22 * c; out.m11 = a03 * s + a23 * c; return out; }; mat4.rotateZ = function(out, a, rad) { var s = Math.sin(rad), c = Math.cos(rad), a00 = a.m00, a01 = a.m01, a02 = a.m02, a03 = a.m03, a10 = a.m04, a11 = a.m05, a12 = a.m06, a13 = a.m07; if (a !== out) { out.m08 = a.m08; out.m09 = a.m09; out.m10 = a.m10; out.m11 = a.m11; out.m12 = a.m12; out.m13 = a.m13; out.m14 = a.m14; out.m15 = a.m15; } out.m00 = a00 * c + a10 * s; out.m01 = a01 * c + a11 * s; out.m02 = a02 * c + a12 * s; out.m03 = a03 * c + a13 * s; out.m04 = a10 * c - a00 * s; out.m05 = a11 * c - a01 * s; out.m06 = a12 * c - a02 * s; out.m07 = a13 * c - a03 * s; return out; }; mat4.fromTranslation = function(out, v) { out.m00 = 1; out.m01 = 0; out.m02 = 0; out.m03 = 0; out.m04 = 0; out.m05 = 1; out.m06 = 0; out.m07 = 0; out.m08 = 0; out.m09 = 0; out.m10 = 1; out.m11 = 0; out.m12 = v.x; out.m13 = v.y; out.m14 = v.z; out.m15 = 1; return out; }; mat4.fromScaling = function(out, v) { out.m00 = v.x; out.m01 = 0; out.m02 = 0; out.m03 = 0; out.m04 = 0; out.m05 = v.y; out.m06 = 0; out.m07 = 0; out.m08 = 0; out.m09 = 0; out.m10 = v.z; out.m11 = 0; out.m12 = 0; out.m13 = 0; out.m14 = 0; out.m15 = 1; return out; }; mat4.fromRotation = function(out, rad, axis) { var x = axis.x, y = axis.y, z = axis.z; var len = Math.sqrt(x * x + y * y + z * z); var s, c, t; if (Math.abs(len) < EPSILON) return null; len = 1 / len; x *= len; y *= len; z *= len; s = Math.sin(rad); c = Math.cos(rad); t = 1 - c; out.m00 = x * x * t + c; out.m01 = y * x * t + z * s; out.m02 = z * x * t - y * s; out.m03 = 0; out.m04 = x * y * t - z * s; out.m05 = y * y * t + c; out.m06 = z * y * t + x * s; out.m07 = 0; out.m08 = x * z * t + y * s; out.m09 = y * z * t - x * s; out.m10 = z * z * t + c; out.m11 = 0; out.m12 = 0; out.m13 = 0; out.m14 = 0; out.m15 = 1; return out; }; mat4.fromXRotation = function(out, rad) { var s = Math.sin(rad), c = Math.cos(rad); out.m00 = 1; out.m01 = 0; out.m02 = 0; out.m03 = 0; out.m04 = 0; out.m05 = c; out.m06 = s; out.m07 = 0; out.m08 = 0; out.m09 = -s; out.m10 = c; out.m11 = 0; out.m12 = 0; out.m13 = 0; out.m14 = 0; out.m15 = 1; return out; }; mat4.fromYRotation = function(out, rad) { var s = Math.sin(rad), c = Math.cos(rad); out.m00 = c; out.m01 = 0; out.m02 = -s; out.m03 = 0; out.m04 = 0; out.m05 = 1; out.m06 = 0; out.m07 = 0; out.m08 = s; out.m09 = 0; out.m10 = c; out.m11 = 0; out.m12 = 0; out.m13 = 0; out.m14 = 0; out.m15 = 1; return out; }; mat4.fromZRotation = function(out, rad) { var s = Math.sin(rad), c = Math.cos(rad); out.m00 = c; out.m01 = s; out.m02 = 0; out.m03 = 0; out.m04 = -s; out.m05 = c; out.m06 = 0; out.m07 = 0; out.m08 = 0; out.m09 = 0; out.m10 = 1; out.m11 = 0; out.m12 = 0; out.m13 = 0; out.m14 = 0; out.m15 = 1; return out; }; mat4.fromRT = function(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; out.m00 = 1 - (yy + zz); out.m01 = xy + wz; out.m02 = xz - wy; out.m03 = 0; out.m04 = xy - wz; out.m05 = 1 - (xx + zz); out.m06 = yz + wx; out.m07 = 0; out.m08 = xz + wy; out.m09 = yz - wx; out.m10 = 1 - (xx + yy); out.m11 = 0; out.m12 = v.x; out.m13 = v.y; out.m14 = v.z; out.m15 = 1; return out; }; mat4.getTranslation = function(out, mat) { out.x = mat.m12; out.y = mat.m13; out.z = mat.m14; return out; }; mat4.getScaling = function(out, mat) { var m11 = mat.m00, m12 = mat.m01, m13 = mat.m02, m21 = mat.m04, m22 = mat.m05, m23 = mat.m06, m31 = mat.m08, m32 = mat.m09, m33 = mat.m10; out.x = Math.sqrt(m11 * m11 + m12 * m12 + m13 * m13); out.y = Math.sqrt(m21 * m21 + m22 * m22 + m23 * m23); out.z = Math.sqrt(m31 * m31 + m32 * m32 + m33 * m33); return out; }; mat4.getRotation = function(out, mat) { var trace = mat.m00 + mat.m05 + mat.m10; var S = 0; if (trace > 0) { S = 2 * Math.sqrt(trace + 1); out.w = .25 * S; out.x = (mat.m06 - mat.m09) / S; out.y = (mat.m08 - mat.m02) / S; out.z = (mat.m01 - mat.m04) / S; } else if (mat.m00 > mat.m05 & mat.m00 > mat.m10) { S = 2 * Math.sqrt(1 + mat.m00 - mat.m05 - mat.m10); out.w = (mat.m06 - mat.m09) / S; out.x = .25 * S; out.y = (mat.m01 + mat.m04) / S; out.z = (mat.m08 + mat.m02) / S; } else if (mat.m05 > mat.m10) { S = 2 * Math.sqrt(1 + mat.m05 - mat.m00 - mat.m10); out.w = (mat.m08 - mat.m02) / S; out.x = (mat.m01 + mat.m04) / S; out.y = .25 * S; out.z = (mat.m06 + mat.m09) / S; } else { S = 2 * Math.sqrt(1 + mat.m10 - mat.m00 - mat.m05); out.w = (mat.m01 - mat.m04) / S; out.x = (mat.m08 + mat.m02) / S; out.y = (mat.m06 + mat.m09) / S; out.z = .25 * S; } return out; }; mat4.fromRTS = function(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; out.m00 = (1 - (yy + zz)) * sx; out.m01 = (xy + wz) * sx; out.m02 = (xz - wy) * sx; out.m03 = 0; out.m04 = (xy - wz) * sy; out.m05 = (1 - (xx + zz)) * sy; out.m06 = (yz + wx) * sy; out.m07 = 0; out.m08 = (xz + wy) * sz; out.m09 = (yz - wx) * sz; out.m10 = (1 - (xx + yy)) * sz; out.m11 = 0; out.m12 = v.x; out.m13 = v.y; out.m14 = v.z; out.m15 = 1; return out; }; mat4.fromRTSOrigin = function(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; out.m00 = (1 - (yy + zz)) * sx; out.m01 = (xy + wz) * sx; out.m02 = (xz - wy) * sx; out.m03 = 0; out.m04 = (xy - wz) * sy; out.m05 = (1 - (xx + zz)) * sy; out.m06 = (yz + wx) * sy; out.m07 = 0; out.m08 = (xz + wy) * sz; out.m09 = (yz - wx) * sz; out.m10 = (1 - (xx + yy)) * sz; out.m11 = 0; out.m12 = v.x + ox - (out.m00 * ox + out.m04 * oy + out.m08 * oz); out.m13 = v.y + oy - (out.m01 * ox + out.m05 * oy + out.m09 * oz); out.m14 = v.z + oz - (out.m02 * ox + out.m06 * oy + out.m10 * oz); out.m15 = 1; return out; }; mat4.fromQuat = function(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; out.m00 = 1 - yy - zz; out.m01 = yx + wz; out.m02 = zx - wy; out.m03 = 0; out.m04 = yx - wz; out.m05 = 1 - xx - zz; out.m06 = zy + wx; out.m07 = 0; out.m08 = zx + wy; out.m09 = zy - wx; out.m10 = 1 - xx - yy; out.m11 = 0; out.m12 = 0; out.m13 = 0; out.m14 = 0; out.m15 = 1; return out; }; mat4.frustum = function(out, left, right, bottom, top, near, far) { var rl = 1 / (right - left); var tb = 1 / (top - bottom); var nf = 1 / (near - far); out.m00 = 2 * near * rl; out.m01 = 0; out.m02 = 0; out.m03 = 0; out.m04 = 0; out.m05 = 2 * near * tb; out.m06 = 0; out.m07 = 0; out.m08 = (right + left) * rl; out.m09 = (top + bottom) * tb; out.m10 = (far + near) * nf; out.m11 = -1; out.m12 = 0; out.m13 = 0; out.m14 = far * near * 2 * nf; out.m15 = 0; return out; }; mat4.perspective = function(out, fovy, aspect, near, far) { var f = 1 / Math.tan(fovy / 2); var nf = 1 / (near - far); out.m00 = f / aspect; out.m01 = 0; out.m02 = 0; out.m03 = 0; out.m04 = 0; out.m05 = f; out.m06 = 0; out.m07 = 0; out.m08 = 0; out.m09 = 0; out.m10 = (far + near) * nf; out.m11 = -1; out.m12 = 0; out.m13 = 0; out.m14 = 2 * far * near * nf; out.m15 = 0; return out; }; mat4.perspectiveFromFieldOfView = function(out, fov, near, far) { var upTan = Math.tan(fov.upDegrees * Math.PI / 180); var downTan = Math.tan(fov.downDegrees * Math.PI / 180); var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180); var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180); var xScale = 2 / (leftTan + rightTan); var yScale = 2 / (upTan + downTan); out.m00 = xScale; out.m01 = 0; out.m02 = 0; out.m03 = 0; out.m04 = 0; out.m05 = yScale; out.m06 = 0; out.m07 = 0; out.m08 = -(leftTan - rightTan) * xScale * .5; out.m09 = (upTan - downTan) * yScale * .5; out.m10 = far / (near - far); out.m11 = -1; out.m12 = 0; out.m13 = 0; out.m14 = far * near / (near - far); out.m15 = 0; return out; }; mat4.ortho = function(out, left, right, bottom, top, near, far) { var lr = 1 / (left - right); var bt = 1 / (bottom - top); var nf = 1 / (near - far); out.m00 = -2 * lr; out.m01 = 0; out.m02 = 0; out.m03 = 0; out.m04 = 0; out.m05 = -2 * bt; out.m06 = 0; out.m07 = 0; out.m08 = 0; out.m09 = 0; out.m10 = 2 * nf; out.m11 = 0; out.m12 = (left + right) * lr; out.m13 = (top + bottom) * bt; out.m14 = (far + near) * nf; out.m15 = 1; return out; }; mat4.lookAt = function(out, eye, center, up) { var x0, x1, x2, y0, y1, y2, z0, z1, z2, len; 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; if (Math.abs(eyex - centerx) < EPSILON && Math.abs(eyey - centery) < EPSILON && Math.abs(eyez - centerz) < EPSILON) return mat4.identity(out); z0 = eyex - centerx; z1 = eyey - centery; z2 = eyez - centerz; len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2); z0 *= len; z1 *= len; z2 *= len; x0 = upy * z2 - upz * z1; x1 = upz * z0 - upx * z2; x2 = upx * z1 - upy * z0; len = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2); if (len) { len = 1 / len; x0 *= len; x1 *= len; x2 *= len; } else { x0 = 0; x1 = 0; x2 = 0; } y0 = z1 * x2 - z2 * x1; y1 = z2 * x0 - z0 * x2; y2 = z0 * x1 - z1 * x0; len = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2); if (len) { len = 1 / len; y0 *= len; y1 *= len; y2 *= len; } else { y0 = 0; y1 = 0; y2 = 0; } out.m00 = x0; out.m01 = y0; out.m02 = z0; out.m03 = 0; out.m04 = x1; out.m05 = y1; out.m06 = z1; out.m07 = 0; out.m08 = x2; out.m09 = y2; out.m10 = z2; out.m11 = 0; out.m12 = -(x0 * eyex + x1 * eyey + x2 * eyez); out.m13 = -(y0 * eyex + y1 * eyey + y2 * eyez); out.m14 = -(z0 * eyex + z1 * eyey + z2 * eyez); out.m15 = 1; return out; }; mat4.str = function(a) { return "mat4(" + a.m00 + ", " + a.m01 + ", " + a.m02 + ", " + a.m03 + ", " + a.m04 + ", " + a.m05 + ", " + a.m06 + ", " + a.m07 + ", " + a.m08 + ", " + a.m09 + ", " + a.m10 + ", " + a.m11 + ", " + a.m12 + ", " + a.m13 + ", " + a.m14 + ", " + a.m15 + ")"; }; mat4.array = function(out, m) { out[0] = m.m00; out[1] = m.m01; out[2] = m.m02; out[3] = m.m03; out[4] = m.m04; out[5] = m.m05; out[6] = m.m06; out[7] = m.m07; out[8] = m.m08; out[9] = m.m09; out[10] = m.m10; out[11] = m.m11; out[12] = m.m12; out[13] = m.m13; out[14] = m.m14; out[15] = m.m15; return out; }; mat4.frob = function(a) { return Math.sqrt(Math.pow(a.m00, 2) + Math.pow(a.m01, 2) + Math.pow(a.m02, 2) + Math.pow(a.m03, 2) + Math.pow(a.m04, 2) + Math.pow(a.m05, 2) + Math.pow(a.m06, 2) + Math.pow(a.m07, 2) + Math.pow(a.m08, 2) + Math.pow(a.m09, 2) + Math.pow(a.m10, 2) + Math.pow(a.m11, 2) + Math.pow(a.m12, 2) + Math.pow(a.m13, 2) + Math.pow(a.m14, 2) + Math.pow(a.m15, 2)); }; mat4.add = function(out, a, b) { out.m00 = a.m00 + b.m00; out.m01 = a.m01 + b.m01; out.m02 = a.m02 + b.m02; out.m03 = a.m03 + b.m03; out.m04 = a.m04 + b.m04; out.m05 = a.m05 + b.m05; out.m06 = a.m06 + b.m06; out.m07 = a.m07 + b.m07; out.m08 = a.m08 + b.m08; out.m09 = a.m09 + b.m09; out.m10 = a.m10 + b.m10; out.m11 = a.m11 + b.m11; out.m12 = a.m12 + b.m12; out.m13 = a.m13 + b.m13; out.m14 = a.m14 + b.m14; out.m15 = a.m15 + b.m15; return out; }; mat4.subtract = function(out, a, b) { out.m00 = a.m00 - b.m00; out.m01 = a.m01 - b.m01; out.m02 = a.m02 - b.m02; out.m03 = a.m03 - b.m03; out.m04 = a.m04 - b.m04; out.m05 = a.m05 - b.m05; out.m06 = a.m06 - b.m06; out.m07 = a.m07 - b.m07; out.m08 = a.m08 - b.m08; out.m09 = a.m09 - b.m09; out.m10 = a.m10 - b.m10; out.m11 = a.m11 - b.m11; out.m12 = a.m12 - b.m12; out.m13 = a.m13 - b.m13; out.m14 = a.m14 - b.m14; out.m15 = a.m15 - b.m15; return out; }; mat4.sub = mat4.subtract; mat4.multiplyScalar = function(out, a, b) { out.m00 = a.m00 * b; out.m01 = a.m01 * b; out.m02 = a.m02 * b; out.m03 = a.m03 * b; out.m04 = a.m04 * b; out.m05 = a.m05 * b; out.m06 = a.m06 * b; out.m07 = a.m07 * b; out.m08 = a.m08 * b; out.m09 = a.m09 * b; out.m10 = a.m10 * b; out.m11 = a.m11 * b; out.m12 = a.m12 * b; out.m13 = a.m13 * b; out.m14 = a.m14 * b; out.m15 = a.m15 * b; return out; }; mat4.multiplyScalarAndAdd = function(out, a, b, scale) { out.m00 = a.m00 + b.m00 * scale; out.m01 = a.m01 + b.m01 * scale; out.m02 = a.m02 + b.m02 * scale; out.m03 = a.m03 + b.m03 * scale; out.m04 = a.m04 + b.m04 * scale; out.m05 = a.m05 + b.m05 * scale; out.m06 = a.m06 + b.m06 * scale; out.m07 = a.m07 + b.m07 * scale; out.m08 = a.m08 + b.m08 * scale; out.m09 = a.m09 + b.m09 * scale; out.m10 = a.m10 + b.m10 * scale; out.m11 = a.m11 + b.m11 * scale; out.m12 = a.m12 + b.m12 * scale; out.m13 = a.m13 + b.m13 * scale; out.m14 = a.m14 + b.m14 * scale; out.m15 = a.m15 + b.m15 * scale; return out; }; mat4.exactEquals = function(a, b) { return a.m00 === b.m00 && a.m01 === b.m01 && a.m02 === b.m02 && a.m03 === b.m03 && a.m04 === b.m04 && a.m05 === b.m05 && a.m06 === b.m06 && a.m07 === b.m07 && a.m08 === b.m08 && a.m09 === b.m09 && a.m10 === b.m10 && a.m11 === b.m11 && a.m12 === b.m12 && a.m13 === b.m13 && a.m14 === b.m14 && a.m15 === b.m15; }; mat4.equals = function(a, b) { var a0 = a.m00, a1 = a.m01, a2 = a.m02, a3 = a.m03, a4 = a.m04, a5 = a.m05, a6 = a.m06, a7 = a.m07, a8 = a.m08, a9 = a.m09, a10 = a.m10, a11 = a.m11, a12 = a.m12, a13 = a.m13, a14 = a.m14, a15 = a.m15; var b0 = b.m00, b1 = b.m01, b2 = b.m02, b3 = b.m03, b4 = b.m04, b5 = b.m05, b6 = b.m06, b7 = b.m07, b8 = b.m08, b9 = b.m09, b10 = b.m10, b11 = b.m11, b12 = b.m12, b13 = b.m13, b14 = b.m14, b15 = b.m15; 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)) && Math.abs(a3 - b3) <= EPSILON * Math.max(1, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= EPSILON * Math.max(1, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= EPSILON * Math.max(1, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= EPSILON * Math.max(1, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= EPSILON * Math.max(1, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= EPSILON * Math.max(1, Math.abs(a8), Math.abs(b8)) && Math.abs(a9 - b9) <= EPSILON * Math.max(1, Math.abs(a9), Math.abs(b9)) && Math.abs(a10 - b10) <= EPSILON * Math.max(1, Math.abs(a10), Math.abs(b10)) && Math.abs(a11 - b11) <= EPSILON * Math.max(1, Math.abs(a11), Math.abs(b11)) && Math.abs(a12 - b12) <= EPSILON * Math.max(1, Math.abs(a12), Math.abs(b12)) && Math.abs(a13 - b13) <= EPSILON * Math.max(1, Math.abs(a13), Math.abs(b13)) && Math.abs(a14 - b14) <= EPSILON * Math.max(1, Math.abs(a14), Math.abs(b14)) && Math.abs(a15 - b15) <= EPSILON * Math.max(1, Math.abs(a15), Math.abs(b15)); }; var _tmp$8 = new Array(3); var _color3 = function _color3(r, g, b) { this.r = r; this.g = g; this.b = b; }; _color3.prototype.toJSON = function toJSON() { _tmp$8[0] = this.r; _tmp$8[1] = this.g; _tmp$8[2] = this.b; return _tmp$8; }; var color3 = {}; color3.create = function() { return new _color3(1, 1, 1); }; color3.new = function(r, g, b) { return new _color3(r, g, b); }; color3.clone = function(a) { return new _color3(a.r, a.g, a.b, a.a); }; color3.copy = function(out, a) { out.r = a.r; out.g = a.g; out.b = a.b; return out; }; color3.set = function(out, r, g, b) { out.r = r; out.g = g; out.b = b; return out; }; color3.fromHex = function(out, hex) { var r = (hex >> 16) / 255; var g = (hex >> 8 & 255) / 255; var b = (255 & hex) / 255; out.r = r; out.g = g; out.b = b; return out; }; color3.add = function(out, a, b) { out.r = a.r + b.r; out.g = a.g + b.g; out.b = a.b + b.b; return out; }; color3.subtract = function(out, a, b) { out.r = a.r - b.r; out.g = a.g - b.g; out.b = a.b - b.b; return out; }; color3.sub = color3.subtract; color3.multiply = function(out, a, b) { out.r = a.r * b.r; out.g = a.g * b.g; out.b = a.b * b.b; return out; }; color3.mul = color3.multiply; color3.divide = function(out, a, b) { out.r = a.r / b.r; out.g = a.g / b.g; out.b = a.b / b.b; return out; }; color3.div = color3.divide; color3.scale = function(out, a, b) { out.r = a.r * b; out.g = a.g * b; out.b = a.b * b; return out; }; color3.lerp = function(out, a, b, t) { var ar = a.r, ag = a.g, ab = a.b; out.r = ar + t * (b.r - ar); out.g = ag + t * (b.g - ag); out.b = ab + t * (b.b - ab); return out; }; color3.str = function(a) { return "color3(" + a.r + ", " + a.g + ", " + a.b + ")"; }; color3.array = function(out, a) { out[0] = a.r; out[1] = a.g; out[2] = a.b; return out; }; color3.exactEquals = function(a, b) { return a.r === b.r && a.g === b.g && a.b === b.b; }; color3.equals = function(a, b) { var a0 = a.r, a1 = a.g, a2 = a.b; var b0 = b.r, b1 = b.g, b2 = b.b; 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)); }; color3.hex = function(a) { return 255 * a.r << 16 | 255 * a.g << 8 | 255 * a.b; }; var _tmp$9 = new Array(4); var _color4 = function _color4(r, g, b, a) { this.r = r; this.g = g; this.b = b; this.a = a; }; _color4.prototype.toJSON = function toJSON() { _tmp$9[0] = this.r; _tmp$9[1] = this.g; _tmp$9[2] = this.b; _tmp$9[3] = this.a; return _tmp$9; }; var color4 = {}; color4.create = function() { return new _color4(1, 1, 1, 1); }; color4.new = function(r, g, b, a) { return new _color4(r, g, b, a); }; color4.clone = function(a) { return new _color4(a.r, a.g, a.b, a.a); }; color4.copy = function(out, a) { out.r = a.r; out.g = a.g; out.b = a.b; out.a = a.a; return out; }; color4.set = function(out, r, g, b, a) { out.r = r; out.g = g; out.b = b; out.a = a; return out; }; color4.fromHex = function(out, hex) { var r = (hex >> 24) / 255; var g = (hex >> 16 & 255) / 255; var b = (hex >> 8 & 255) / 255; var a = (255 & hex) / 255; out.r = r; out.g = g; out.b = b; out.a = a; return out; }; color4.add = function(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; }; color4.subtract = function(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; }; color4.sub = color4.subtract; color4.multiply = function(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; }; color4.mul = color4.multiply; color4.divide = function(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; }; color4.div = color4.divide; color4.scale = function(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; }; color4.lerp = function(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; }; color4.str = function(a) { return "color4(" + a.r + ", " + a.g + ", " + a.b + ", " + a.a + ")"; }; color4.array = function(out, a) { out[0] = a.r; out[1] = a.g; out[2] = a.b; out[3] = a.a; return out; }; color4.exactEquals = function(a, b) { return a.r === b.r && a.g === b.g && a.b === b.b && a.a === b.a; }; color4.equals = function(a, b) { var a0 = a.r, a1 = a.g, a2 = a.b, a3 = a.a; var b0 = b.r, b1 = b.g, b2 = b.b, b3 = b.a; 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)) && Math.abs(a3 - b3) <= EPSILON * Math.max(1, Math.abs(a3), Math.abs(b3)); }; color4.hex = function(a) { return (255 * a.r << 24 | 255 * a.g << 16 | 255 * a.b << 8 | 255 * a.a) >>> 0; }; var bits = bits_; var math = Object.freeze({ bits: bits, vec2: vec2, vec3: vec3, vec4: vec4, quat: quat, mat2: mat2, mat23: mat23, mat3: mat3, mat4: mat4, color3: color3, color4: color4, EPSILON: EPSILON, equals: equals, approx: approx, clamp: clamp, clamp01: clamp01, lerp: lerp, toRadian: toRadian, toDegree: toDegree, random: random, randomRange: randomRange, randomRangeInt: randomRangeInt, nextPow2: nextPow2 }); var enums = { PROJ_PERSPECTIVE: 0, PROJ_ORTHO: 1, LIGHT_DIRECTIONAL: 0, LIGHT_POINT: 1, LIGHT_SPOT: 2, SHADOW_NONE: 0, SHADOW_HARD: 1, SHADOW_SOFT: 2, PARAM_INT: 0, PARAM_INT2: 1, PARAM_INT3: 2, PARAM_INT4: 3, PARAM_FLOAT: 4, PARAM_FLOAT2: 5, PARAM_FLOAT3: 6, PARAM_FLOAT4: 7, PARAM_COLOR3: 8, PARAM_COLOR4: 9, PARAM_MAT2: 10, PARAM_MAT3: 11, PARAM_MAT4: 12, PARAM_TEXTURE_2D: 13, PARAM_TEXTURE_CUBE: 14, CLEAR_COLOR: 1, CLEAR_DEPTH: 2, CLEAR_STENCIL: 4 }; 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 _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: null, internalFormat: null, pixelType: null } ]; var enums$1 = { 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, 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_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 }; function attrTypeBytes(attrType) { if (attrType === enums$1.ATTR_TYPE_INT8) return 1; if (attrType === enums$1.ATTR_TYPE_UINT8) return 1; if (attrType === enums$1.ATTR_TYPE_INT16) return 2; if (attrType === enums$1.ATTR_TYPE_UINT16) return 2; if (attrType === enums$1.ATTR_TYPE_INT32) return 4; if (attrType === enums$1.ATTR_TYPE_UINT32) return 4; if (attrType === enums$1.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$1.TEXTURE_FMT_RGBA8]; } return result; } var VertexFormat = function VertexFormat(infos) { var this$1 = this; this._attr2el = {}; this._elements = []; this._bytes = 0; var offset = 0; for (var i = 0, len = infos.length; i < len; ++i) { var info = infos[i]; var el = { name: info.name, offset: offset, stride: 0, stream: -1, type: info.type, num: info.num, normalize: void 0 !== info.normalize && info.normalize, bytes: info.num * attrTypeBytes(info.type) }; this$1._attr2el[el.name] = el; this$1._elements.push(el); this$1._bytes += el.bytes; offset += el.bytes; } for (var i$1 = 0, len$1 = this._elements.length; i$1 < len$1; ++i$1) { var el$1 = this$1._elements[i$1]; el$1.stride = this$1._bytes; } }; VertexFormat.prototype.element = function element(attrName) { return this._attr2el[attrName]; }; var IndexBuffer = function IndexBuffer(device, format, usage, data, numIndices) { this._device = device; this._format = format; this._usage = usage; this._numIndices = numIndices; this._bytesPerIndex = 0; format === enums$1.INDEX_FMT_UINT8 ? this._bytesPerIndex = 1 : format === enums$1.INDEX_FMT_UINT16 ? this._bytesPerIndex = 2 : format === enums$1.INDEX_FMT_UINT32 && (this._bytesPerIndex = 4); this._bytes = this._bytesPerIndex * numIndices; this._glID = device._gl.createBuffer(); this.update(0, data); device._stats.ib += this._bytes; }; var prototypeAccessors = { count: { configurable: true } }; IndexBuffer.prototype.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; }; IndexBuffer.prototype.update = function update(offset, data) { if (-1 === this._glID) { console.error("The buffer is destroyed"); return; } if (data && data.byteLength + offset > this._bytes) { console.error("Failed to update data, bytes exceed."); return; } var gl = this._device._gl; var glUsage = this._usage; gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._glID); data ? offset ? gl.bufferSubData(gl.ELEMENT_ARRAY_BUFFER, offset, data) : gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, data, glUsage) : this._bytes ? gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this._bytes, glUsage) : console.warn("bufferData should not submit 0 bytes data"); this._device._restoreIndexBuffer(); }; prototypeAccessors.count.get = function() { return this._numIndices; }; Object.defineProperties(IndexBuffer.prototype, prototypeAccessors); var VertexBuffer = function VertexBuffer(device, format, usage, data, numVertices) { this._device = device; this._format = format; this._usage = usage; this._numVertices = numVertices; this._bytes = this._format._bytes * numVertices; this._glID = device._gl.createBuffer(); this.update(0, data); device._stats.vb += this._bytes; }; var prototypeAccessors$1 = { count: { configurable: true } }; VertexBuffer.prototype.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; }; VertexBuffer.prototype.update = function update(offset, data) { if (-1 === this._glID) { console.error("The buffer is destroyed"); return; } if (data && data.byteLength + offset > this._bytes) { console.error("Failed to update data, bytes exceed."); return; } var gl = this._device._gl; var glUsage = this._usage; gl.bindBuffer(gl.ARRAY_BUFFER, this._glID); data ? offset ? gl.bufferSubData(gl.ARRAY_BUFFER, offset, data) : gl.bufferData(gl.ARRAY_BUFFER, data, glUsage) : this._bytes ? gl.bufferData(gl.ARRAY_BUFFER, this._bytes, glUsage) : console.warn("bufferData should not submit 0 bytes data"); gl.bindBuffer(gl.ARRAY_BUFFER, null); }; prototypeAccessors$1.count.get = function() { return this._numVertices; }; Object.defineProperties(VertexBuffer.prototype, prototypeAccessors$1); var _genID = 0; function _parseError(out, type, errorLog) { 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 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 prototypeAccessors$2 = { id: { configurable: true } }; prototypeAccessors$2.id.get = function() { return this._id; }; Program.prototype.link = function link() { var this$1 = this; 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) { errors.forEach((function(err) { console.error("Failed to compile " + err.type + " " + err.fileID + " (ln " + err.line + "): " + err.message); })); return; } if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { console.error("Failed to link shader program: " + gl.getProgramInfoLog(program)); failed = true; } if (failed) return; this._glID = program; 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$1._attributes.push({ name: info.name, location: location, type: info.type }); } var numUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); for (var i$1 = 0; i$1 < numUniforms; ++i$1) { var info$1 = gl.getActiveUniform(program, i$1); var name = info$1.name; var location$1 = gl.getUniformLocation(program, name); var isArray = "[0]" === name.substr(name.length - 3); isArray && (name = name.substr(0, name.length - 3)); this$1._uniforms.push({ name: name, location: location$1, type: info$1.type, size: isArray ? info$1.size : void 0 }); } this._linked = true; }; Program.prototype.destroy = function destroy() { var gl = this._device._gl; gl.deleteProgram(this._glID); this._linked = false; this._glID = null; this._attributes = []; this._uniforms = []; this._samplers = []; }; Object.defineProperties(Program.prototype, prototypeAccessors$2); function _createShader(gl, type, src) { var shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); return shader; } var Texture = function Texture(device) { this._device = device; this._width = 4; this._height = 4; this._hasMipmap = false; this._compressed = false; this._anisotropy = 1; this._minFilter = enums$1.FILTER_LINEAR; this._magFilter = enums$1.FILTER_LINEAR; this._mipFilter = enums$1.FILTER_LINEAR; this._wrapS = enums$1.WRAP_REPEAT; this._wrapT = enums$1.WRAP_REPEAT; this._format = enums$1.TEXTURE_FMT_RGBA8; this._target = -1; }; Texture.prototype.destroy = function destroy() { if (-1 === this._glID) { console.error("The texture already destroyed"); return; } var gl = this._device._gl; gl.deleteTexture(this._glID); this._device._stats.tex -= this.bytes; this._glID = -1; }; function isPow2$1(v) { return !(v & v - 1) && !!v; } var Texture2D = (function(Texture$$1) { function Texture2D(device, options) { Texture$$1.call(this, device); var gl = this._device._gl; this._target = gl.TEXTURE_2D; this._glID = gl.createTexture(); options.images = options.images || [ null ]; this.update(options); } Texture$$1 && (Texture2D.__proto__ = Texture$$1); Texture2D.prototype = Object.create(Texture$$1 && Texture$$1.prototype); Texture2D.prototype.constructor = Texture2D; Texture2D.prototype.update = function update(options) { var gl = this._device._gl; var genMipmap = this._hasMipmap; 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$1.TEXTURE_FMT_RGB_DXT1 && this._format <= enums$1.TEXTURE_FMT_RGBA_PVRTC_4BPPV1; } if (void 0 !== options.mipmap) { this._hasMipmap = options.mipmap; genMipmap = options.mipmap; } if (void 0 !== options.images && options.images.length > 1) { genMipmap = 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 = isPow2$1(this._width) && isPow2$1(this._height); pot || (genMipmap = false); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, this._glID); void 0 !== options.images && options.images.length > 0 && this._setMipmap(options.images, options.flipY, options.premultiplyAlpha); this._setTexInfo(); if (genMipmap) { gl.hint(gl.GENERATE_MIPMAP_HINT, gl.NICEST); gl.generateMipmap(gl.TEXTURE_2D); } this._device._restoreTexture(0); }; Texture2D.prototype.updateSubImage = function updateSubImage(options) { var gl = this._device._gl; var glFmt = glTextureFmt(this._format); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, this._glID); this._setSubImage(glFmt, options); this._device._restoreTexture(0); }; Texture2D.prototype.updateImage = function updateImage(options) { var gl = this._device._gl; var glFmt = glTextureFmt(this._format); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, this._glID); this._setImage(glFmt, options); this._device._restoreTexture(0); }; Texture2D.prototype._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); } }; Texture2D.prototype._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); } }; Texture2D.prototype._setMipmap = function _setMipmap(images, flipY, premultiplyAlpha) { var this$1 = this; var glFmt = 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$1._width >> i; options.height = this$1._height >> i; options.image = images[i]; this$1._setImage(glFmt, options); } }; Texture2D.prototype._setTexInfo = function _setTexInfo() { var gl = this._device._gl; var pot = isPow2$1(this._width) && isPow2$1(this._height); if (!pot && (this._wrapS !== enums$1.WRAP_CLAMP || this._wrapT !== enums$1.WRAP_CLAMP)) { console.warn("WebGL1 doesn't support all wrap modes with NPOT textures"); this._wrapS = enums$1.WRAP_CLAMP; this._wrapT = enums$1.WRAP_CLAMP; } var mipFilter = this._hasMipmap ? 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, glFilter(gl, this._minFilter, mipFilter)); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, glFilter(gl, this._magFilter, -1)); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, this._wrapS); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, this._wrapT); var ext = this._device.ext("EXT_texture_filter_anisotropic"); ext && ext.TEXTURE_MAX_ANISOTROPY_EXT && gl.texParameteri(gl.TEXTURE_2D, ext.TEXTURE_MAX_ANISOTROPY_EXT, this._anisotropy); }; return Texture2D; })(Texture); var TextureCube = (function(Texture$$1) { function TextureCube(device, options) { Texture$$1.call(this, device); var gl = this._device._gl; this._target = gl.TEXTURE_CUBE_MAP; this._glID = gl.createTexture(); this.update(options); } Texture$$1 && (TextureCube.__proto__ = Texture$$1); TextureCube.prototype = Object.create(Texture$$1 && Texture$$1.prototype); TextureCube.prototype.constructor = TextureCube; TextureCube.prototype.update = function update(options) { var gl = this._device._gl; var genMipmap = this._hasMipmap; 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$1.TEXTURE_FMT_RGB_DXT1 && this._format <= enums$1.TEXTURE_FMT_RGBA_PVRTC_4BPPV1; } if (void 0 !== options.mipmap) { this._hasMipmap = options.mipmap; genMipmap = options.mipmap; } if (void 0 !== options.images && options.images.length > 1) { genMipmap = 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 = isPow2$1(this._width) && isPow2$1(this._height); pot || (genMipmap = false); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_CUBE_MAP, this._glID); void 0 !== options.images && options.images.length > 0 && this._setMipmap(options.images, options.flipY, options.premultiplyAlpha); this._setTexInfo(); if (genMipmap) { gl.hint(gl.GENERATE_MIPMAP_HINT, gl.NICEST); gl.generateMipmap(gl.TEXTURE_CUBE_MAP); } this._device._restoreTexture(0); }; TextureCube.prototype.updateSubImage = function updateSubImage(options) { var gl = this._device._gl; var glFmt = glTextureFmt(this._format); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_CUBE_MAP, this._glID); this._setSubImage(glFmt, options); this._device._restoreTexture(0); }; TextureCube.prototype.updateImage = function updateImage(options) { var gl = this._device._gl; var glFmt = glTextureFmt(this._format); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_CUBE_MAP, this._glID); this._setImage(glFmt, options); this._device._restoreTexture(0); }; TextureCube.prototype._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); }; TextureCube.prototype._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); }; TextureCube.prototype._setMipmap = function _setMipmap(images, flipY, premultiplyAlpha) { var this$1 = this; var glFmt = 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$1._width >> i; options.height = this$1._height >> i; for (var face = 0; face < 6; ++face) { options.faceIndex = face; options.image = levelImages[face]; this$1._setImage(glFmt, options); } } }; TextureCube.prototype._setTexInfo = function _setTexInfo() { var gl = this._device._gl; var pot = isPow2$1(this._width) && isPow2$1(this._height); if (!pot && (this._wrapS !== enums$1.WRAP_CLAMP || this._wrapT !== enums$1.WRAP_CLAMP)) { console.warn("WebGL1 doesn't support all wrap modes with NPOT textures"); this._wrapS = enums$1.WRAP_CLAMP; this._wrapT = enums$1.WRAP_CLAMP; } var mipFilter = this._hasMipmap ? 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, glFilter(gl, this._minFilter, mipFilter)); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, glFilter(gl, this._magFilter, -1)); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, this._wrapS); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, this._wrapT); var ext = this._device.ext("EXT_texture_filter_anisotropic"); ext && ext.TEXTURE_MAX_ANISOTROPY_EXT && gl.texParameteri(gl.TEXTURE_CUBE_MAP, ext.TEXTURE_MAX_ANISOTROPY_EXT, this._anisotropy); }; return TextureCube; })(Texture); var RenderBuffer = function RenderBuffer(device, format, width, height) { this._device = device; this._format = format; this._width = width; this._height = height; var gl = device._gl; this._glID = gl.createRenderbuffer(); gl.bindRenderbuffer(gl.RENDERBUFFER, this._glID); gl.renderbufferStorage(gl.RENDERBUFFER, format, width, height); gl.bindRenderbuffer(gl.RENDERBUFFER, null); }; RenderBuffer.prototype.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; }; var FrameBuffer = 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(); }; FrameBuffer.prototype.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; }; var _default = { blend: false, blendSep: false, blendColor: 4294967295, blendEq: enums$1.BLEND_FUNC_ADD, blendAlphaEq: enums$1.BLEND_FUNC_ADD, blendSrc: enums$1.BLEND_ONE, blendDst: enums$1.BLEND_ZERO, blendSrcAlpha: enums$1.BLEND_ONE, blendDstAlpha: enums$1.BLEND_ZERO, depthTest: false, depthWrite: false, depthFunc: enums$1.DS_FUNC_LESS, stencilTest: false, stencilSep: false, stencilFuncFront: enums$1.DS_FUNC_ALWAYS, stencilRefFront: 0, stencilMaskFront: 255, stencilFailOpFront: enums$1.STENCIL_OP_KEEP, stencilZFailOpFront: enums$1.STENCIL_OP_KEEP, stencilZPassOpFront: enums$1.STENCIL_OP_KEEP, stencilWriteMaskFront: 255, stencilFuncBack: enums$1.DS_FUNC_ALWAYS, stencilRefBack: 0, stencilMaskBack: 255, stencilFailOpBack: enums$1.STENCIL_OP_KEEP, stencilZFailOpBack: enums$1.STENCIL_OP_KEEP, stencilZPassOpBack: enums$1.STENCIL_OP_KEEP, stencilWriteMaskBack: 255, cullMode: enums$1.CULL_BACK, primitiveType: enums$1.PT_TRIANGLES, maxStream: -1, vertexBuffers: [], vertexBufferOffsets: [], indexBuffer: null, maxTextureSlot: -1, textureUnits: [], program: null }; var State = 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); }; State.prototype.reset = function reset() { this.set(_default); }; State.prototype.set = function set(cpy) { var this$1 = this; 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$1.vertexBuffers[i] = cpy.vertexBuffers[i]; for (var i$1 = 0; i$1 < cpy.vertexBufferOffsets.length; ++i$1) this$1.vertexBufferOffsets[i$1] = cpy.vertexBufferOffsets[i$1]; this.indexBuffer = cpy.indexBuffer; this.maxTextureSlot = cpy.maxTextureSlot; for (var i$2 = 0; i$2 < cpy.textureUnits.length; ++i$2) this$1.textureUnits[i$2] = cpy.textureUnits[i$2]; this.program = cpy.program; }; var GL_INT = 5124; var GL_FLOAT$1 = 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 = {}; _type2uniformCommit[GL_INT] = function(gl, id, value) { gl.uniform1i(id, value); }; _type2uniformCommit[GL_FLOAT$1] = function(gl, id, value) { gl.uniform1f(id, value); }; _type2uniformCommit[GL_FLOAT_VEC2] = function(gl, id, value) { gl.uniform2fv(id, value); }; _type2uniformCommit[GL_FLOAT_VEC3] = function(gl, id, value) { gl.uniform3fv(id, value); }; _type2uniformCommit[GL_FLOAT_VEC4] = function(gl, id, value) { gl.uniform4fv(id, value); }; _type2uniformCommit[GL_INT_VEC2] = function(gl, id, value) { gl.uniform2iv(id, value); }; _type2uniformCommit[GL_INT_VEC3] = function(gl, id, value) { gl.uniform3iv(id, value); }; _type2uniformCommit[GL_INT_VEC4] = function(gl, id, value) { gl.uniform4iv(id, value); }; _type2uniformCommit[GL_BOOL] = function(gl, id, value) { gl.uniform1i(id, value); }; _type2uniformCommit[GL_BOOL_VEC2] = function(gl, id, value) { gl.uniform2iv(id, value); }; _type2uniformCommit[GL_BOOL_VEC3] = function(gl, id, value) { gl.uniform3iv(id, value); }; _type2uniformCommit[GL_BOOL_VEC4] = function(gl, id, value) { gl.uniform4iv(id, value); }; _type2uniformCommit[GL_FLOAT_MAT2] = function(gl, id, value) { gl.uniformMatrix2fv(id, false, value); }; _type2uniformCommit[GL_FLOAT_MAT3] = function(gl, id, value) { gl.uniformMatrix3fv(id, false, value); }; _type2uniformCommit[GL_FLOAT_MAT4] = function(gl, id, value) { gl.uniformMatrix4fv(id, false, value); }; _type2uniformCommit[GL_SAMPLER_2D] = function(gl, id, value) { gl.uniform1i(id, value); }; _type2uniformCommit[GL_SAMPLER_CUBE] = function(gl, id, value) { gl.uniform1i(id, value); }; var _type2uniformArrayCommit = {}; _type2uniformArrayCommit[GL_INT] = function(gl, id, value) { gl.uniform1iv(id, value); }; _type2uniformArrayCommit[GL_FLOAT$1] = function(gl, id, value) { gl.uniform1fv(id, value); }; _type2uniformArrayCommit[GL_FLOAT_VEC2] = function(gl, id, value) { gl.uniform2fv(id, value); }; _type2uniformArrayCommit[GL_FLOAT_VEC3] = function(gl, id, value) { gl.uniform3fv(id, value); }; _type2uniformArrayCommit[GL_FLOAT_VEC4] = function(gl, id, value) { gl.uniform4fv(id, value); }; _type2uniformArrayCommit[GL_INT_VEC2] = function(gl, id, value) { gl.uniform2iv(id, value); }; _type2uniformArrayCommit[GL_INT_VEC3] = function(gl, id, value) { gl.uniform3iv(id, value); }; _type2uniformArrayCommit[GL_INT_VEC4] = function(gl, id, value) { gl.uniform4iv(id, value); }; _type2uniformArrayCommit[GL_BOOL] = function(gl, id, value) { gl.uniform1iv(id, value); }; _type2uniformArrayCommit[GL_BOOL_VEC2] = function(gl, id, value) { gl.uniform2iv(id, value); }; _type2uniformArrayCommit[GL_BOOL_VEC3] = function(gl, id, value) { gl.uniform3iv(id, value); }; _type2uniformArrayCommit[GL_BOOL_VEC4] = function(gl, id, value) { gl.uniform4iv(id, value); }; _type2uniformArrayCommit[GL_FLOAT_MAT2] = function(gl, id, value) { gl.uniformMatrix2fv(id, false, value); }; _type2uniformArrayCommit[GL_FLOAT_MAT3] = function(gl, id, value) { gl.uniformMatrix3fv(id, false, value); }; _type2uniformArrayCommit[GL_FLOAT_MAT4] = function(gl, id, value) { gl.uniformMatrix4fv(id, false, value); }; _type2uniformArrayCommit[GL_SAMPLER_2D] = function(gl, id, value) { gl.uniform1iv(id, value); }; _type2uniformArrayCommit[GL_SAMPLER_CUBE] = function(gl, id, value) { gl.uniform1iv(id, value); }; 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$1.BLEND_CONSTANT_COLOR && next.blendSrc !== enums$1.BLEND_ONE_MINUS_CONSTANT_COLOR && next.blendDst !== enums$1.BLEND_CONSTANT_COLOR && next.blendDst !== enums$1.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$1.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 !== cur.stencilTest) { if (!next.stencilTest) { gl.disable(gl.STENCIL_TEST); return; } gl.enable(gl.STENCIL_TEST); if (next.stencilSep) { gl.stencilFuncSeparate(gl.FRONT, next.stencilFuncFront, next.stencilRefFront, next.stencilMaskFront); gl.stencilMaskSeparate(gl.FRONT, next.stencilWriteMaskFront); gl.stencilOpSeparate(gl.FRONT, next.stencilFailOpFront, next.stencilZFailOpFront, next.stencilZPassOpFront); gl.stencilFuncSeparate(gl.BACK, next.stencilFuncBack, next.stencilRefBack, next.stencilMaskBack); gl.stencilMaskSeparate(gl.BACK, next.stencilWriteMaskBack); gl.stencilOpSeparate(gl.BACK, next.stencilFailOpBack, next.stencilZFailOpBack, next.stencilZPassOpBack); } else { gl.stencilFunc(next.stencilFuncFront, next.stencilRefFront, next.stencilMaskFront); gl.stencilMask(next.stencilWriteMaskFront); gl.stencilOp(next.stencilFailOpFront, next.stencilZFailOpFront, next.stencilZPassOpFront); } return; } if (!next.stencilTest) return; if (cur.stencilSep !== next.stencilSep) { if (next.stencilSep) { gl.stencilFuncSeparate(gl.FRONT, next.stencilFuncFront, next.stencilRefFront, next.stencilMaskFront); gl.stencilMaskSeparate(gl.FRONT, next.stencilWriteMaskFront); gl.stencilOpSeparate(gl.FRONT, next.stencilFailOpFront, next.stencilZFailOpFront, next.stencilZPassOpFront); gl.stencilFuncSeparate(gl.BACK, next.stencilFuncBack, next.stencilRefBack, next.stencilMaskBack); gl.stencilMaskSeparate(gl.BACK, next.stencilWriteMaskBack); gl.stencilOpSeparate(gl.BACK, next.stencilFailOpBack, next.stencilZFailOpBack, next.stencilZPassOpBack); } else { gl.stencilFunc(next.stencilFuncFront, next.stencilRefFront, next.stencilMaskFront); gl.stencilMask(next.stencilWriteMaskFront); gl.stencilOp(next.stencilFailOpFront, next.stencilZFailOpFront, next.stencilZPassOpFront); } return; } if (next.stencilSep) { 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$1.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) { console.warn("VertexBuffer not assigned, please call setVertexBuffer before every draw."); return; } if (cur.maxStream !== next.maxStream) attrsDirty = true; else if (cur.program !== next.program) attrsDirty = true; else for (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$1 = 0; i$1 < device._caps.maxVertexAttribs; ++i$1) device._newAttributes[i$1] = 0; for (var i$2 = 0; i$2 < next.maxStream + 1; ++i$2) { var vb = next.vertexBuffers[i$2]; var vbOffset = next.vertexBufferOffsets[i$2]; if (!vb) 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 i$3 = 0; i$3 < device._caps.maxVertexAttribs; ++i$3) if (device._enabledAttributes[i$3] !== device._newAttributes[i$3]) { gl.disableVertexAttribArray(i$3); device._enabledAttributes[i$3] = 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 ? gl.framebufferTexture2D(gl.FRAMEBUFFER, location, gl.TEXTURE_2D, attachment._glID, 0) : attachment instanceof TextureCube ? 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 Device(canvasEL, opts) { var this$1 = this; 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; } 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_etc1", "WEBGL_compressed_texture_pvrtc", "WEBGL_compressed_texture_s3tc", "WEBGL_depth_texture", "WEBGL_draw_buffers" ]); this._initCaps(); this._initStates(); State.initDefault(this); this._current = new State(this); this._next = new State(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$1._enabledAttributes[i] = 0; this$1._newAttributes[i] = 0; } }; Device.prototype._initExtensions = function _initExtensions(extensions) { var this$1 = this; 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); ext && (this$1._extensions[name] = ext); } catch (e) { console.error(e); } } }; Device.prototype._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.maxDrawBuffers = extDrawBuffers ? gl.getParameter(extDrawBuffers.MAX_DRAW_BUFFERS_WEBGL) : 1; this._caps.maxColorAttachments = extDrawBuffers ? gl.getParameter(extDrawBuffers.MAX_COLOR_ATTACHMENTS_WEBGL) : 1; }; Device.prototype._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); }; Device.prototype._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); }; Device.prototype._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); }; Device.prototype.ext = function ext(name) { return this._extensions[name]; }; Device.prototype.setFrameBuffer = function setFrameBuffer(fb) { var this$1 = this; if (this._framebuffer === fb) return; this._framebuffer = fb; var gl = this._gl; if (null === fb) { gl.bindFramebuffer(gl.FRAMEBUFFER, null); return; } gl.bindFramebuffer(gl.FRAMEBUFFER, fb._glID); var numColors = this._framebuffer._colors.length; for (var i = 0; i < numColors; ++i) { var colorBuffer = this$1._framebuffer._colors[i]; _attach(gl, gl.COLOR_ATTACHMENT0 + i, colorBuffer); } for (var i$1 = numColors; i$1 < this._caps.maxColorAttachments; ++i$1) gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i$1, gl.TEXTURE_2D, null, 0); this._framebuffer._depth && _attach(gl, gl.DEPTH_ATTACHMENT, this._framebuffer._depth); this._framebuffer._stencil && _attach(gl, gl.STENCIL_ATTACHMENT, fb._stencil); this._framebuffer._depthStencil && _attach(gl, gl.DEPTH_STENCIL_ATTACHMENT, fb._depthStencil); }; Device.prototype.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; } }; Device.prototype.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; } }; Device.prototype.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$1.DS_FUNC_ALWAYS && gl.depthFunc(this._current.depthFunc); } }; Device.prototype.enableBlend = function enableBlend() { this._next.blend = true; }; Device.prototype.enableDepthTest = function enableDepthTest() { this._next.depthTest = true; }; Device.prototype.enableDepthWrite = function enableDepthWrite() { this._next.depthWrite = true; }; Device.prototype.enableStencilTest = function enableStencilTest() { this._next.stencilTest = true; }; Device.prototype.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; }; Device.prototype.setStencilFuncFront = function setStencilFuncFront(func, ref, mask) { this._next.stencilSep = true; this._next.stencilFuncFront = func; this._next.stencilRefFront = ref; this._next.stencilMaskFront = mask; }; Device.prototype.setStencilFuncBack = function setStencilFuncBack(func, ref, mask) { this._next.stencilSep = true; this._next.stencilFuncBack = func; this._next.stencilRefBack = ref; this._next.stencilMaskBack = mask; }; Device.prototype.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; }; Device.prototype.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; }; Device.prototype.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; }; Device.prototype.setDepthFunc = function setDepthFunc(depthFunc) { this._next.depthFunc = depthFunc; }; Device.prototype.setBlendColor32 = function setBlendColor32(rgba) { this._next.blendColor = rgba; }; Device.prototype.setBlendColor = function setBlendColor(r, g, b, a) { this._next.blendColor = (255 * r << 24 | 255 * g << 16 | 255 * b << 8 | 255 * a) >>> 0; }; Device.prototype.setBlendFunc = function setBlendFunc(src, dst) { this._next.blendSep = false; this._next.blendSrc = src; this._next.blendDst = dst; }; Device.prototype.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; }; Device.prototype.setBlendEq = function setBlendEq(eq) { this._next.blendSep = false; this._next.blendEq = eq; }; Device.prototype.setBlendEqSep = function setBlendEqSep(eq, alphaEq) { this._next.blendSep = true; this._next.blendEq = eq; this._next.blendAlphaEq = alphaEq; }; Device.prototype.setCullMode = function setCullMode(mode) { this._next.cullMode = mode; }; Device.prototype.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); }; Device.prototype.setIndexBuffer = function setIndexBuffer(buffer) { this._next.indexBuffer = buffer; }; Device.prototype.setProgram = function setProgram(program) { this._next.program = program; }; Device.prototype.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); }; Device.prototype.setTextureArray = function setTextureArray(name, textures, slots) { var this$1 = this; 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$1._next.textureUnits[slot] = textures[i]; } this.setUniform(name, slots); }; Device.prototype.setUniform = function setUniform(name, value) { var uniform = this._uniforms[name]; var sameType = false; do { if (!uniform) break; if (uniform.isArray !== Array.isArray(value)) 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; var isArray = false; if (value instanceof Float32Array || Array.isArray(value)) { newValue = new Float32Array(value); isArray = true; } else if (value instanceof Int32Array) { newValue = new Int32Array(value); isArray = true; } uniform = { dirty: true, value: newValue, isArray: isArray }; } this._uniforms[name] = uniform; }; Device.prototype.setPrimitiveType = function setPrimitiveType(type) { this._next.primitiveType = type; }; Device.prototype.draw = function draw(base, count) { var this$1 = this; 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 ? 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$1._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); } 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 += 1; cur.set(next); next.reset(); }; var gfx = { VertexFormat: VertexFormat, IndexBuffer: IndexBuffer, VertexBuffer: VertexBuffer, Program: Program, Texture: Texture, Texture2D: Texture2D, TextureCube: TextureCube, RenderBuffer: RenderBuffer, FrameBuffer: FrameBuffer, Device: Device, attrTypeBytes: attrTypeBytes, glFilter: glFilter, glTextureFmt: glTextureFmt }; Object.assign(gfx, enums$1); var InputAssembler = function InputAssembler(vb, ib, pt) { void 0 === pt && (pt = gfx.PT_TRIANGLES); this._vertexBuffer = vb; this._indexBuffer = ib; this._primitiveType = pt; this._start = 0; this._count = -1; }; InputAssembler.prototype.getPrimitiveCount = function getPrimitiveCount() { if (-1 !== this._count) return this._count; if (this._indexBuffer) return this._indexBuffer.count; return this._vertexBuffer.count; }; var Pass = function Pass(name) { this._programName = name; this._cullMode = gfx.CULL_BACK; this._blend = false; this._blendEq = gfx.BLEND_FUNC_ADD; this._blendAlphaEq = gfx.BLEND_FUNC_ADD; this._blendSrc = gfx.BLEND_ONE; this._blendDst = gfx.BLEND_ZERO; this._blendSrcAlpha = gfx.BLEND_ONE; this._blendDstAlpha = gfx.BLEND_ZERO; this._blendColor = 4294967295; this._depthTest = false; this._depthWrite = false; this._depthFunc = gfx.DS_FUNC_LESS; this._stencilTest = false; this._stencilFuncFront = gfx.DS_FUNC_ALWAYS; this._stencilRefFront = 0; this._stencilMaskFront = 255; this._stencilFailOpFront = gfx.STENCIL_OP_KEEP; this._stencilZFailOpFront = gfx.STENCIL_OP_KEEP; this._stencilZPassOpFront = gfx.STENCIL_OP_KEEP; this._stencilWriteMaskFront = 255; this._stencilFuncBack = gfx.DS_FUNC_ALWAYS; this._stencilRefBack = 0; this._stencilMaskBack = 255; this._stencilFailOpBack = gfx.STENCIL_OP_KEEP; this._stencilZFailOpBack = gfx.STENCIL_OP_KEEP; this._stencilZPassOpBack = gfx.STENCIL_OP_KEEP; this._stencilWriteMaskBack = 255; }; Pass.prototype.copy = function(pass) { this._programName = pass._programName; this._cullMode = pass._cullMode; this._blend = pass._blend; this._blendEq = pass._blendEq; this._blendAlphaEq = pass._blendAlphaEq; this._blendSrc = pass._blendSrc; this._blendDst = pass._blendDst; this._blendSrcAlpha = pass._blendSrcAlpha; this._blendDstAlpha = pass._blendDstAlpha; this._blendColor = pass._blendColor; this._depthTest = pass._depthTest; this._depthWrite = pass._depthWrite; this._depthFunc = pass._depthFunc; this._stencilTest = pass._stencilTest; this._stencilFuncFront = pass._stencilFuncFront; this._stencilRefFront = pass._stencilRefFront; this._stencilMaskFront = pass._stencilMaskFront; this._stencilFailOpFront = pass._stencilFailOpFront; this._stencilZFailOpFront = pass._stencilZFailOpFront; this._stencilZPassOpFront = pass._stencilZPassOpFront; this._stencilWriteMaskFront = pass._stencilWriteMaskFront; this._stencilFuncBack = pass._stencilFuncBack; this._stencilRefBack = pass._stencilRefBack; this._stencilMaskBack = pass._stencilMaskBack; this._stencilFailOpBack = pass._stencilFailOpBack; this._stencilZFailOpBack = pass._stencilZFailOpBack; this._stencilZPassOpBack = pass._stencilZPassOpBack; this._stencilWriteMaskBack = pass._stencilWriteMaskBack; }; Pass.prototype.setCullMode = function setCullMode(cullMode) { this._cullMode = cullMode; }; Pass.prototype.setBlend = function setBlend(blendEq, blendSrc, blendDst, blendAlphaEq, blendSrcAlpha, blendDstAlpha, blendColor) { void 0 === blendEq && (blendEq = gfx.BLEND_FUNC_ADD); void 0 === blendSrc && (blendSrc = gfx.BLEND_ONE); void 0 === blendDst && (blendDst = gfx.BLEND_ZERO); void 0 === blendAlphaEq && (blendAlphaEq = gfx.BLEND_FUNC_ADD); void 0 === blendSrcAlpha && (blendSrcAlpha = gfx.BLEND_ONE); void 0 === blendDstAlpha && (blendDstAlpha = gfx.BLEND_ZERO); void 0 === blendColor && (blendColor = 4294967295); this._blend = true; this._blendEq = blendEq; this._blendSrc = blendSrc; this._blendDst = blendDst; this._blendAlphaEq = blendAlphaEq; this._blendSrcAlpha = blendSrcAlpha; this._blendDstAlpha = blendDstAlpha; this._blendColor = blendColor; }; Pass.prototype.setDepth = function setDepth(depthTest, depthWrite, depthFunc) { void 0 === depthTest && (depthTest = false); void 0 === depthWrite && (depthWrite = false); void 0 === depthFunc && (depthFunc = gfx.DS_FUNC_LESS); this._depthTest = depthTest; this._depthWrite = depthWrite; this._depthFunc = depthFunc; }; Pass.prototype.setStencilFront = function setStencilFront(stencilFunc, stencilRef, stencilMask, stencilFailOp, stencilZFailOp, stencilZPassOp, stencilWriteMask) { 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._stencilTest = true; this._stencilFuncFront = stencilFunc; this._stencilRefFront = stencilRef; this._stencilMaskFront = stencilMask; this._stencilFailOpFront = stencilFailOp; this._stencilZFailOpFront = stencilZFailOp; this._stencilZPassOpFront = stencilZPassOp; this._stencilWriteMaskFront = stencilWriteMask; }; Pass.prototype.setStencilBack = function setStencilBack(stencilFunc, stencilRef, stencilMask, stencilFailOp, stencilZFailOp, stencilZPassOp, stencilWriteMask) { 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._stencilTest = true; this._stencilFuncBack = stencilFunc; this._stencilRefBack = stencilRef; this._stencilMaskBack = stencilMask; this._stencilFailOpBack = stencilFailOp; this._stencilZFailOpBack = stencilZFailOp; this._stencilZPassOpBack = stencilZPassOp; this._stencilWriteMaskBack = stencilWriteMask; }; Pass.prototype.disableStencilTest = function disableStencilTest() { this._stencilTest = false; }; var _stageOffset = 0; var _name2stageID = {}; var config = { addStage: function(name) { if (void 0 !== _name2stageID[name]) return; var stageID = 1 << _stageOffset; _name2stageID[name] = stageID; _stageOffset += 1; }, stageID: function(name) { var id = _name2stageID[name]; if (void 0 === id) return -1; return id; }, stageIDs: function(nameList) { var key = 0; for (var i = 0; i < nameList.length; ++i) { var id = _name2stageID[nameList[i]]; void 0 !== id && (key |= id); } return key; } }; var _genID$1 = 0; var Technique = function Technique(stages, parameters, passes, layer) { void 0 === layer && (layer = 0); this._id = _genID$1++; this._stageIDs = config.stageIDs(stages); this._parameters = parameters; this._passes = passes; this._layer = layer; }; var prototypeAccessors$3 = { passes: { configurable: true }, stageIDs: { configurable: true } }; Technique.prototype.copy = function(technique) { this._id = technique._id; this._stageIDs = technique._stageIDs; this._parameters = []; for (var _i = 0; _i < technique._parameters.length; ++_i) { var parameter = technique._parameters[_i]; this._parameters.push({ name: parameter.name, type: parameter.type }); } for (var _i2 = 0; _i2 < technique._passes.length; ++_i2) { var pass = this._passes[_i2]; if (!pass) { pass = new renderer.Pass(); this._passes.push(pass); } pass.copy(technique._passes[_i2]); } this._passes.length = technique._passes.length; this._layer = technique._layer; }; Technique.prototype.setStages = function setStages(stages) { this._stageIDs = config.stageIDs(stages); }; prototypeAccessors$3.passes.get = function() { return this._passes; }; prototypeAccessors$3.stageIDs.get = function() { return this._stageIDs; }; Object.defineProperties(Technique.prototype, prototypeAccessors$3); var Effect = function Effect(techniques, properties, defines) { void 0 === properties && (properties = {}); void 0 === defines && (defines = []); this._techniques = techniques; this._properties = properties; this._defines = defines; }; Effect.prototype.clear = function clear() { this._techniques.length = 0; this._properties = null; this._defines.length = 0; }; Effect.prototype.getTechnique = function getTechnique(stage) { var this$1 = this; var stageID = config.stageID(stage); for (var i = 0; i < this._techniques.length; ++i) { var tech = this$1._techniques[i]; if (tech.stageIDs & stageID) return tech; } return null; }; Effect.prototype.getProperty = function getProperty(name) { return this._properties[name]; }; Effect.prototype.setProperty = function setProperty(name, value) { this._properties[name] = value; }; Effect.prototype.getDefine = function getDefine(name) { var this$1 = this; for (var i = 0; i < this._defines.length; ++i) { var def = this$1._defines[i]; if (def.name === name) return def.value; } console.warn("Failed to get define " + name + ", define not found."); return null; }; Effect.prototype.define = function define(name, value) { var this$1 = this; for (var i = 0; i < this._defines.length; ++i) { var def = this$1._defines[i]; if (def.name === name) { def.value = value; return; } } console.warn("Failed to set define " + name + ", define not found."); }; Effect.prototype.extractDefines = function extractDefines(out) { var this$1 = this; void 0 === out && (out = {}); for (var i = 0; i < this._defines.length; ++i) { var def = this$1._defines[i]; out[def.name] = def.value; } return out; }; function createIA(device, data) { if (!data.positions) { console.error("The data must have positions field"); return null; } var verts = []; var vcount = data.positions.length / 3; for (var i = 0; i < vcount; ++i) { verts.push(data.positions[3 * i], data.positions[3 * i + 1], data.positions[3 * i + 2]); data.normals && verts.push(data.normals[3 * i], data.normals[3 * i + 1], data.normals[3 * i + 2]); data.uvs && verts.push(data.uvs[2 * i], data.uvs[2 * i + 1]); } var vfmt = []; vfmt.push({ name: gfx.ATTR_POSITION, type: gfx.ATTR_TYPE_FLOAT32, num: 3 }); data.normals && vfmt.push({ name: gfx.ATTR_NORMAL, type: gfx.ATTR_TYPE_FLOAT32, num: 3 }); data.uvs && vfmt.push({ name: gfx.ATTR_UV0, type: gfx.ATTR_TYPE_FLOAT32, num: 2 }); var vb = new gfx.VertexBuffer(device, new gfx.VertexFormat(vfmt), gfx.USAGE_STATIC, new Float32Array(verts), vcount); var ib = null; data.indices && (ib = new gfx.IndexBuffer(device, gfx.INDEX_FMT_UINT16, gfx.USAGE_STATIC, new Uint16Array(data.indices), data.indices.length)); return new InputAssembler(vb, ib); } var _m4_tmp = mat4.create(); var _genID$2 = 0; var View = function View() { this._id = _genID$2++; this._rect = { x: 0, y: 0, w: 1, h: 1 }; this._color = color4.new(.3, .3, .3, 1); this._depth = 1; this._stencil = 0; this._clearFlags = enums.CLEAR_COLOR | enums.CLEAR_DEPTH; this._matView = mat4.create(); this._matProj = mat4.create(); this._matViewProj = mat4.create(); this._matInvViewProj = mat4.create(); this._stages = []; this._cullingMask = 1; this._framebuffer = null; this._shadowLight = null; }; View.prototype.getForward = function getForward(out) { return vec3.set(out, -this._matView.m02, -this._matView.m06, -this._matView.m10); }; View.prototype.getPosition = function getPosition(out) { mat4.invert(_m4_tmp, this._matView); return mat4.getTranslation(out, _m4_tmp); }; var _forward = vec3.new(0, 0, -1); var _m4_tmp$1 = mat4.create(); var _m3_tmp = mat3.create(); var _transformedLightDirection = vec3.create(); function _computeSpotLightViewProjMatrix(light, outView, outProj) { light._node.getWorldRT(outView); mat4.invert(outView, outView); mat4.perspective(outProj, light._spotAngle * light._spotAngleScale, 1, light._shadowMinDepth, light._shadowMaxDepth); } function _computeDirectionalLightViewProjMatrix(light, outView, outProj) { light._node.getWorldRT(outView); mat4.invert(outView, outView); var halfSize = light._shadowFustumSize / 2; mat4.ortho(outProj, -halfSize, halfSize, -halfSize, halfSize, light._shadowMinDepth, light._shadowMaxDepth); } function _computePointLightViewProjMatrix(light, outView, outProj) {} var Light = function Light() { this._poolID = -1; this._node = null; this._type = enums.LIGHT_DIRECTIONAL; this._color = color3.new(1, 1, 1); this._intensity = 1; this._range = 1; this._spotAngle = toRadian(60); this._spotExp = 1; this._directionUniform = new Float32Array(3); this._positionUniform = new Float32Array(3); this._colorUniform = new Float32Array([ this._color.r * this._intensity, this._color.g * this._intensity, this._color.b * this._intensity ]); this._spotUniform = new Float32Array([ Math.cos(.5 * this._spotAngle), this._spotExp ]); this._shadowType = enums.SHADOW_NONE; this._shadowFrameBuffer = null; this._shadowMap = null; this._shadowMapDirty = false; this._shadowDepthBuffer = null; this._shadowResolution = 1024; this._shadowBias = 5e-5; this._shadowDarkness = 1; this._shadowMinDepth = 1; this._shadowMaxDepth = 1e3; this._shadowDepthScale = 50; this._frustumEdgeFalloff = 0; this._viewProjMatrix = mat4.create(); this._spotAngleScale = 1; this._shadowFustumSize = 80; }; var prototypeAccessors$4 = { color: { configurable: true }, intensity: { configurable: true }, type: { configurable: true }, spotAngle: { configurable: true }, spotExp: { configurable: true }, range: { configurable: true }, shadowType: { configurable: true }, shadowMap: { configurable: true }, viewProjMatrix: { configurable: true }, shadowResolution: { configurable: true }, shadowBias: { configurable: true }, shadowDarkness: { configurable: true }, shadowMinDepth: { configurable: true }, shadowMaxDepth: { configurable: true }, shadowDepthScale: { configurable: true }, frustumEdgeFalloff: { configurable: true } }; Light.prototype.setNode = function setNode(node) { this._node = node; }; Light.prototype.setColor = function setColor(r, g, b) { color3.set(this._color, r, g, b); this._colorUniform[0] = r * this._intensity; this._colorUniform[1] = g * this._intensity; this._colorUniform[2] = b * this._intensity; }; prototypeAccessors$4.color.get = function() { return this._color; }; Light.prototype.setIntensity = function setIntensity(val) { this._intensity = val; this._colorUniform[0] = val * this._color.r; this._colorUniform[1] = val * this._color.g; this._colorUniform[2] = val * this._color.b; }; prototypeAccessors$4.intensity.get = function() { return this._intensity; }; Light.prototype.setType = function setType(tpe) { this._type = tpe; }; prototypeAccessors$4.type.get = function() { return this._type; }; Light.prototype.setSpotAngle = function setSpotAngle(val) { this._spotAngle = val; this._spotUniform[0] = Math.cos(.5 * this._spotAngle); }; prototypeAccessors$4.spotAngle.get = function() { return this._spotAngle; }; Light.prototype.setSpotExp = function setSpotExp(val) { this._spotExp = val; this._spotUniform[1] = val; }; prototypeAccessors$4.spotExp.get = function() { return this._spotExp; }; Light.prototype.setRange = function setRange(tpe) { this._range = tpe; }; prototypeAccessors$4.range.get = function() { return this._range; }; Light.prototype.setShadowType = function setShadowType(type) { this._shadowType === enums.SHADOW_NONE && type !== enums.SHADOW_NONE && (this._shadowMapDirty = true); this._shadowType = type; }; prototypeAccessors$4.shadowType.get = function() { return this._shadowType; }; prototypeAccessors$4.shadowMap.get = function() { return this._shadowMap; }; prototypeAccessors$4.viewProjMatrix.get = function() { return this._viewProjMatrix; }; Light.prototype.setShadowResolution = function setShadowResolution(val) { this._shadowResolution !== val && (this._shadowMapDirty = true); this._shadowResolution = val; }; prototypeAccessors$4.shadowResolution.get = function() { return this._shadowResolution; }; Light.prototype.setShadowBias = function setShadowBias(val) { this._shadowBias = val; }; prototypeAccessors$4.shadowBias.get = function() { return this._shadowBias; }; Light.prototype.setShadowDarkness = function setShadowDarkness(val) { this._shadowDarkness = val; }; prototypeAccessors$4.shadowDarkness.get = function() { return this._shadowDarkness; }; Light.prototype.setShadowMinDepth = function setShadowMinDepth(val) { this._shadowMinDepth = val; }; prototypeAccessors$4.shadowMinDepth.get = function() { if (this._type === enums.LIGHT_DIRECTIONAL) return 1; return this._shadowMinDepth; }; Light.prototype.setShadowMaxDepth = function setShadowMaxDepth(val) { this._shadowMaxDepth = val; }; prototypeAccessors$4.shadowMaxDepth.get = function() { if (this._type === enums.LIGHT_DIRECTIONAL) return 1; return this._shadowMaxDepth; }; Light.prototype.setShadowDepthScale = function setShadowDepthScale(val) { this._shadowDepthScale = val; }; prototypeAccessors$4.shadowDepthScale.get = function() { return this._shadowDepthScale; }; Light.prototype.setFrustumEdgeFalloff = function setFrustumEdgeFalloff(val) { this._frustumEdgeFalloff = val; }; prototypeAccessors$4.frustumEdgeFalloff.get = function() { return this._frustumEdgeFalloff; }; Light.prototype.extractView = function extractView(out, stages) { out._shadowLight = this; out._rect.x = 0; out._rect.y = 0; out._rect.w = this._shadowResolution; out._rect.h = this._shadowResolution; color4.set(out._color, 1, 1, 1, 1); out._depth = 1; out._stencil = 0; out._clearFlags = enums.CLEAR_COLOR | enums.CLEAR_DEPTH; out._stages = stages; out._framebuffer = this._shadowFrameBuffer; switch (this._type) { case enums.LIGHT_SPOT: _computeSpotLightViewProjMatrix(this, out._matView, out._matProj); break; case enums.LIGHT_DIRECTIONAL: _computeDirectionalLightViewProjMatrix(this, out._matView, out._matProj); break; case enums.LIGHT_POINT: _computePointLightViewProjMatrix(this, out._matView, out._matProj); break; default: console.warn("shadow of this light type is not supported"); } mat4.mul(out._matViewProj, out._matProj, out._matView); this._viewProjMatrix = out._matViewProj; mat4.invert(out._matInvViewProj, out._matViewProj); }; Light.prototype._updateLightPositionAndDirection = function _updateLightPositionAndDirection() { this._node.getWorldMatrix(_m4_tmp$1); mat3.fromMat4(_m3_tmp, _m4_tmp$1); vec3.transformMat3(_transformedLightDirection, _forward, _m3_tmp); vec3.array(this._directionUniform, _transformedLightDirection); var pos = this._positionUniform; pos[0] = _m4_tmp$1.m12; pos[1] = _m4_tmp$1.m13; pos[2] = _m4_tmp$1.m14; }; Light.prototype._generateShadowMap = function _generateShadowMap(device) { this._shadowMap = new gfx.Texture2D(device, { width: this._shadowResolution, height: this._shadowResolution, format: gfx.TEXTURE_FMT_RGBA8, wrapS: gfx.WRAP_CLAMP, wrapT: gfx.WRAP_CLAMP }); this._shadowDepthBuffer = new gfx.RenderBuffer(device, gfx.RB_FMT_D16, this._shadowResolution, this._shadowResolution); this._shadowFrameBuffer = new gfx.FrameBuffer(device, this._shadowResolution, this._shadowResolution, { colors: [ this._shadowMap ], depth: this._shadowDepthBuffer }); }; Light.prototype._destroyShadowMap = function _destroyShadowMap() { if (this._shadowMap) { this._shadowMap.destroy(); this._shadowDepthBuffer.destroy(); this._shadowFrameBuffer.destroy(); this._shadowMap = null; this._shadowDepthBuffer = null; this._shadowFrameBuffer = null; } }; Light.prototype.update = function update(device) { this._updateLightPositionAndDirection(); if (this._shadowType === enums.SHADOW_NONE) this._destroyShadowMap(); else if (this._shadowMapDirty) { this._destroyShadowMap(); this._generateShadowMap(device); this._shadowMapDirty = false; } }; Object.defineProperties(Light.prototype, prototypeAccessors$4); var _matView = mat4.create(); var _matProj = mat4.create(); var _matViewProj = mat4.create(); var _matInvViewProj = mat4.create(); var _tmp_v3 = vec3.create(); var Camera = function Camera() { this._poolID = -1; this._node = null; this._projection = enums.PROJ_PERSPECTIVE; this._color = color4.new(.2, .3, .47, 1); this._depth = 1; this._stencil = 0; this._clearFlags = enums.CLEAR_COLOR | enums.CLEAR_DEPTH; this._cullingMask = 1; 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; }; var prototypeAccessors$5 = { cullingMask: { configurable: true } }; prototypeAccessors$5.cullingMask.get = function() { return this._cullingMask; }; prototypeAccessors$5.cullingMask.set = function(mask) { this._cullingMask = mask; }; Camera.prototype.getNode = function getNode() { return this._node; }; Camera.prototype.setNode = function setNode(node) { this._node = node; }; Camera.prototype.getType = function getType() { return this._projection; }; Camera.prototype.setType = function setType(type) { this._projection = type; }; Camera.prototype.getOrthoHeight = function getOrthoHeight() { return this._orthoHeight; }; Camera.prototype.setOrthoHeight = function setOrthoHeight(val) { this._orthoHeight = val; }; Camera.prototype.getFov = function getFov() { return this._fov; }; Camera.prototype.setFov = function setFov(fov) { this._fov = fov; }; Camera.prototype.getNear = function getNear() { return this._near; }; Camera.prototype.setNear = function setNear(near) { this._near = near; }; Camera.prototype.getFar = function getFar() { return this._far; }; Camera.prototype.setFar = function setFar(far) { this._far = far; }; Camera.prototype.getColor = function getColor(out) { return color4.copy(out, this._color); }; Camera.prototype.setColor = function setColor(r, g, b, a) { color4.set(this._color, r, g, b, a); }; Camera.prototype.getDepth = function getDepth() { return this._depth; }; Camera.prototype.setDepth = function setDepth(depth) { this._depth = depth; }; Camera.prototype.getStencil = function getStencil() { return this._stencil; }; Camera.prototype.setStencil = function setStencil(stencil) { this._stencil = stencil; }; Camera.prototype.getClearFlags = function getClearFlags() { return this._clearFlags; }; Camera.prototype.setClearFlags = function setClearFlags(flags) { this._clearFlags = flags; }; Camera.prototype.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; }; Camera.prototype.setRect = function setRect(x, y, w, h) { this._rect.x = x; this._rect.y = y; this._rect.w = w; this._rect.h = h; }; Camera.prototype.getStages = function getStages() { return this._stages; }; Camera.prototype.setStages = function setStages(stages) { this._stages = stages; }; Camera.prototype.getFramebuffer = function getFramebuffer() { return this._framebuffer; }; Camera.prototype.setFramebuffer = function setFramebuffer(framebuffer) { this._framebuffer = framebuffer; }; Camera.prototype.extractView = function extractView(out, width, height) { 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; out._color = this._color; out._depth = this._depth; out._stencil = this._stencil; out._clearFlags = this._clearFlags; out._cullingMask = this._cullingMask; out._stages = this._stages; out._framebuffer = this._framebuffer; this._node.getWorldRT(out._matView); mat4.invert(out._matView, out._matView); var aspect = width / height; if (this._projection === enums.PROJ_PERSPECTIVE) mat4.perspective(out._matProj, this._fov, aspect, this._near, this._far); else { var x = this._orthoHeight * aspect; var y = this._orthoHeight; mat4.ortho(out._matProj, -x, x, -y, y, this._near, this._far); } mat4.mul(out._matViewProj, out._matProj, out._matView); mat4.invert(out._matInvViewProj, out._matViewProj); }; Camera.prototype.screenToWorld = function screenToWorld(out, screenPos, width, height) { var aspect = 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; this._node.getWorldRT(_matView); mat4.invert(_matView, _matView); if (this._projection === enums.PROJ_PERSPECTIVE) mat4.perspective(_matProj, this._fov, aspect, this._near, this._far); else { var x = this._orthoHeight * aspect; var y = this._orthoHeight; mat4.ortho(_matProj, -x, x, -y, y, this._near, this._far); } mat4.mul(_matViewProj, _matProj, _matView); mat4.invert(_matInvViewProj, _matViewProj); if (this._projection === enums.PROJ_PERSPECTIVE) { vec3.set(out, 2 * (screenPos.x - cx) / cw - 1, 2 * (screenPos.y - cy) / ch - 1, 1); vec3.transformMat4(out, out, _matInvViewProj); this._node.getWorldPos(_tmp_v3); vec3.lerp(out, _tmp_v3, out, screenPos.z / this._far); } else { var range = this._farClip - this._nearClip; vec3.set(out, 2 * (screenPos.x - cx) / cw - 1, 2 * (screenPos.y - cy) / ch - 1, (this._far - screenPos.z) / range * 2 - 1); vec3.transformMat4(out, out, _matInvViewProj); } return out; }; Camera.prototype.worldToScreen = function worldToScreen(out, worldPos, width, height) { var aspect = 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; this._node.getWorldRT(_matView); mat4.invert(_matView, _matView); if (this._projection === enums.PROJ_PERSPECTIVE) mat4.perspective(_matProj, this._fov, aspect, this._near, this._far); else { var x = this._orthoHeight * aspect; var y = this._orthoHeight; mat4.ortho(_matProj, -x, x, -y, y, this._near, this._far); } mat4.mul(_matViewProj, _matProj, _matView); var w = worldPos.x * _matViewProj.m03 + worldPos.y * _matViewProj.m07 + worldPos.z * _matViewProj.m11 + _matViewProj.m15; vec3.transformMat4(out, worldPos, _matViewProj); out.x = cx + .5 * (out.x / w + 1) * cw; out.y = cy + .5 * (out.y / w + 1) * ch; return out; }; Object.defineProperties(Camera.prototype, prototypeAccessors$5); var Model = function Model() { this._poolID = -1; this._node = null; this._inputAssemblers = []; this._effects = []; this._defines = []; this._dynamicIA = false; this._cullingMask = -1; }; var prototypeAccessors$6 = { inputAssemblerCount: { configurable: true }, dynamicIA: { configurable: true }, drawItemCount: { configurable: true }, cullingMask: { configurable: true } }; prototypeAccessors$6.inputAssemblerCount.get = function() { return this._inputAssemblers.length; }; prototypeAccessors$6.dynamicIA.get = function() { return this._dynamicIA; }; prototypeAccessors$6.drawItemCount.get = function() { return this._dynamicIA ? 1 : this._inputAssemblers.length; }; prototypeAccessors$6.cullingMask.get = function() { return this._cullingMask; }; prototypeAccessors$6.cullingMask.set = function(mask) { this._cullingMask = mask; }; Model.prototype.setNode = function setNode(node) { this._node = node; }; Model.prototype.setDynamicIA = function setDynamicIA(enabled) { this._dynamicIA = enabled; }; Model.prototype.addInputAssembler = function addInputAssembler(ia) { if (-1 !== this._inputAssemblers.indexOf(ia)) return; this._inputAssemblers.push(ia); }; Model.prototype.clearInputAssemblers = function clearInputAssemblers() { this._inputAssemblers.length = 0; }; Model.prototype.addEffect = function addEffect(effect) { if (-1 !== this._effects.indexOf(effect)) return; this._effects.push(effect); var defs = Object.create(null); effect.extractDefines(defs); this._defines.push(defs); }; Model.prototype.clearEffects = function clearEffects() { this._effects.length = 0; this._defines.length = 0; }; Model.prototype.extractDrawItem = function extractDrawItem(out, index) { if (this._dynamicIA) { out.model = this; out.node = this._node; out.ia = null; out.effect = this._effects[0]; out.defines = out.effect.extractDefines(this._defines[0]); return; } if (index >= this._inputAssemblers.length) { out.model = null; out.node = null; out.ia = null; out.effect = null; out.defines = null; return; } out.model = this; out.node = this._node; out.ia = this._inputAssemblers[index]; var effect, defines; if (index < this._effects.length) { effect = this._effects[index]; defines = this._defines[index]; } else { effect = this._effects[this._effects.length - 1]; defines = this._defines[this._effects.length - 1]; } out.effect = effect; out.defines = effect.extractDefines(defines); }; Object.defineProperties(Model.prototype, prototypeAccessors$6); 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$1(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$1(a); var bl = log10$1(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 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; }; TimSort.prototype.pushRun = function pushRun(runStart, runLength) { this.runStart[this.stackSize] = runStart; this.runLength[this.stackSize] = runLength; this.stackSize += 1; }; TimSort.prototype.mergeRuns = function mergeRuns() { var this$1 = this; while (this.stackSize > 1) { var n = this$1.stackSize - 2; if (n >= 1 && this$1.runLength[n - 1] <= this$1.runLength[n] + this$1.runLength[n + 1] || n >= 2 && this$1.runLength[n - 2] <= this$1.runLength[n] + this$1.runLength[n - 1]) this$1.runLength[n - 1] < this$1.runLength[n + 1] && n--; else if (this$1.runLength[n] > this$1.runLength[n + 1]) break; this$1.mergeAt(n); } }; TimSort.prototype.forceMergeRuns = function forceMergeRuns() { var this$1 = this; while (this.stackSize > 1) { var n = this$1.stackSize - 2; n > 0 && this$1.runLength[n - 1] < this$1.runLength[n + 1] && n--; this$1.mergeAt(n); } }; TimSort.prototype.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); }; TimSort.prototype.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]; } }; TimSort.prototype.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]; } }; function sort(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(); } var FixedArray = function FixedArray(size) { this._count = 0; this._data = new Array(size); }; var prototypeAccessors$7 = { length: { configurable: true }, data: { configurable: true } }; FixedArray.prototype._resize = function _resize(size) { var this$1 = this; if (size > this._data.length) for (var i = this._data.length; i < size; ++i) this$1._data[i] = void 0; }; prototypeAccessors$7.length.get = function() { return this._count; }; prototypeAccessors$7.data.get = function() { return this._data; }; FixedArray.prototype.reset = function reset() { var this$1 = this; for (var i = 0; i < this._count; ++i) this$1._data[i] = void 0; this._count = 0; }; FixedArray.prototype.push = function push(val) { this._count >= this._data.length && this._resize(2 * this._data.length); this._data[this._count] = val; ++this._count; }; FixedArray.prototype.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; }; FixedArray.prototype.fastRemove = function fastRemove(idx) { if (idx >= this._count) return; var last = this._count - 1; this._data[idx] = this._data[last]; this._data[last] = void 0; this._count -= 1; }; FixedArray.prototype.indexOf = function indexOf(val) { var idx = this._data.indexOf(val); if (idx >= this._count) return -1; return idx; }; FixedArray.prototype.sort = function sort$1(cmp) { return sort(this._data, 0, this._count, cmp); }; Object.defineProperties(FixedArray.prototype, prototypeAccessors$7); var Pool = function Pool(fn, size) { var this$1 = this; this._fn = fn; this._idx = size - 1; this._frees = new Array(size); for (var i = 0; i < size; ++i) this$1._frees[i] = fn(); }; Pool.prototype._expand = function _expand(size) { var this$1 = this; var old = this._frees; this._frees = new Array(size); var len = size - old.length; for (var i = 0; i < len; ++i) this$1._frees[i] = this$1._fn(); for (var i$1 = len, j = 0; i$1 < size; ++i$1, ++j) this$1._frees[i$1] = old[j]; this._idx += len; }; Pool.prototype.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; }; Pool.prototype.free = function free(obj) { ++this._idx; this._frees[this._idx] = obj; }; var LinkedArray = function LinkedArray(fn, size) { this._fn = fn; this._count = 0; this._head = null; this._tail = null; this._pool = new Pool(fn, size); }; var prototypeAccessors$8 = { head: { configurable: true }, tail: { configurable: true }, length: { configurable: true } }; prototypeAccessors$8.head.get = function() { return this._head; }; prototypeAccessors$8.tail.get = function() { return this._tail; }; prototypeAccessors$8.length.get = function() { return this._count; }; LinkedArray.prototype.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; }; LinkedArray.prototype.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; }; LinkedArray.prototype.forEach = function forEach(fn, binder) { var this$1 = this; 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$1); cursor = next; ++idx; } }; Object.defineProperties(LinkedArray.prototype, prototypeAccessors$8); var RecyclePool = function RecyclePool(fn, size) { var this$1 = this; this._fn = fn; this._count = 0; this._data = new Array(size); for (var i = 0; i < size; ++i) this$1._data[i] = fn(); }; var prototypeAccessors$9 = { length: { configurable: true }, data: { configurable: true } }; prototypeAccessors$9.length.get = function() { return this._count; }; prototypeAccessors$9.data.get = function() { return this._data; }; RecyclePool.prototype.reset = function reset() { this._count = 0; }; RecyclePool.prototype.resize = function resize(size) { var this$1 = this; if (size > this._data.length) for (var i = this._data.length; i < size; ++i) this$1._data[i] = this$1._fn(); }; RecyclePool.prototype.add = function add() { this._count >= this._data.length && this.resize(2 * this._data.length); return this._data[this._count++]; }; RecyclePool.prototype.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; }; RecyclePool.prototype.sort = function sort$1(cmp) { return sort(this._data, 0, this._count, cmp); }; Object.defineProperties(RecyclePool.prototype, prototypeAccessors$9); var _bufferPools = Array(8); for (var i = 0; i < 8; ++i) _bufferPools[i] = []; var Scene = function Scene() { this._lights = new FixedArray(16); this._models = new FixedArray(16); this._cameras = new FixedArray(16); this._debugCamera = null; this._views = []; }; Scene.prototype._add = function _add(pool, item) { if (-1 !== item._poolID) return; pool.push(item); item._poolID = pool.length - 1; }; Scene.prototype._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; }; Scene.prototype.reset = function reset() { var this$1 = this; for (var i = 0; i < this._models.length; ++i) { var model = this$1._models.data[i]; model._cullingMask = -1; } }; Scene.prototype.setDebugCamera = function setDebugCamera(cam) { this._debugCamera = cam; }; Scene.prototype.getCameraCount = function getCameraCount() { return this._cameras.length; }; Scene.prototype.getCamera = function getCamera(idx) { return this._cameras.data[idx]; }; Scene.prototype.addCamera = function addCamera(camera) { this._add(this._cameras, camera); }; Scene.prototype.removeCamera = function removeCamera(camera) { this._remove(this._cameras, camera); }; Scene.prototype.getModelCount = function getModelCount() { return this._models.length; }; Scene.prototype.getModel = function getModel(idx) { return this._models.data[idx]; }; Scene.prototype.addModel = function addModel(model) { this._add(this._models, model); }; Scene.prototype.removeModel = function removeModel(model) { this._remove(this._models, model); }; Scene.prototype.getLightCount = function getLightCount() { return this._lights.length; }; Scene.prototype.getLight = function getLight(idx) { return this._lights.data[idx]; }; Scene.prototype.addLight = function addLight(light) { this._add(this._lights, light); }; Scene.prototype.removeLight = function removeLight(light) { this._remove(this._lights, light); }; Scene.prototype.addView = function addView(view) { -1 === this._views.indexOf(view) && this._views.push(view); }; Scene.prototype.removeView = function removeView(view) { var idx = this._views.indexOf(view); -1 !== idx && this._views.splice(idx, 1); }; var _shdID = 0; function _generateDefines(defs) { var defines = []; for (var def in defs) true === defs[def] && defines.push("#define " + def); return defines.join("\n"); } function _replaceMacroNums(string, defs) { var cache = {}; var tmp = string; for (var def in defs) Number.isInteger(defs[def]) && (cache[def] = defs[def]); for (var def$1 in cache) { var reg = new RegExp(def$1, "g"); tmp = tmp.replace(reg, cache[def$1]); } 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); } var ProgramLib = function ProgramLib(device, templates, chunks) { var this$1 = this; void 0 === templates && (templates = []); void 0 === chunks && (chunks = {}); this._device = device; this._precision = "precision highp float;\n"; this._templates = {}; for (var i = 0; i < templates.length; ++i) { var tmpl = templates[i]; this$1.define(tmpl.name, tmpl.vert, tmpl.frag, tmpl.defines); } this._chunks = {}; Object.assign(this._chunks, chunks); this._cache = {}; }; ProgramLib.prototype.define = function define(name, vert, frag, defines) { if (this._templates[name]) { console.warn("Failed to define shader " + name + ": already exists."); return; } var id = ++_shdID; var offset = 0; var loop = function(i) { var def = defines[i]; def._offset = offset; var cnt = 1; if (void 0 !== def.min && void 0 !== def.max) { cnt = Math.ceil(.5 * (def.max - def.min)); def._map = function(value) { return value - this._min << def._offset; }.bind(def); } else def._map = function(value) { if (value) return 1 << def._offset; return 0; }.bind(def); offset += cnt; def._offset = offset; }; for (var i = 0; i < defines.length; ++i) loop(i); vert = this._precision + vert; frag = this._precision + frag; this._templates[name] = { id: id, name: name, vert: vert, frag: frag, defines: defines }; }; ProgramLib.prototype.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 key << 8 | tmpl.id; }; ProgramLib.prototype.getProgram = function getProgram(name, defines) { var key = this.getKey(name, defines); var program = this._cache[key]; if (program) return program; var tmpl = this._templates[name]; var customDef = _generateDefines(defines) + "\n"; var vert = _replaceMacroNums(tmpl.vert, defines); vert = customDef + _unrollLoops(vert); var frag = _replaceMacroNums(tmpl.frag, defines); frag = customDef + _unrollLoops(frag); program = new gfx.Program(this._device, { vert: vert, frag: frag }); program.link(); this._cache[key] = program; return program; }; var _m3_tmp$1 = mat3.create(); var _m4_tmp$2 = mat4.create(); var _stageInfos = new RecyclePool(function() { return { stage: null, items: null }; }, 8); var _float2_pool = new RecyclePool(function() { return new Float32Array(2); }, 8); var _float3_pool = new RecyclePool(function() { return new Float32Array(3); }, 8); var _float4_pool = new RecyclePool(function() { return new Float32Array(4); }, 8); var _float9_pool = new RecyclePool(function() { return new Float32Array(9); }, 8); var _float16_pool = new RecyclePool(function() { return new Float32Array(16); }, 8); var _float64_pool = new RecyclePool(function() { return new Float32Array(64); }, 8); var _int2_pool = new RecyclePool(function() { return new Int32Array(2); }, 8); var _int3_pool = new RecyclePool(function() { return new Int32Array(3); }, 8); var _int4_pool = new RecyclePool(function() { return new Int32Array(4); }, 8); var _int64_pool = new RecyclePool(function() { return new Int32Array(64); }, 8); var _type2uniformValue = {}; _type2uniformValue[enums.PARAM_INT] = function(value) { return value; }; _type2uniformValue[enums.PARAM_INT2] = function(value) { return vec2.array(_int2_pool.add(), value); }; _type2uniformValue[enums.PARAM_INT3] = function(value) { return vec3.array(_int3_pool.add(), value); }; _type2uniformValue[enums.PARAM_INT4] = function(value) { return vec4.array(_int4_pool.add(), value); }; _type2uniformValue[enums.PARAM_FLOAT] = function(value) { return value; }; _type2uniformValue[enums.PARAM_FLOAT2] = function(value) { return vec2.array(_float2_pool.add(), value); }; _type2uniformValue[enums.PARAM_FLOAT3] = function(value) { return vec3.array(_float3_pool.add(), value); }; _type2uniformValue[enums.PARAM_FLOAT4] = function(value) { return vec4.array(_float4_pool.add(), value); }; _type2uniformValue[enums.PARAM_COLOR3] = function(value) { return color3.array(_float3_pool.add(), value); }; _type2uniformValue[enums.PARAM_COLOR4] = function(value) { return color4.array(_float4_pool.add(), value); }; _type2uniformValue[enums.PARAM_MAT2] = function(value) { return mat2.array(_float4_pool.add(), value); }; _type2uniformValue[enums.PARAM_MAT3] = function(value) { return mat3.array(_float9_pool.add(), value); }; _type2uniformValue[enums.PARAM_MAT4] = function(value) { return mat4.array(_float16_pool.add(), value); }; var _type2uniformArrayValue = {}; _type2uniformArrayValue[enums.PARAM_INT] = { func: function func(values) { var result = _int64_pool.add(); for (var i = 0; i < values.length; ++i) result[i] = values[i]; return result; }, size: 1 }; _type2uniformArrayValue[enums.PARAM_INT2] = { func: function func(values) { var result = _int64_pool.add(); for (var i = 0; i < values.length; ++i) { result[2 * i] = values[i].x; result[2 * i + 1] = values[i].y; } return result; }, size: 2 }; _type2uniformArrayValue[enums.PARAM_INT3] = { func: void 0, size: 3 }; _type2uniformArrayValue[enums.PARAM_INT4] = { func: function func(values) { var result = _int64_pool.add(); for (var i = 0; i < values.length; ++i) { var v = values[i]; result[4 * i] = v.x; result[4 * i + 1] = v.y; result[4 * i + 2] = v.z; result[4 * i + 3] = v.w; } return result; }, size: 4 }; _type2uniformArrayValue[enums.PARAM_FLOAT] = { func: function func(values) { var result = _float64_pool.add(); for (var i = 0; i < values.length; ++i) result[i] = values[i]; return result; }, size: 1 }; _type2uniformArrayValue[enums.PARAM_FLOAT2] = { func: function func(values) { var result = _float64_pool.add(); for (var i = 0; i < values.length; ++i) { result[2 * i] = values[i].x; result[2 * i + 1] = values[i].y; } return result; }, size: 2 }; _type2uniformArrayValue[enums.PARAM_FLOAT3] = { func: void 0, size: 3 }; _type2uniformArrayValue[enums.PARAM_FLOAT4] = { func: function func(values) { var result = _float64_pool.add(); for (var i = 0; i < values.length; ++i) { var v = values[i]; result[4 * i] = v.x; result[4 * i + 1] = v.y; result[4 * i + 2] = v.z; result[4 * i + 3] = v.w; } return result; }, size: 4 }; _type2uniformArrayValue[enums.PARAM_COLOR3] = { func: void 0, size: 3 }; _type2uniformArrayValue[enums.PARAM_COLOR4] = { func: function func(values) { var result = _float64_pool.add(); for (var i = 0; i < values.length; ++i) { var v = values[i]; result[4 * i] = v.r; result[4 * i + 1] = v.g; result[4 * i + 2] = v.b; result[4 * i + 3] = v.a; } return result; }, size: 4 }; _type2uniformArrayValue[enums.PARAM_MAT2] = { func: function func(values) { var result = _float64_pool.add(); for (var i = 0; i < values.length; ++i) { var v = values[i]; result[4 * i] = v.m00; result[4 * i + 1] = v.m01; result[4 * i + 2] = v.m02; result[4 * i + 3] = v.m03; } return result; }, size: 4 }; _type2uniformArrayValue[enums.PARAM_MAT3] = { func: void 0, size: 9 }; _type2uniformArrayValue[enums.PARAM_MAT4] = { func: function func(values) { var result = _float64_pool.add(); for (var i = 0; i < values.length; ++i) { var v = values[i]; result[16 * i] = v.m00; result[16 * i + 1] = v.m01; result[16 * i + 2] = v.m02; result[16 * i + 3] = v.m03; result[16 * i + 4] = v.m04; result[16 * i + 5] = v.m05; result[16 * i + 6] = v.m06; result[16 * i + 7] = v.m07; result[16 * i + 8] = v.m08; result[16 * i + 9] = v.m09; result[16 * i + 10] = v.m10; result[16 * i + 11] = v.m11; result[16 * i + 12] = v.m12; result[16 * i + 13] = v.m13; result[16 * i + 14] = v.m14; result[16 * i + 15] = v.m15; } return result; }, size: 16 }; var Base = function Base(device, opts) { var obj; this._device = device; this._programLib = new ProgramLib(device, opts.programTemplates, opts.programChunks); this._opts = opts; this._type2defaultValue = (obj = {}, obj[enums.PARAM_INT] = 0, obj[enums.PARAM_INT2] = vec2.new(0, 0), obj[enums.PARAM_INT3] = vec3.new(0, 0, 0), obj[enums.PARAM_INT4] = vec4.new(0, 0, 0, 0), obj[enums.PARAM_FLOAT] = 0, obj[enums.PARAM_FLOAT2] = vec2.new(0, 0), obj[enums.PARAM_FLOAT3] = vec3.new(0, 0, 0), obj[enums.PARAM_FLOAT4] = vec4.new(0, 0, 0, 0), obj[enums.PARAM_COLOR3] = color3.new(0, 0, 0), obj[enums.PARAM_COLOR4] = color4.new(0, 0, 0, 1), obj[enums.PARAM_MAT2] = mat2.create(), obj[enums.PARAM_MAT3] = mat3.create(), obj[enums.PARAM_MAT4] = mat4.create(), obj[enums.PARAM_TEXTURE_2D] = opts.defaultTexture, obj[enums.PARAM_TEXTURE_CUBE] = opts.defaultTextureCube, obj); this._stage2fn = {}; this._usedTextureUnits = 0; this._viewPools = new RecyclePool(function() { return new View(); }, 8); this._drawItemsPools = new RecyclePool(function() { return { model: null, node: null, ia: null, effect: null, defines: null }; }, 100); this._stageItemsPools = new RecyclePool(function() { return new RecyclePool(function() { return { model: null, node: null, ia: null, effect: null, defines: null, technique: null, sortKey: -1 }; }, 100); }, 16); }; Base.prototype._resetTextuerUnit = function _resetTextuerUnit() { this._usedTextureUnits = 0; }; Base.prototype._allocTextuerUnit = function _allocTextuerUnit() { 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; }; Base.prototype._registerStage = function _registerStage(name, fn) { this._stage2fn[name] = fn; }; Base.prototype._reset = function _reset() { this._viewPools.reset(); this._stageItemsPools.reset(); }; Base.prototype._requestView = function _requestView() { return this._viewPools.add(); }; Base.prototype._render = function _render(view, scene) { var this$1 = this; 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.CLEAR_COLOR && (clearOpts.color = [ view._color.r, view._color.g, view._color.b, view._color.a ]); view._clearFlags & enums.CLEAR_DEPTH && (clearOpts.depth = view._depth); view._clearFlags & enums.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; for (var m = 0; m < model.drawItemCount; ++m) { var drawItem = this$1._drawItemsPools.add(); model.extractDrawItem(drawItem, m); } } _stageInfos.reset(); for (var i$1 = 0; i$1 < view._stages.length; ++i$1) { var stage = view._stages[i$1]; var stageItems = this$1._stageItemsPools.add(); stageItems.reset(); for (var j = 0; j < this._drawItemsPools.length; ++j) { var drawItem$1 = this$1._drawItemsPools.data[j]; var tech = drawItem$1.effect.getTechnique(stage); if (tech) { var stageItem = stageItems.add(); stageItem.model = drawItem$1.model; stageItem.node = drawItem$1.node; stageItem.ia = drawItem$1.ia; stageItem.effect = drawItem$1.effect; stageItem.defines = drawItem$1.defines; stageItem.technique = tech; stageItem.sortKey = -1; } } var stageInfo = _stageInfos.add(); stageInfo.stage = stage; stageInfo.items = stageItems; } for (var i$2 = 0; i$2 < _stageInfos.length; ++i$2) { var info = _stageInfos.data[i$2]; var fn = this$1._stage2fn[info.stage]; fn(view, info.items); } }; Base.prototype._draw = function _draw(item) { var this$1 = this; var device = this._device; var programLib = this._programLib; var node = item.node; var ia = item.ia; var effect = item.effect; var technique = item.technique; var defines = item.defines; _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$2); device.setUniform("model", mat4.array(_float16_pool.add(), _m4_tmp$2)); var inverse = mat3.invert(_m3_tmp$1, mat3.fromMat4(_m3_tmp$1, _m4_tmp$2)); if (inverse) { mat3.transpose(_m3_tmp$1, inverse); device.setUniform("normalMatrix", mat3.array(_float9_pool.add(), _m3_tmp$1)); } for (var i = 0; i < technique._parameters.length; ++i) { var prop = technique._parameters[i]; var param = effect.getProperty(prop.name); void 0 === param && (param = prop.val); void 0 === param && (param = this$1._type2defaultValue[prop.type]); if (void 0 === param) { console.warn("Failed to set technique property " + prop.name + ", value not found."); continue; } if (prop.type === enums.PARAM_TEXTURE_2D || prop.type === enums.PARAM_TEXTURE_CUBE) if (void 0 !== prop.size) { if (prop.size !== param.length) { console.error("The length of texture array (" + param.length + ") is not corrent(expect " + prop.size + ")."); continue; } var slots = _int64_pool.add(); for (var index = 0; index < param.length; ++index) slots[index] = this$1._allocTextuerUnit(); device.setTextureArray(prop.name, param, slots); } else device.setTexture(prop.name, param, this$1._allocTextuerUnit()); else { var convertedValue = void 0; if (void 0 !== prop.size) { var convertArray = _type2uniformArrayValue[prop.type]; if (void 0 === convertArray.func) { console.error("Uniform array of color3/int3/float3/mat3 can not be supportted!"); continue; } if (prop.size * convertArray.size > 64) { console.error("Uniform array is too long!"); continue; } convertedValue = convertArray.func(param); } else { var convertFn = _type2uniformValue[prop.type]; convertedValue = convertFn(param); } device.setUniform(prop.name, convertedValue); } } for (var i$1 = 0; i$1 < technique._passes.length; ++i$1) { var pass = technique._passes[i$1]; var count = ia.getPrimitiveCount(); device.setVertexBuffer(0, ia._vertexBuffer); ia._indexBuffer && device.setIndexBuffer(ia._indexBuffer); device.setPrimitiveType(ia._primitiveType); var program = programLib.getProgram(pass._programName, defines); device.setProgram(program); 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(); if (pass._stencilTest) { device.enableStencilTest(); 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$1._resetTextuerUnit(); } }; var renderer = { addStage: config.addStage, createIA: createIA, Pass: Pass, Technique: Technique, Effect: Effect, InputAssembler: InputAssembler, View: View, Light: Light, Camera: Camera, Model: Model, Scene: Scene, Base: Base, ProgramLib: ProgramLib }; Object.assign(renderer, enums); var _a16_view = new Float32Array(16); var _a16_proj = new Float32Array(16); var _a16_viewProj = new Float32Array(16); var ForwardRenderer = (function(superclass) { function ForwardRenderer(device, builtin) { superclass.call(this, device, builtin); this._registerStage("transparent", this._transparentStage.bind(this)); } superclass && (ForwardRenderer.__proto__ = superclass); ForwardRenderer.prototype = Object.create(superclass && superclass.prototype); ForwardRenderer.prototype.constructor = ForwardRenderer; ForwardRenderer.prototype.reset = function reset() { this._reset(); }; ForwardRenderer.prototype.render = function render(scene) { var this$1 = this; this._reset(); scene._cameras.sort((function(a, b) { return a._depth > b._depth ? 1 : a._depth < b._depth ? -1 : 0; })); for (var i = 0; i < scene._cameras.length; ++i) { var camera = scene._cameras.data[i]; camera._poolID = i; this$1.renderCamera(camera, scene); } }; ForwardRenderer.prototype.renderCamera = function renderCamera(camera, scene) { var canvas = this._device._gl.canvas; var view = camera.view; var dirty = camera.dirty; if (!view) { view = this._requestView(); dirty = true; } if (dirty) { var width = canvas.width; var height = canvas.height; if (camera._framebuffer) { width = camera._framebuffer._width; height = camera._framebuffer._height; } camera.extractView(view, width, height); } this._render(view, scene); }; ForwardRenderer.prototype._transparentStage = function _transparentStage(view, items) { var this$1 = this; this._device.setUniform("view", mat4.array(_a16_view, view._matView)); this._device.setUniform("proj", mat4.array(_a16_proj, view._matProj)); this._device.setUniform("viewProj", mat4.array(_a16_viewProj, view._matViewProj)); for (var i = 0; i < items.length; ++i) { var item = items.data[i]; this$1._draw(item); } }; return ForwardRenderer; })(renderer.Base); var chunks = {}; var templates = [ { name: "gray_sprite", vert: "\n \nuniform mat4 viewProj;\nattribute vec3 a_position;\nattribute mediump vec2 a_uv0;\nvarying mediump vec2 uv0;\n#ifndef useColor\nattribute lowp vec4 a_color;\nvarying lowp vec4 v_fragmentColor;\n#endif\nvoid main () {\n vec4 pos = viewProj * vec4(a_position, 1);\n gl_Position = pos;\n uv0 = a_uv0;\n #ifndef useColor\n v_fragmentColor = a_color;\n #endif\n}", frag: "\n \nuniform sampler2D texture;\nvarying mediump vec2 uv0;\n#ifdef useColor\n uniform lowp vec4 color;\n#else\n varying lowp vec4 v_fragmentColor;\n#endif\nvoid main () {\n #ifdef useColor\n vec4 o = color;\n #else\n vec4 o = v_fragmentColor;\n #endif\n vec4 c = o * texture2D(texture, uv0);\n float gray = 0.2126*c.r + 0.7152*c.g + 0.0722*c.b;\n gl_FragColor = vec4(gray, gray, gray, c.a);\n}", defines: [ { name: "useColor" } ] }, { name: "sprite", vert: "\n \nuniform mat4 viewProj;\n#ifdef use2DPos\nattribute vec2 a_position;\n#else\nattribute vec3 a_position;\n#endif\nattribute lowp vec4 a_color;\n#ifdef useModel\n uniform mat4 model;\n#endif\n#ifdef useTexture\n attribute mediump vec2 a_uv0;\n varying mediump vec2 uv0;\n#endif\n#ifndef useColor\nvarying lowp vec4 v_fragmentColor;\n#endif\nvoid main () {\n mat4 mvp;\n #ifdef useModel\n mvp = viewProj * model;\n #else\n mvp = viewProj;\n #endif\n #ifdef use2DPos\n vec4 pos = mvp * vec4(a_position, 0, 1);\n #else\n vec4 pos = mvp * vec4(a_position, 1);\n #endif\n #ifndef useColor\n v_fragmentColor = a_color;\n #endif\n #ifdef useTexture\n uv0 = a_uv0;\n #endif\n gl_Position = pos;\n}", frag: "\n \n#ifdef useTexture\n uniform sampler2D texture;\n varying mediump vec2 uv0;\n#endif\n#ifdef alphaTest\n uniform lowp float alphaThreshold;\n#endif\n#ifdef useColor\n uniform lowp vec4 color;\n#else\n varying lowp vec4 v_fragmentColor;\n#endif\nvoid main () {\n #ifdef useColor\n vec4 o = color;\n #else\n vec4 o = v_fragmentColor;\n #endif\n #ifdef useTexture\n o *= texture2D(texture, uv0);\n #endif\n #ifdef alphaTest\n if (o.a <= alphaThreshold)\n discard;\n #endif\n gl_FragColor = o;\n}", defines: [ { name: "useTexture" }, { name: "useModel" }, { name: "alphaTest" }, { name: "use2DPos" }, { name: "useColor" } ] }, { name: "spine", vert: "\n \nuniform mat4 viewProj;\n\n#ifdef use2DPos\n attribute vec2 a_position;\n#else\n attribute vec3 a_position;\n#endif\n\nattribute lowp vec4 a_color;\n#ifdef useTint\n attribute lowp vec4 a_color0;\n#endif\n\n#ifdef useModel\n uniform mat4 model;\n#endif\n\nattribute mediump vec2 a_uv0;\nvarying mediump vec2 uv0;\n\nvarying lowp vec4 v_light;\n#ifdef useTint\n varying lowp vec4 v_dark;\n#endif\n\nvoid main () {\n mat4 mvp;\n #ifdef useModel\n mvp = viewProj * model;\n #else\n mvp = viewProj;\n #endif\n\n #ifdef use2DPos\n vec4 pos = mvp * vec4(a_position, 0, 1);\n #else\n vec4 pos = mvp * vec4(a_position, 1);\n #endif\n\n v_light = a_color;\n #ifdef useTint\n v_dark = a_color0;\n #endif\n\n uv0 = a_uv0;\n\n gl_Position = pos;\n}", frag: "\n \nuniform sampler2D texture;\nvarying mediump vec2 uv0;\n\n#ifdef alphaTest\n uniform lowp float alphaThreshold;\n#endif\n\nvarying lowp vec4 v_light;\n#ifdef useTint\n varying lowp vec4 v_dark;\n#endif\n\nvoid main () {\n vec4 texColor = texture2D(texture, uv0);\n vec4 finalColor;\n\n #ifdef useTint\n finalColor.a = v_light.a * texColor.a;\n finalColor.rgb = ((texColor.a - 1.0) * v_dark.a + 1.0 - texColor.rgb) * v_dark.rgb + texColor.rgb * v_light.rgb;\n #else\n finalColor = texColor * v_light;\n #endif\n\n #ifdef alphaTest\n if (finalColor.a <= alphaThreshold)\n discard;\n #endif\n\n gl_FragColor = finalColor;\n}", defines: [ { name: "useModel" }, { name: "alphaTest" }, { name: "use2DPos" }, { name: "useTint" } ] } ]; var shaders = { chunks: chunks, templates: templates }; var BaseRenderData = function BaseRenderData() { this.material = null; this.vertexCount = 0; this.indiceCount = 0; }; var _pool; var _dataPool = new Pool(function() { return { x: 0, y: 0, u: 0, v: 0, color: 0 }; }, 128); var RenderData = (function(BaseRenderData$$1) { function RenderData() { BaseRenderData$$1.call(this); this._data = []; this._indices = []; this._pivotX = 0; this._pivotY = 0; this._width = 0; this._height = 0; this.uvDirty = true; this.vertDirty = true; } BaseRenderData$$1 && (RenderData.__proto__ = BaseRenderData$$1); RenderData.prototype = Object.create(BaseRenderData$$1 && BaseRenderData$$1.prototype); RenderData.prototype.constructor = RenderData; var prototypeAccessors = { type: { configurable: true }, dataLength: { configurable: true } }; prototypeAccessors.type.get = function() { return RenderData.type; }; prototypeAccessors.dataLength.get = function() { return this._data.length; }; prototypeAccessors.dataLength.set = function(length) { var data = this._data; if (data.length !== length) { for (var i = length; i < data.length; i++) _dataPool.free(data[i]); for (var i$1 = data.length; i$1 < length; i$1++) data[i$1] = _dataPool.alloc(); data.length = length; } }; RenderData.prototype.updateSizeNPivot = function updateSizeNPivot(width, height, pivotX, pivotY) { if (width !== this._width || height !== this._height || pivotX !== this._pivotX || pivotY !== this._pivotY) { this._width = width; this._height = height; this._pivotX = pivotX; this._pivotY = pivotY; this.vertDirty = true; } }; RenderData.alloc = function alloc() { return _pool.alloc(); }; RenderData.free = function free(data) { if (data instanceof RenderData) { for (var i = data.length - 1; i > 0; i--) _dataPool.free(data._data[i]); data._data.length = 0; data._indices.length = 0; data.material = null; data.uvDirty = true; data.vertDirty = true; data.vertexCount = 0; data.indiceCount = 0; _pool.free(data); } }; Object.defineProperties(RenderData.prototype, prototypeAccessors); return RenderData; })(BaseRenderData); RenderData.type = "RenderData"; _pool = new Pool(function() { return new RenderData(); }, 32); var IARenderData = (function(BaseRenderData$$1) { function IARenderData() { BaseRenderData$$1.call(this); this.ia = null; } BaseRenderData$$1 && (IARenderData.__proto__ = BaseRenderData$$1); IARenderData.prototype = Object.create(BaseRenderData$$1 && BaseRenderData$$1.prototype); IARenderData.prototype.constructor = IARenderData; var prototypeAccessors = { type: { configurable: true } }; prototypeAccessors.type.get = function() { return IARenderData.type; }; Object.defineProperties(IARenderData.prototype, prototypeAccessors); return IARenderData; })(BaseRenderData); IARenderData.type = "IARenderData"; var Asset = function Asset(persist) { void 0 === persist && (persist = true); this._loaded = false; this._persist = persist; }; Asset.prototype.unload = function unload() { this._loaded = false; }; Asset.prototype.reload = function reload() {}; var Texture$2 = (function(Asset$$1) { function Texture(persist) { void 0 === persist && (persist = true); Asset$$1.call(this, persist); this._texture = null; } Asset$$1 && (Texture.__proto__ = Asset$$1); Texture.prototype = Object.create(Asset$$1 && Asset$$1.prototype); Texture.prototype.constructor = Texture; Texture.prototype.getImpl = function getImpl() { return this._texture; }; Texture.prototype.getId = function getId() {}; Texture.prototype.destroy = function destroy() { this._texture && this._texture.destroy(); }; return Texture; })(Asset); 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; } function serializeDefines(defines) { var str = ""; for (var i = 0; i < defines.length; i++) str += defines[i].name + defines[i].value; return str; } function serializePass(pass) { 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); return str; } function computeHash(material) { var effect = material._effect; var hashData = ""; if (effect) { var i, j, techData, param, prop, propKey; hashData += serializeDefines(effect._defines); for (i = 0; i < effect._techniques.length; i++) { techData = effect._techniques[i]; hashData += techData.stageIDs; for (j = 0; j < techData.passes.length; j++) hashData += serializePass(techData.passes[j]); for (j = 0; j < techData._parameters.length; j++) { param = techData._parameters[j]; propKey = param.name; prop = effect._properties[propKey]; if (!prop) continue; switch (param.type) { case renderer.PARAM_INT: case renderer.PARAM_FLOAT: hashData += prop + ";"; break; case renderer.PARAM_INT2: case renderer.PARAM_FLOAT2: hashData += prop.x + "," + prop.y + ";"; break; case renderer.PARAM_INT4: case renderer.PARAM_FLOAT4: hashData += prop.x + "," + prop.y + "," + prop.z + "," + prop.w + ";"; break; case renderer.PARAM_COLOR4: hashData += prop.r + "," + prop.g + "," + prop.b + "," + prop.a + ";"; break; case renderer.PARAM_MAT2: hashData += prop.m00 + "," + prop.m01 + "," + prop.m02 + "," + prop.m03 + ";"; break; case renderer.PARAM_TEXTURE_2D: case renderer.PARAM_TEXTURE_CUBE: hashData += material._texIds[propKey] + ";"; break; case renderer.PARAM_INT3: case renderer.PARAM_FLOAT3: case renderer.PARAM_COLOR3: case renderer.PARAM_MAT3: case renderer.PARAM_MAT4: hashData += JSON.stringify(prop) + ";"; } } } } return hashData ? murmurhash2_32_gc(hashData, 666) : hashData; } var Material = (function(Asset$$1) { function Material(persist) { void 0 === persist && (persist = false); Asset$$1.call(this, persist); this._effect = null; this._texIds = {}; this._hash = ""; } Asset$$1 && (Material.__proto__ = Asset$$1); Material.prototype = Object.create(Asset$$1 && Asset$$1.prototype); Material.prototype.constructor = Material; var prototypeAccessors = { hash: { configurable: true } }; prototypeAccessors.hash.get = function() { return this._hash; }; Material.prototype.updateHash = function updateHash(value) { this._hash = value || computeHash(this); }; Object.defineProperties(Material.prototype, prototypeAccessors); return Material; })(Asset); var SpriteMaterial = (function(Material$$1) { function SpriteMaterial() { Material$$1.call(this, false); var pass = new renderer.Pass("sprite"); pass.setDepth(false, false); pass.setCullMode(gfx.CULL_NONE); pass.setBlend(gfx.BLEND_FUNC_ADD, gfx.BLEND_SRC_ALPHA, gfx.BLEND_ONE_MINUS_SRC_ALPHA, gfx.BLEND_FUNC_ADD, gfx.BLEND_SRC_ALPHA, gfx.BLEND_ONE_MINUS_SRC_ALPHA); var mainTech = new renderer.Technique([ "transparent" ], [ { name: "texture", type: renderer.PARAM_TEXTURE_2D }, { name: "color", type: renderer.PARAM_COLOR4 } ], [ pass ]); this._color = { r: 1, g: 1, b: 1, a: 1 }; this._effect = new renderer.Effect([ mainTech ], { color: this._color }, [ { name: "useTexture", value: true }, { name: "useModel", value: false }, { name: "alphaTest", value: false }, { name: "use2DPos", value: true }, { name: "useColor", value: true } ]); this._mainTech = mainTech; this._texture = null; } Material$$1 && (SpriteMaterial.__proto__ = Material$$1); SpriteMaterial.prototype = Object.create(Material$$1 && Material$$1.prototype); SpriteMaterial.prototype.constructor = SpriteMaterial; var prototypeAccessors = { effect: { configurable: true }, useTexture: { configurable: true }, useModel: { configurable: true }, use2DPos: { configurable: true }, useColor: { configurable: true }, texture: { configurable: true }, color: { configurable: true } }; prototypeAccessors.effect.get = function() { return this._effect; }; prototypeAccessors.useTexture.get = function() { return this._effect.getDefine("useTexture"); }; prototypeAccessors.useTexture.set = function(val) { this._effect.define("useTexture", val); }; prototypeAccessors.useModel.get = function() { return this._effect.getDefine("useModel"); }; prototypeAccessors.useModel.set = function(val) { this._effect.define("useModel", val); }; prototypeAccessors.use2DPos.get = function() { return this._effect.getDefine("use2DPos"); }; prototypeAccessors.use2DPos.set = function(val) { this._effect.define("use2DPos", val); }; prototypeAccessors.useColor.get = function() { return this._effect.getDefine("useColor"); }; prototypeAccessors.useColor.set = function(val) { this._effect.define("useColor", val); }; prototypeAccessors.texture.get = function() { return this._texture; }; prototypeAccessors.texture.set = function(val) { if (this._texture !== val) { this._texture = val; this._effect.setProperty("texture", val.getImpl()); this._texIds["texture"] = val.getId(); } }; prototypeAccessors.color.get = function() { return this._color; }; prototypeAccessors.color.set = function(val) { var color = this._color; color.r = val.r / 255; color.g = val.g / 255; color.b = val.b / 255; color.a = val.a / 255; this._effect.setProperty("color", color); }; SpriteMaterial.prototype.clone = function clone() { var copy = new SpriteMaterial(); copy._mainTech.copy(this._mainTech); copy.texture = this.texture; copy.useTexture = this.useTexture; copy.useModel = this.useModel; copy.use2DPos = this.use2DPos; copy.useColor = this.useColor; copy.updateHash(); return copy; }; Object.defineProperties(SpriteMaterial.prototype, prototypeAccessors); return SpriteMaterial; })(Material); var SpineMaterial = (function(Material$$1) { function SpineMaterial() { Material$$1.call(this, false); var pass = new renderer.Pass("spine"); pass.setDepth(false, false); pass.setCullMode(gfx.CULL_NONE); pass.setBlend(gfx.BLEND_FUNC_ADD, gfx.BLEND_SRC_ALPHA, gfx.BLEND_ONE_MINUS_SRC_ALPHA, gfx.BLEND_FUNC_ADD, gfx.BLEND_SRC_ALPHA, gfx.BLEND_ONE_MINUS_SRC_ALPHA); var mainTech = new renderer.Technique([ "transparent" ], [ { name: "texture", type: renderer.PARAM_TEXTURE_2D } ], [ pass ]); this._effect = new renderer.Effect([ mainTech ], {}, [ { name: "useModel", value: true }, { name: "alphaTest", value: false }, { name: "use2DPos", value: true }, { name: "useTint", value: false } ]); this._mainTech = mainTech; this._texture = null; } Material$$1 && (SpineMaterial.__proto__ = Material$$1); SpineMaterial.prototype = Object.create(Material$$1 && Material$$1.prototype); SpineMaterial.prototype.constructor = SpineMaterial; var prototypeAccessors = { effect: { configurable: true }, useModel: { configurable: true }, use2DPos: { configurable: true }, useTint: { configurable: false }, texture: { configurable: true } }; prototypeAccessors.effect.get = function() { return this._effect; }; prototypeAccessors.useModel.get = function() { return this._effect.getDefine("useModel"); }; prototypeAccessors.useModel.set = function(val) { this._effect.define("useModel", val); }; prototypeAccessors.use2DPos.get = function() { return this._effect.getDefine("use2DPos"); }; prototypeAccessors.use2DPos.set = function(val) { this._effect.define("use2DPos", val); }; prototypeAccessors.useTint.get = function() { return this._effect.getDefine("useTint"); }; prototypeAccessors.useTint.set = function(val) { this._effect.define("useTint", val); }; prototypeAccessors.texture.get = function() { return this._texture; }; prototypeAccessors.texture.set = function(val) { if (this._texture !== val) { this._texture = val; this._effect.setProperty("texture", val.getImpl()); this._texIds["texture"] = val.getId(); } }; SpineMaterial.prototype.clone = function clone() { var copy = new SpineMaterial(); copy._mainTech.copy(this._mainTech); copy.texture = this.texture; copy.useModel = this.useModel; copy.use2DPos = this.use2DPos; copy.useTint = this.useTint; copy._hash = this._hash; return copy; }; Object.defineProperties(SpineMaterial.prototype, prototypeAccessors); return SpineMaterial; })(Material); var GraySpriteMaterial = (function(Material$$1) { function GraySpriteMaterial() { Material$$1.call(this, false); var pass = new renderer.Pass("gray_sprite"); pass.setDepth(false, false); pass.setCullMode(gfx.CULL_NONE); pass.setBlend(gfx.BLEND_FUNC_ADD, gfx.BLEND_SRC_ALPHA, gfx.BLEND_ONE_MINUS_SRC_ALPHA, gfx.BLEND_FUNC_ADD, gfx.BLEND_SRC_ALPHA, gfx.BLEND_ONE_MINUS_SRC_ALPHA); var mainTech = new renderer.Technique([ "transparent" ], [ { name: "texture", type: renderer.PARAM_TEXTURE_2D }, { name: "color", type: renderer.PARAM_COLOR4 } ], [ pass ]); this._color = { r: 1, g: 1, b: 1, a: 1 }; this._effect = new renderer.Effect([ mainTech ], { color: this._color }, [ { name: "useColor", value: false } ]); this._mainTech = mainTech; this._texture = null; } Material$$1 && (GraySpriteMaterial.__proto__ = Material$$1); GraySpriteMaterial.prototype = Object.create(Material$$1 && Material$$1.prototype); GraySpriteMaterial.prototype.constructor = GraySpriteMaterial; var prototypeAccessors = { effect: { configurable: true }, texture: { configurable: true }, color: { configurable: true } }; prototypeAccessors.effect.get = function() { return this._effect; }; prototypeAccessors.texture.get = function() { return this._texture; }; prototypeAccessors.texture.set = function(val) { if (this._texture !== val) { this._texture = val; this._effect.setProperty("texture", val.getImpl()); this._texIds["texture"] = val.getId(); } }; prototypeAccessors.color.get = function() { return this._color; }; prototypeAccessors.color.set = function(val) { var color = this._color; color.r = val.r / 255; color.g = val.g / 255; color.b = val.b / 255; color.a = val.a / 255; this._effect.setProperty("color", color); }; GraySpriteMaterial.prototype.clone = function clone() { var copy = new GraySpriteMaterial(); copy._mainTech.copy(this._mainTech); copy.texture = this.texture; copy.color = this.color; copy.updateHash(); return copy; }; Object.defineProperties(GraySpriteMaterial.prototype, prototypeAccessors); return GraySpriteMaterial; })(Material); var StencilMaterial = (function(Material$$1) { function StencilMaterial() { Material$$1.call(this, false); this._pass = new renderer.Pass("sprite"); this._pass.setDepth(false, false); this._pass.setCullMode(gfx.CULL_NONE); this._pass.setBlend(gfx.BLEND_FUNC_ADD, gfx.BLEND_SRC_ALPHA, gfx.BLEND_ONE_MINUS_SRC_ALPHA, gfx.BLEND_FUNC_ADD, gfx.BLEND_SRC_ALPHA, gfx.BLEND_ONE_MINUS_SRC_ALPHA); var mainTech = new renderer.Technique([ "transparent" ], [ { name: "texture", type: renderer.PARAM_TEXTURE_2D }, { name: "alphaThreshold", type: renderer.PARAM_FLOAT }, { name: "color", type: renderer.PARAM_COLOR4 } ], [ this._pass ]); this._effect = new renderer.Effect([ mainTech ], { color: { r: 1, g: 1, b: 1, a: 1 } }, [ { name: "useTexture", value: true }, { name: "useModel", value: false }, { name: "alphaTest", value: true }, { name: "use2DPos", value: true }, { name: "useColor", value: true } ]); this._mainTech = mainTech; this._texture = null; } Material$$1 && (StencilMaterial.__proto__ = Material$$1); StencilMaterial.prototype = Object.create(Material$$1 && Material$$1.prototype); StencilMaterial.prototype.constructor = StencilMaterial; var prototypeAccessors = { effect: { configurable: true }, useTexture: { configurable: true }, useModel: { configurable: true }, useColor: { configurable: true }, texture: { configurable: true }, alphaThreshold: { configurable: true } }; prototypeAccessors.effect.get = function() { return this._effect; }; prototypeAccessors.useTexture.get = function() { this._effect.getDefine("useTexture"); }; prototypeAccessors.useTexture.set = function(val) { this._effect.define("useTexture", val); }; prototypeAccessors.useModel.get = function() { this._effect.getDefine("useModel"); }; prototypeAccessors.useModel.set = function(val) { this._effect.define("useModel", val); }; prototypeAccessors.useColor.get = function() { this._effect.getDefine("useColor"); }; prototypeAccessors.useColor.set = function(val) { this._effect.define("useColor", val); }; prototypeAccessors.texture.get = function() { return this._texture; }; prototypeAccessors.texture.set = function(val) { if (this._texture !== val) { this._texture = val; this._effect.setProperty("texture", val.getImpl()); this._texIds["texture"] = val.getId(); } }; prototypeAccessors.alphaThreshold.get = function() { return this._effect.getProperty("alphaThreshold"); }; prototypeAccessors.alphaThreshold.set = function(val) { this._effect.setProperty("alphaThreshold", val); }; StencilMaterial.prototype.clone = function clone() { var copy = new StencilMaterial(); copy._mainTech.copy(this._mainTech); copy.useTexture = this.useTexture; copy.useModel = this.useModel; copy.useColor = this.useColor; copy.texture = this.texture; copy.alphaThreshold = this.alphaThreshold; copy.updateHash(); return copy; }; Object.defineProperties(StencilMaterial.prototype, prototypeAccessors); return StencilMaterial; })(Material); var Device$2 = 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$2.prototype._restoreTexture = function _restoreTexture(unit) {}; Device$2.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$2.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$2.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); } }; var Texture2D$2 = 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$2.prototype.update = function update(options) { this.updateImage(options); }; Texture2D$2.prototype.updateImage = function updateImage(options) { if (options.images && options.images[0]) { var image = options.images[0]; image && image !== this._image && (this._image = image); } }; Texture2D$2.prototype.destroy = function destroy() { this._image = null; }; var canvas = { Device: Device$2, Texture2D: Texture2D$2 }; var Scene$2 = renderer.Scene; var Camera$2 = renderer.Camera; var View$2 = renderer.View; var Texture2D$4 = gfx.Texture2D; var Device$4 = gfx.Device; var Model$2 = renderer.Model; var InputAssembler$2 = renderer.InputAssembler; renderer.addStage("transparent"); var renderEngine = { Device: Device$4, ForwardRenderer: ForwardRenderer, Texture2D: Texture2D$4, canvas: canvas, Scene: Scene$2, Camera: Camera$2, View: View$2, Model: Model$2, RenderData: RenderData, IARenderData: IARenderData, InputAssembler: InputAssembler$2, Asset: Asset, TextureAsset: Texture$2, Material: Material, SpineMaterial: SpineMaterial, SpriteMaterial: SpriteMaterial, GraySpriteMaterial: GraySpriteMaterial, StencilMaterial: StencilMaterial, shaders: shaders, RecyclePool: RecyclePool, Pool: Pool, math: math, renderer: renderer, gfx: gfx }; module.exports = renderEngine; }), {} ], 204: [ (function(require, module, exports) { var DONOTHING = 0; var LOCAL_TRANSFORM = 1; var WORLD_TRANSFORM = 2; var TRANSFORM = LOCAL_TRANSFORM | WORLD_TRANSFORM; var UPDATE_RENDER_DATA = 4; var OPACITY = 8; var COLOR = 16; var RENDER = 32; var CUSTOM_IA_RENDER = 64; var CHILDREN = 128; var POST_UPDATE_RENDER_DATA = 256; var POST_RENDER = 512; var FINAL = 1024; var _batcher = void 0; 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); }; function mul(out, a, b) { var aa = a.m00, ab = a.m01, ac = a.m04, ad = a.m05, atx = a.m12, aty = a.m13; var ba = b.m00, bb = b.m01, bc = b.m04, bd = b.m05, btx = b.m12, bty = b.m13; if (0 !== bb || 0 !== bc) { out.m00 = aa * ba + ab * bc; out.m01 = aa * bb + ab * bd; out.m04 = ac * ba + ad * bc; out.m05 = ac * bb + ad * bd; out.m12 = ba * atx + bc * aty + btx; out.m13 = bb * atx + bd * aty + bty; } else { out.m00 = aa * ba; out.m01 = ab * bd; out.m04 = ac * ba; out.m05 = ad * bd; out.m12 = ba * atx + btx; out.m13 = bd * aty + bty; } } _proto._worldTransform = function(node) { _batcher.worldMatDirty++; var t = node._matrix; var position = node._position; t.m12 = position.x; t.m13 = position.y; mul(node._worldMatrix, t, node._parent._worldMatrix); node._renderFlag &= ~WORLD_TRANSFORM; this._next._func(node); _batcher.worldMatDirty--; }; _proto._color = function(node) { var comp = node._renderComponent; comp ? comp._updateColor() : node._renderFlag &= ~COLOR; this._next._func(node); }; _proto._opacity = function(node) { _batcher.parentOpacityDirty++; node._renderFlag &= ~OPACITY; this._next._func(node); _batcher.parentOpacityDirty--; }; _proto._updateRenderData = function(node) { var comp = node._renderComponent; comp._assembler.updateRenderData(comp); node._renderFlag &= ~UPDATE_RENDER_DATA; this._next._func(node); }; _proto._render = function(node) { var comp = node._renderComponent; _batcher._commitComp(comp, comp._assembler, node._cullingMask); this._next._func(node); }; _proto._customIARender = function(node) { var comp = node._renderComponent; _batcher._commitIA(comp, comp._assembler, node._cullingMask); 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 ? 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; 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._postUpdateRenderData = function(node) { var comp = node._renderComponent; comp._postAssembler && comp._postAssembler.updateRenderData(comp); node._renderFlag &= ~POST_UPDATE_RENDER_DATA; this._next._func(node); }; _proto._postRender = function(node) { var comp = node._renderComponent; _batcher._commitComp(comp, comp._postAssembler, node._cullingMask); 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) { var flow = new RenderFlow(); flow._next = next || EMPTY_FLOW; switch (flag) { case DONOTHING: flow._func = flow._doNothing; break; case LOCAL_TRANSFORM: flow._func = flow._localTransform; break; case WORLD_TRANSFORM: flow._func = flow._worldTransform; break; case COLOR: flow._func = flow._color; break; case OPACITY: flow._func = flow._opacity; break; case UPDATE_RENDER_DATA: flow._func = flow._updateRenderData; break; case RENDER: flow._func = flow._render; break; case CUSTOM_IA_RENDER: flow._func = flow._customIARender; break; case CHILDREN: flow._func = flow._children; break; case POST_UPDATE_RENDER_DATA: flow._func = flow._postUpdateRenderData; 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; RenderFlow.visit = function(scene) { _batcher.reset(); _batcher.walking = true; _cullingMask = 1 << scene.groupIndex; if (scene._renderFlag & WORLD_TRANSFORM) { _batcher.worldMatDirty++; scene._calculWorldMatrix(); scene._renderFlag &= ~WORLD_TRANSFORM; flows[scene._renderFlag]._func(scene); _batcher.worldMatDirty--; } else flows[scene._renderFlag]._func(scene); _batcher.terminate(); }; RenderFlow.init = function(batcher) { _batcher = batcher; flows[0] = EMPTY_FLOW; for (var i = 1; i < FINAL; i++) flows[i] = new RenderFlow(); }; RenderFlow.FLAG_DONOTHING = DONOTHING; RenderFlow.FLAG_LOCAL_TRANSFORM = LOCAL_TRANSFORM; RenderFlow.FLAG_WORLD_TRANSFORM = WORLD_TRANSFORM; RenderFlow.FLAG_TRANSFORM = TRANSFORM; RenderFlow.FLAG_COLOR = COLOR; RenderFlow.FLAG_OPACITY = OPACITY; RenderFlow.FLAG_UPDATE_RENDER_DATA = UPDATE_RENDER_DATA; RenderFlow.FLAG_RENDER = RENDER; RenderFlow.FLAG_CUSTOM_IA_RENDER = CUSTOM_IA_RENDER; RenderFlow.FLAG_CHILDREN = CHILDREN; RenderFlow.FLAG_POST_UPDATE_RENDER_DATA = POST_UPDATE_RENDER_DATA; RenderFlow.FLAG_POST_RENDER = POST_RENDER; RenderFlow.FLAG_FINAL = FINAL; module.exports = cc.RenderFlow = RenderFlow; }), {} ], 205: [ (function(require, module, exports) { var RenderTexture = require("../../../assets/CCRenderTexture"); var space = 2; function Atlas(width, height) { var texture = new RenderTexture(); texture.initWithSize(width, height); texture.update(); this._texture = texture; this._x = space; this._y = space; this._nexty = space; this._width = width; this._height = height; this._innerTextureInfos = {}; this._innerSpriteFrames = []; } Atlas.DEFAULT_HASH = new RenderTexture()._getHash(); cc.js.mixin(Atlas.prototype, { insertSpriteFrame: function(spriteFrame) { var rect = spriteFrame._rect, texture = spriteFrame._texture, info = this._innerTextureInfos[texture._id]; var sx = rect.x, sy = rect.y; if (info) { sx += info.x; sy += info.y; } else { var width = texture.width, height = texture.height; 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) return null; this._texture.drawTextureAt(texture, this._x - 1, this._y); this._texture.drawTextureAt(texture, this._x + 1, this._y); this._texture.drawTextureAt(texture, this._x, this._y - 1); this._texture.drawTextureAt(texture, this._x, this._y + 1); this._texture.drawTextureAt(texture, this._x, this._y); this._innerTextureInfos[texture._id] = { x: this._x, y: this._y, texture: texture }; sx += this._x; sy += this._y; this._x += width + space; this._dirty = true; } var frame = { x: sx, y: sy, texture: this._texture }; this._innerSpriteFrames.push(spriteFrame); return frame; }, update: function() { if (!this._dirty) return; this._texture.update(); this._dirty = false; }, reset: function() { this._x = space; this._y = space; this._nexty = space; var frames = this._innerSpriteFrames; for (var i = 0, l = frames.length; i < l; i++) { var frame = frames[i]; if (!frame.isValid) continue; frame._resetDynamicAtlasFrame(); } this._innerSpriteFrames.length = 0; this._innerTextureInfos = {}; }, destroy: function() { this.reset(); this._texture.destroy(); } }); module.exports = Atlas; }), { "../../../assets/CCRenderTexture": 43 } ], 206: [ (function(require, module, exports) { var Atlas = require("./atlas"); var _atlases = []; var _atlasIndex = -1; var _maxAtlasCount = 5; var _textureSize = 2048; var _minFrameSize = 8; var _maxFrameSize = 512; var _debugNode = null; function newAtlas() { var atlas = _atlases[++_atlasIndex]; if (!atlas) { atlas = new Atlas(_textureSize, _textureSize); _atlases.push(atlas); } return atlas; } function beforeSceneLoad() { dynamicAtlasManager.reset(); } var _enabled = false; var dynamicAtlasManager = { 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 textureSize() { return _textureSize; }, set textureSize(value) { _textureSize = value; }, get maxFrameSize() { return _maxFrameSize; }, set maxFrameSize(value) { _maxFrameSize = value; }, insertSpriteFrame: function(spriteFrame) { false; if (!_enabled || _atlasIndex === _maxAtlasCount || !spriteFrame || spriteFrame._original) return null; var texture = spriteFrame._texture; if (texture instanceof cc.RenderTexture) return null; var w = texture.width, h = texture.height; if (w > _maxFrameSize || h > _maxFrameSize || w <= _minFrameSize || h <= _minFrameSize || texture._getHash() !== Atlas.DEFAULT_HASH) return null; var atlas = _atlases[_atlasIndex]; atlas || (atlas = newAtlas()); var frame = atlas.insertSpriteFrame(spriteFrame); if (!frame && _atlasIndex !== _maxAtlasCount) { atlas = newAtlas(); return atlas.insertSpriteFrame(spriteFrame); } return frame; }, reset: function() { for (var i = 0, l = _atlases.length; i < l; i++) _atlases[i].destroy(); _atlases.length = 0; _atlasIndex = -1; }, showDebug: false, update: function() { if (!this.enabled) return; for (var i = 0; i <= _atlasIndex; i++) _atlases[i].update(); } }; module.exports = cc.dynamicAtlasManager = dynamicAtlasManager; }), { "./atlas": 205 } ], 207: [ (function(require, module, exports) { var macro = require("../../../platform/CCMacro"); var Label = require("../../../components/CCLabel"); var Overflow = Label.Overflow; var textUtils = require("../../../utils/text-utils"); var FontLetterDefinition = function() { this._u = 0; this._v = 0; this._width = 0; this._height = 0; this._offsetX = 0; this._offsetY = 0; this._textureID = 0; this._validDefinition = false; this._xAdvance = 0; }; cc.FontAtlas = function(fntConfig) { this._letterDefinitions = {}; }; cc.FontAtlas.prototype = { constructor: cc.FontAtlas, addLetterDefinitions: function(letter, letterDefinition) { this._letterDefinitions[letter] = letterDefinition; }, cloneLetterDefinition: function() { var copyLetterDefinitions = {}; for (var key in this._letterDefinitions) { var value = new FontLetterDefinition(); cc.js.mixin(value, this._letterDefinitions[key]); copyLetterDefinitions[key] = value; } return copyLetterDefinitions; }, assignLetterDefinitions: function(letterDefinition) { for (var key in this._letterDefinitions) { var newValue = letterDefinition[key]; var oldValue = this._letterDefinitions[key]; cc.js.mixin(oldValue, newValue); } }, scaleFontLetterDefinition: function(scaleFactor) { for (var fontDefinition in this._letterDefinitions) { var letterDefinitions = this._letterDefinitions[fontDefinition]; letterDefinitions._width *= scaleFactor; letterDefinitions._height *= scaleFactor; letterDefinitions._offsetX *= scaleFactor; letterDefinitions._offsetY *= scaleFactor; letterDefinitions._xAdvance *= scaleFactor; } }, getLetterDefinitionForChar: function(char) { var hasKey = this._letterDefinitions.hasOwnProperty(char.charCodeAt(0)); var letterDefinition = void 0; letterDefinition = hasKey ? this._letterDefinitions[char.charCodeAt(0)] : null; return letterDefinition; } }; var LetterInfo = function() { this._char = ""; this._valid = true; this._positionX = 0; this._positionY = 0; this._lineIndex = 0; }; var _tmpRect = cc.rect(); var _comp = null; var _horizontalKernings = []; var _lettersInfo = []; var _linesWidth = []; var _linesOffsetX = []; var _labelDimensions = cc.size(); var _fontAtlas = null; 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 _string = ""; var _fontSize = 0; var _originFontSize = 0; var _contentSize = cc.size(); 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; module.exports = { updateRenderData: function(comp) { if (!comp._renderData.vertDirty) return; if (_comp === comp) return; _comp = comp; this._updateProperties(); this._updateContent(); _comp._actualFontSize = _fontSize; _comp.node.setContentSize(_contentSize); _comp._renderData.vertDirty = _comp._renderData.uvDirty = false; _comp = null; this._resetProperties(); }, _updateFontScale: function() { _bmfontScale = _fontSize / _originFontSize; }, _updateProperties: function() { var fontAsset = _comp.font; _spriteFrame = fontAsset.spriteFrame; _fntConfig = fontAsset._fntConfig; _fontAtlas = _comp._fontAtlas; if (!_fontAtlas) { _fontAtlas = new cc.FontAtlas(_fntConfig); var fontDict = _fntConfig.fontDefDictionary; for (var fontDef in fontDict) { var letterDefinition = new FontLetterDefinition(); var rect = fontDict[fontDef].rect; letterDefinition._offsetX = fontDict[fontDef].xOffset; letterDefinition._offsetY = fontDict[fontDef].yOffset; letterDefinition._width = rect.width; letterDefinition._height = rect.height; letterDefinition._u = rect.x; letterDefinition._v = rect.y; letterDefinition._textureID = 0; letterDefinition._validDefinition = true; letterDefinition._xAdvance = fontDict[fontDef].xAdvance; _fontAtlas.addLetterDefinitions(fontDef, letterDefinition); } _comp._fontAtlas = _fontAtlas; } _string = _comp.string.toString(); _fontSize = _comp.fontSize; _originFontSize = _fntConfig.fontSize; _contentSize.width = _comp.node._contentSize.width; _contentSize.height = _comp.node._contentSize.height; _hAlign = _comp.horizontalAlign; _vAlign = _comp.verticalAlign; _spacingX = _comp.spacingX; _overflow = _comp.overflow; _lineHeight = _comp._lineHeight; _isWrapText = _overflow !== Overflow.NONE && (_overflow === Overflow.RESIZE_HEIGHT || _comp.enableWrapText); this._setupBMFontOverflowMetrics(); }, _resetProperties: function() { _fontAtlas = null; _fntConfig = null; _spriteFrame = null; }, _updateContent: function() { this._updateFontScale(); this._computeHorizontalKerningForText(); this._alignText(); }, _computeHorizontalKerningForText: function() { var string = _string; var stringLen = string.length; var kerningDict = _fntConfig.kerningDict; var horizontalKernings = _horizontalKernings; 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; } }, _multilineTextWrap: function(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); this._updateFontScale(); var letterDefinitions = _fontAtlas._letterDefinitions; for (var index = 0; index < textLen; ) { var character = _string.charAt(index); if ("\n" === character) { _linesWidth.push(letterRight); letterRight = 0; lineIndex++; nextTokenX = 0; nextTokenY -= _lineHeight * _bmfontScale + _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 = _fontAtlas.getLetterDefinitionForChar(character); if (!letterDef) { this._recordPlaceholderInfo(letterIndex, character); console.log("Can't find letter definition in texture atlas " + _fntConfig.atlasName + " for letter:" + character); continue; } var letterX = nextLetterX + letterDef._offsetX * _bmfontScale; if (_isWrapText && _maxLineWidth > 0 && nextTokenX > 0 && letterX + letterDef._width * _bmfontScale > _maxLineWidth && !textUtils.isUnicodeSpace(character)) { _linesWidth.push(letterRight); letterRight = 0; lineIndex++; nextTokenX = 0; nextTokenY -= _lineHeight * _bmfontScale + _lineSpacing; newLine = true; break; } letterPosition.x = letterX; letterPosition.y = nextTokenY - letterDef._offsetY * _bmfontScale; this._recordLetterInfo(letterDefinitions, letterPosition, character, letterIndex, lineIndex); letterIndex + 1 < _horizontalKernings.length && letterIndex < textLen - 1 && (nextLetterX += _horizontalKernings[letterIndex + 1]); nextLetterX += letterDef._xAdvance * _bmfontScale + _spacingX; tokenRight = letterPosition.x + letterDef._width * _bmfontScale; tokenHighestY < letterPosition.y && (tokenHighestY = letterPosition.y); tokenLowestY > letterPosition.y - letterDef._height * _bmfontScale && (tokenLowestY = letterPosition.y - letterDef._height * _bmfontScale); } if (newLine) continue; nextTokenX = nextLetterX; letterRight = tokenRight; highestY < tokenHighestY && (highestY = tokenHighestY); lowestY > tokenLowestY && (lowestY = tokenLowestY); longestLine < letterRight && (longestLine = letterRight); index += tokenLen; } _linesWidth.push(letterRight); _numberOfLines = lineIndex + 1; _textDesiredHeight = _numberOfLines * _lineHeight * _bmfontScale; _numberOfLines > 1 && (_textDesiredHeight += (_numberOfLines - 1) * _lineSpacing); _contentSize.width = _labelWidth; _contentSize.height = _labelHeight; _labelWidth <= 0 && (_contentSize.width = parseFloat(longestLine.toFixed(2))); _labelHeight <= 0 && (_contentSize.height = parseFloat(_textDesiredHeight.toFixed(2))); _tailoredTopY = _contentSize.height; _tailoredBottomY = 0; highestY > 0 && (_tailoredTopY = _contentSize.height + highestY); lowestY < -_textDesiredHeight && (_tailoredBottomY = _textDesiredHeight + lowestY); return true; }, _getFirstCharLen: function() { return 1; }, _getFirstWordLen: function(text, startIndex, textLen) { var character = text.charAt(startIndex); if (textUtils.isUnicodeCJK(character) || "\n" === character || textUtils.isUnicodeSpace(character)) return 1; var len = 1; var letterDef = _fontAtlas.getLetterDefinitionForChar(character); if (!letterDef) return len; var nextLetterX = letterDef._xAdvance * _bmfontScale + _spacingX; var letterX = void 0; for (var index = startIndex + 1; index < textLen; ++index) { character = text.charAt(index); letterDef = _fontAtlas.getLetterDefinitionForChar(character); if (!letterDef) break; letterX = nextLetterX + letterDef._offsetX * _bmfontScale; if (letterX + letterDef._width * _bmfontScale > _maxLineWidth && !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; }, _multilineTextWrapByWord: function() { return this._multilineTextWrap(this._getFirstWordLen); }, _multilineTextWrapByChar: function() { return this._multilineTextWrap(this._getFirstCharLen); }, _recordPlaceholderInfo: function(letterIndex, char) { if (letterIndex >= _lettersInfo.length) { var tmpInfo = new LetterInfo(); _lettersInfo.push(tmpInfo); } _lettersInfo[letterIndex]._char = char; _lettersInfo[letterIndex]._valid = false; }, _recordLetterInfo: function(letterDefinitions, letterPosition, character, letterIndex, lineIndex) { if (letterIndex >= _lettersInfo.length) { var tmpInfo = new LetterInfo(); _lettersInfo.push(tmpInfo); } character = character.charCodeAt(0); _lettersInfo[letterIndex]._lineIndex = lineIndex; _lettersInfo[letterIndex]._char = character; _lettersInfo[letterIndex]._valid = letterDefinitions[character]._validDefinition; _lettersInfo[letterIndex]._positionX = letterPosition.x; _lettersInfo[letterIndex]._positionY = letterPosition.y; }, _alignText: function() { _textDesiredHeight = 0; _linesWidth.length = 0; _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); }, _scaleFontSizeDown: function(fontSize) { var shouldUpdateContent = true; if (!fontSize) { fontSize = .1; shouldUpdateContent = false; } _fontSize = fontSize; shouldUpdateContent && this._updateContent(); }, _shrinkLabelToContentSize: function(lambda) { var fontSize = _fontSize; var originalLineHeight = _lineHeight; var fontAtlas = _fontAtlas; var i = 0; var tempLetterDefinition = fontAtlas.cloneLetterDefinition(); var flag = true; while (lambda()) { ++i; var newFontSize = fontSize - i; flag = false; if (newFontSize <= 0) break; var scale = newFontSize / fontSize; fontAtlas.assignLetterDefinitions(tempLetterDefinition); fontAtlas.scaleFontLetterDefinition(scale); _lineHeight = originalLineHeight * scale; _lineBreakWithoutSpaces ? this._multilineTextWrapByChar() : this._multilineTextWrapByWord(); this._computeAlignmentOffset(); } _lineHeight = originalLineHeight; fontAtlas.assignLetterDefinitions(tempLetterDefinition); flag || fontSize - i >= 0 && this._scaleFontSizeDown(fontSize - i); }, _isVerticalClamp: function() { return _textDesiredHeight > _contentSize.height; }, _isHorizontalClamp: function() { var letterDefinitions = _fontAtlas._letterDefinitions; var letterClamp = false; for (var ctr = 0, l = _string.length; ctr < l; ++ctr) { var letterInfo = _lettersInfo[ctr]; if (letterInfo._valid) { var letterDef = letterDefinitions[letterInfo._char]; var px = letterInfo._positionX + letterDef._width / 2 * _bmfontScale; var lineIndex = letterInfo._lineIndex; 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; }, _isHorizontalClamped: function(px, lineIndex) { var wordWidth = _linesWidth[lineIndex]; var letterOverClamp = px > _contentSize.width || px < 0; return _isWrapText ? wordWidth > _contentSize.width && letterOverClamp : letterOverClamp; }, _updateQuads: function() { var letterDefinitions = _fontAtlas._letterDefinitions; var texture = _spriteFrame._texture; var node = _comp.node; var renderData = _comp._renderData; renderData.dataLength = renderData.vertexCount = renderData.indiceCount = 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 = letterDefinitions[letterInfo._char]; _tmpRect.height = letterDef._height; _tmpRect.width = letterDef._width; _tmpRect.x = letterDef._u; _tmpRect.y = letterDef._v; var py = letterInfo._positionY + _letterOffsetY; if (_labelHeight > 0) { if (py > _tailoredTopY) { var clipTop = py - _tailoredTopY; _tmpRect.y += clipTop; _tmpRect.height -= clipTop; py -= clipTop; } py - letterDef._height * _bmfontScale < _tailoredBottomY && (_tmpRect.height = py < _tailoredBottomY ? 0 : py - _tailoredBottomY); } var lineIndex = letterInfo._lineIndex; var px = letterInfo._positionX + letterDef._width / 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._width) { ret = false; break; } _tmpRect.width = 0; } if (_tmpRect.height > 0 && _tmpRect.width > 0) { 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 = _tmpRect.x; _tmpRect.x = rect.x + rect.height - _tmpRect.y - _tmpRect.height - trimmedTop; _tmpRect.y = originalX + rect.y - trimmedLeft; _tmpRect.y < 0 && (_tmpRect.height = _tmpRect.height + trimmedTop); } else { _tmpRect.x += rect.x - trimmedLeft; _tmpRect.y += rect.y + trimmedTop; } var letterPositionX = letterInfo._positionX + _linesOffsetX[letterInfo._lineIndex]; this.appendQuad(renderData, texture, _tmpRect, isRotated, letterPositionX - appx, py - appy, _bmfontScale); } } return ret; }, appendQuad: function(renderData, texture, rect, rotated, x, y, scale) {}, _computeAlignmentOffset: function() { _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]); } switch (_vAlign) { case macro.VerticalTextAlignment.TOP: _letterOffsetY = _contentSize.height; break; case macro.VerticalTextAlignment.CENTER: _letterOffsetY = (_contentSize.height + _textDesiredHeight) / 2; break; case macro.VerticalTextAlignment.BOTTOM: _letterOffsetY = _textDesiredHeight; } }, _setupBMFontOverflowMetrics: function() { 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; _labelDimensions.width = newWidth; _labelDimensions.height = newHeight; _maxLineWidth = newWidth; } }; }), { "../../../components/CCLabel": 70, "../../../platform/CCMacro": 166, "../../../utils/text-utils": 250 } ], 208: [ (function(require, module, exports) { function LabelFrame() { this._rect = null; this.uv = []; this._texture = null; this._original = null; } LabelFrame.prototype = { constructor: LabelFrame, getRect: function() { return cc.rect(this._rect); }, setRect: function(rect) { this._rect = rect; this._texture && this._calculateUV(); }, _setDynamicAtlasFrame: function(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() { 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(texture) { this._texture = texture; this._rect = cc.rect(0, 0, texture.width, texture.height); this._calculateUV(); }, _calculateUV: function() { 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; }), {} ], 209: [ (function(require, module, exports) { var macro = require("../../../platform/CCMacro"); 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 Overflow = Label.Overflow; var WHITE = cc.Color.WHITE; var space = 2; var LetterInfo = function() { this.char = ""; this.valid = true; this.x = 0; this.y = 0; this.line = 0; this.hash = ""; }; var FontLetterDefinition = function() { this.u = 0; this.v = 0; this.w = 0; this.h = 0; this.texture = null; this.offsetX = 0; this.offsetY = 0; this.valid = false; this.xAdvance = 0; }; var _backgroundStyle = "rgba(255, 255, 255, 0.005)"; 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._hash = char.charCodeAt(0) + labelInfo.hash; } LetterTexture.prototype = { constructor: LetterTexture, updateRenderData: function() { this._updateProperties(); this._updateTexture(); }, _updateProperties: function() { 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._width = parseFloat(width.toFixed(2)) + 2 * this._labelInfo.margin; this._height = this._labelInfo.lineHeight; 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() { var context = this._context; var labelInfo = this._labelInfo, width = this._canvas.width, height = this._canvas.height; context.textAlign = "center"; context.textBaseline = "middle"; context.clearRect(0, 0, width, height); context.fillStyle = _backgroundStyle; context.fillRect(0, 0, width, height); context.font = labelInfo.fontDesc; var startX = width / 2; var startY = height / 2; var color = labelInfo.color; context.lineJoin = "round"; context.fillStyle = "rgba(" + color.r + ", " + color.g + ", " + color.b + ", 1)"; if (labelInfo.isOutlined) { 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() { this._texture.destroy(); this._texture = null; Label._canvasPool.put(this._data); } }; function LetterAtlas(width, height) { var texture = new RenderTexture(); texture.initWithSize(width, height); texture.update(); this._texture = texture; this._x = space; this._y = space; this._nexty = space; this._width = width; this._height = height; this._letterDefinitions = {}; cc.director.on(cc.Director.EVENT_BEFORE_SCENE_LAUNCH, this.beforeSceneLoad, this); } cc.js.mixin(LetterAtlas.prototype, { insertLetterTexture: function(letterTexture) { var texture = letterTexture._texture; var width = texture.width, height = texture.height; 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) return null; this._texture.drawTextureAt(texture, this._x, this._y); this._dirty = true; var letterDefinition = new FontLetterDefinition(); letterDefinition.u = this._x; letterDefinition.v = this._y; letterDefinition.texture = this._texture; letterDefinition.valid = true; letterDefinition.w = letterTexture._width; letterDefinition.h = letterTexture._height; letterDefinition.xAdvance = letterTexture._width; this._x += width + space; this._letterDefinitions[letterTexture._hash] = letterDefinition; return letterDefinition; }, update: function() { if (!this._dirty) return; this._texture.update(); this._dirty = false; }, reset: function() { this._x = space; this._y = space; this._nexty = space; var chars = this._letterDefinitions; for (var i = 0, l = chars.length; i < l; i++) { var char = chars[i]; if (!char.isValid) continue; char.destroy(); } this._letterDefinitions = {}; }, destroy: function() { this.reset(); this._texture.destroy(); }, beforeSceneLoad: function() { this.destroy(); var texture = new RenderTexture(); texture.initWithSize(this._width, this._height); texture.update(); this._texture = texture; }, getLetter: function(key) { return this._letterDefinitions[key]; }, addLetterDefinitions: function(key, letterDefinition) { this._letterDefinitions[key] = letterDefinition; }, cloneLetterDefinition: function() { var copyLetterDefinitions = {}; for (var key in this._letterDefinitions) { var value = new FontLetterDefinition(); cc.js.mixin(value, this._letterDefinitions[key]); copyLetterDefinitions[key] = value; } return copyLetterDefinitions; }, assignLetterDefinitions: function(letterDefinition) { for (var key in this._letterDefinitions) { var newValue = letterDefinition[key]; var oldValue = this._letterDefinitions[key]; cc.js.mixin(oldValue, newValue); } }, scaleFontLetterDefinition: function(scaleFactor) { for (var fontDefinition in this._letterDefinitions) { var letterDefinitions = this._letterDefinitions[fontDefinition]; letterDefinitions.w *= scaleFactor; letterDefinitions.h *= scaleFactor; letterDefinitions.offsetX *= scaleFactor; letterDefinitions.offsetY *= scaleFactor; letterDefinitions.xAdvance *= scaleFactor; } }, getLetterDefinitionForChar: function(char, labelInfo) { var hash = char.charCodeAt(0) + labelInfo.hash; var letterDefinition = this._letterDefinitions[hash]; if (!letterDefinition) { var temp = new LetterTexture(char, labelInfo); temp.updateRenderData(); letterDefinition = this.insertLetterTexture(temp); temp.destroy(); } return letterDefinition; } }); var _tmpRect = cc.rect(); var _comp = null; var _horizontalKernings = []; var _lettersInfo = []; var _linesWidth = []; var _linesOffsetX = []; var _labelDimensions = cc.size(); var _fontAtlas = null; 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 _lineSpacing = 0; var _string = ""; var _fontSize = 0; var _originFontSize = 0; var _contentSize = cc.size(); 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 _atlasWidth = 2048; var _atlasHeight = 2048; var _fontFamily = ""; var _isBold = false; var _labelInfo = { fontSize: 0, lineHeight: 0, hash: "", fontFamily: "", fontDesc: "Arial", hAlign: 0, vAlign: 0, color: WHITE, isOutlined: false, out: WHITE, margin: 0 }; module.exports = { _getAssemblerData: function() { _fontAtlas || (_fontAtlas = new LetterAtlas(_atlasWidth, _atlasHeight)); return _fontAtlas._texture; }, updateRenderData: function(comp) { if (!comp._renderData.vertDirty) return; if (_comp === comp) return; _comp = comp; this._updateFontFamily(comp); _labelInfo.fontFamily = _fontFamily; this._updateProperties(); _labelInfo.fontDesc = this._getFontDesc(); this._updateContent(); _comp._actualFontSize = _fontSize; _comp.node.setContentSize(_contentSize); _comp._renderData.vertDirty = _comp._renderData.uvDirty = false; _comp = null; this._resetProperties(); }, _updateFontScale: function() { _bmfontScale = _fontSize / _originFontSize; }, _updateProperties: function() { _string = _comp.string.toString(); _fontSize = _comp.fontSize; _originFontSize = _fontSize; _contentSize.width = _comp.node._contentSize.width; _contentSize.height = _comp.node._contentSize.height; _hAlign = _comp.horizontalAlign; _vAlign = _comp.verticalAlign; _spacingX = _comp.spacingX; _overflow = _comp.overflow; _lineHeight = _comp._lineHeight; _isBold = _comp._isBold; _isWrapText = _overflow !== Overflow.NONE && (_overflow === Overflow.RESIZE_HEIGHT || _comp.enableWrapText); var outline = OUTLINE_SUPPORTED && _comp.getComponent(LabelOutline); if (outline && outline.enabled) { _labelInfo.isOutlined = true; _labelInfo.margin = outline.width; _labelInfo.out = outline.color; _labelInfo.out.a = outline.color.a * _comp.node.color.a / 255; } else { _labelInfo.isOutlined = false; _labelInfo.margin = 0; } _labelInfo.lineHeight = _lineHeight; _labelInfo.fontSize = _fontSize; _labelInfo.fontFamily = _fontFamily; _labelInfo.color = _comp.node.color; _labelInfo.hash = this._computeHash(_labelInfo); this._setupBMFontOverflowMetrics(); }, _updateFontFamily: function(comp) { if (comp.useSystemFont) _fontFamily = comp.fontFamily; else if (comp.font) if (comp.font._nativeAsset) _fontFamily = comp.font._nativeAsset; else { _fontFamily = cc.loader.getRes(comp.font.nativeUrl); _fontFamily || cc.loader.load(comp.font.nativeUrl, (function(err, fontFamily) { _fontFamily = fontFamily || "Arial"; comp.font._nativeAsset = fontFamily; comp._updateRenderData(true); })); } else _fontFamily = "Arial"; }, _computeHash: function(labelInfo) { var hashData = ""; var color = labelInfo.color.toHEX("#rrggbb"); var out = ""; labelInfo.isOutlined && (out = labelInfo.out.toHEX("#rrggbb")); return hashData + labelInfo.fontSize + labelInfo.fontFamily + color + out; }, _getFontDesc: function() { var fontDesc = _fontSize.toString() + "px "; fontDesc += _fontFamily; _isBold && (fontDesc = "bold " + fontDesc); return fontDesc; }, _resetProperties: function() {}, _updateContent: function() { this._updateFontScale(); this._alignText(); }, _computeHorizontalKerningForText: function() { var string = _string; var stringLen = string.length; var kerningDict = _fntConfig.kerningDict; var horizontalKernings = _horizontalKernings; 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; } }, _multilineTextWrap: function(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); this._updateFontScale(); for (var index = 0; index < textLen; ) { var character = _string.charAt(index); if ("\n" === character) { _linesWidth.push(letterRight); letterRight = 0; lineIndex++; nextTokenX = 0; nextTokenY -= _lineHeight * _bmfontScale + _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 = _fontAtlas.getLetterDefinitionForChar(character, _labelInfo); if (!letterDef) { this._recordPlaceholderInfo(letterIndex, character); continue; } var letterX = nextLetterX + letterDef.offsetX * _bmfontScale; if (_isWrapText && _maxLineWidth > 0 && nextTokenX > 0 && letterX + letterDef.w * _bmfontScale > _maxLineWidth && !textUtils.isUnicodeSpace(character)) { _linesWidth.push(letterRight); letterRight = 0; lineIndex++; nextTokenX = 0; nextTokenY -= _lineHeight * _bmfontScale + _lineSpacing; newLine = true; break; } letterPosition.x = letterX; letterPosition.y = nextTokenY - letterDef.offsetY * _bmfontScale; this._recordLetterInfo(letterPosition, character, letterIndex, lineIndex); letterIndex + 1 < _horizontalKernings.length && letterIndex < textLen - 1 && (nextLetterX += _horizontalKernings[letterIndex + 1]); nextLetterX += letterDef.xAdvance * _bmfontScale + _spacingX; tokenRight = letterPosition.x + letterDef.w * _bmfontScale; 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; } _linesWidth.push(letterRight); _numberOfLines = lineIndex + 1; _textDesiredHeight = _numberOfLines * _lineHeight * _bmfontScale; _numberOfLines > 1 && (_textDesiredHeight += (_numberOfLines - 1) * _lineSpacing); _contentSize.width = _labelWidth; _contentSize.height = _labelHeight; _labelWidth <= 0 && (_contentSize.width = parseFloat(longestLine.toFixed(2))); _labelHeight <= 0 && (_contentSize.height = parseFloat(_textDesiredHeight.toFixed(2))); _tailoredTopY = _contentSize.height; _tailoredBottomY = 0; highestY > 0 && (_tailoredTopY = _contentSize.height + highestY); lowestY < -_textDesiredHeight && (_tailoredBottomY = _textDesiredHeight + lowestY); return true; }, _getFirstCharLen: function() { return 1; }, _getFirstWordLen: function(text, startIndex, textLen) { var character = text.charAt(startIndex); if (textUtils.isUnicodeCJK(character) || "\n" === character || textUtils.isUnicodeSpace(character)) return 1; var len = 1; var letterDef = _fontAtlas.getLetterDefinitionForChar(character, _labelInfo); if (!letterDef) return len; var nextLetterX = letterDef.xAdvance * _bmfontScale + _spacingX; var letterX = void 0; for (var index = startIndex + 1; index < textLen; ++index) { character = text.charAt(index); letterDef = _fontAtlas.getLetterDefinitionForChar(character, _labelInfo); 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; }, _multilineTextWrapByWord: function() { return this._multilineTextWrap(this._getFirstWordLen); }, _multilineTextWrapByChar: function() { return this._multilineTextWrap(this._getFirstCharLen); }, _recordPlaceholderInfo: function(letterIndex, char) { if (letterIndex >= _lettersInfo.length) { var tmpInfo = new LetterInfo(); _lettersInfo.push(tmpInfo); } _lettersInfo[letterIndex].char = char; _lettersInfo[letterIndex].hash = char.charCodeAt(0) + _labelInfo.hash; _lettersInfo[letterIndex].valid = false; }, _recordLetterInfo: function(letterPosition, character, letterIndex, lineIndex) { if (letterIndex >= _lettersInfo.length) { var tmpInfo = new LetterInfo(); _lettersInfo.push(tmpInfo); } var char = character.charCodeAt(0); var key = char + _labelInfo.hash; _lettersInfo[letterIndex].line = lineIndex; _lettersInfo[letterIndex].char = character; _lettersInfo[letterIndex].hash = key; _lettersInfo[letterIndex].valid = _fontAtlas.getLetter(key).valid; _lettersInfo[letterIndex].x = letterPosition.x; _lettersInfo[letterIndex].y = letterPosition.y; }, _alignText: function() { _textDesiredHeight = 0; _linesWidth.length = 0; _lineBreakWithoutSpaces ? this._multilineTextWrapByChar() : this._multilineTextWrapByWord(); this._computeAlignmentOffset(); this._updateQuads(); }, _scaleFontSizeDown: function(fontSize) { var shouldUpdateContent = true; if (!fontSize) { fontSize = .1; shouldUpdateContent = false; } _fontSize = fontSize; shouldUpdateContent && this._updateContent(); }, _isVerticalClamp: function() { return _textDesiredHeight > _contentSize.height; }, _isHorizontalClamp: function() { var letterClamp = false; for (var ctr = 0, l = _string.length; ctr < l; ++ctr) { var letterInfo = _lettersInfo[ctr]; if (letterInfo.valid) { var letterDef = _fontAtlas.getLetter(letterInfo.hash); var px = letterInfo.x + letterDef.w / 2 * _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; }, _isHorizontalClamped: function(px, lineIndex) { var wordWidth = _linesWidth[lineIndex]; var letterOverClamp = px > _contentSize.width || px < 0; return _isWrapText ? wordWidth > _contentSize.width && letterOverClamp : letterOverClamp; }, _updateQuads: function() { var texture = _fontAtlas._texture; var node = _comp.node; var renderData = _comp._renderData; renderData.dataLength = renderData.vertexCount = renderData.indiceCount = 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 = _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 && (_tmpRect.height = py < _tailoredBottomY ? 0 : py - _tailoredBottomY); } 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 letterPositionX = letterInfo.x + _linesOffsetX[letterInfo.line]; this.appendQuad(renderData, texture, _tmpRect, false, letterPositionX - appx, py - appy, _bmfontScale); } } return ret; }, appendQuad: function(renderData, texture, rect, rotated, x, y, scale) {}, _computeAlignmentOffset: function() { _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]); } switch (_vAlign) { case macro.VerticalTextAlignment.TOP: _letterOffsetY = _contentSize.height; break; case macro.VerticalTextAlignment.CENTER: _letterOffsetY = (_contentSize.height + _textDesiredHeight) / 2; break; case macro.VerticalTextAlignment.BOTTOM: _letterOffsetY = _textDesiredHeight; } }, _setupBMFontOverflowMetrics: function() { 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; _labelDimensions.width = newWidth; _labelDimensions.height = newHeight; _maxLineWidth = newWidth; } }; }), { "../../../assets/CCRenderTexture": 43, "../../../components/CCComponent": 68, "../../../components/CCLabel": 70, "../../../components/CCLabelOutline": 71, "../../../platform/CCMacro": 166, "../../../utils/text-utils": 250 } ], 210: [ (function(require, module, exports) { var macro = require("../../../platform/CCMacro"); var textUtils = require("../../../utils/text-utils"); var Component = require("../../../components/CCComponent"); var Label = require("../../../components/CCLabel"); var LabelOutline = require("../../../components/CCLabelOutline"); var Overflow = Label.Overflow; var WHITE = cc.Color.WHITE; var OUTLINE_SUPPORTED = cc.js.isChildClassOf(LabelOutline, Component); 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(); var _lineHeight = 0; var _hAlign = 0; var _vAlign = 0; var _color = null; var _fontFamily = ""; var _overflow = Overflow.NONE; var _isWrapText = false; var _invisibleAlpha = (1 / 255).toFixed(3); var _isOutlined = false; var _outlineColor = null; var _outlineWidth = 0; var _margin = 0; var _isBold = false; var _isItalic = false; var _isUnderline = false; var _sharedLabelData = void 0; module.exports = { _getAssemblerData: function() { _sharedLabelData = Label._canvasPool.get(); _sharedLabelData.canvas.width = _sharedLabelData.canvas.height = 1; return _sharedLabelData; }, _resetAssemblerData: function(assemblerData) { assemblerData && Label._canvasPool.put(assemblerData); }, updateRenderData: function(comp) { if (!comp._renderData.vertDirty) return; this._updateFontFamily(comp); this._updateProperties(comp); this._calculateLabelFont(); this._calculateSplitedStrings(); this._updateLabelDimensions(); this._calculateTextBaseline(); this._updateTexture(comp); this._calDynamicAtlas(comp); comp._actualFontSize = _fontSize; comp.node.setContentSize(_canvasSize); this._updateVerts(comp); comp._renderData.vertDirty = comp._renderData.uvDirty = false; _context = null; _canvas = null; _texture = null; }, _updateVerts: function() {}, _updateFontFamily: function(comp) { if (comp.useSystemFont) _fontFamily = comp.fontFamily; else if (comp.font) if (comp.font._nativeAsset) _fontFamily = comp.font._nativeAsset; else { _fontFamily = cc.loader.getRes(comp.font.nativeUrl); _fontFamily || cc.loader.load(comp.font.nativeUrl, (function(err, fontFamily) { _fontFamily = fontFamily || "Arial"; comp.font._nativeAsset = fontFamily; comp._updateRenderData(true); })); } else _fontFamily = "Arial"; }, _updateProperties: function(comp) { var assemblerData = comp._assemblerData; _context = assemblerData.context; _canvas = assemblerData.canvas; _texture = comp._frame._original ? comp._frame._original._texture : comp._frame._texture; _string = comp.string.toString(); _fontSize = comp._fontSize; _drawFontsize = _fontSize; _overflow = comp.overflow; _canvasSize.width = comp.node.width; _canvasSize.height = comp.node.height; _lineHeight = comp._lineHeight; _hAlign = comp.horizontalAlign; _vAlign = comp.verticalAlign; _color = comp.node.color; _isBold = comp._isBold; _isItalic = comp._isItalic; _isUnderline = comp._isUnderline; _isWrapText = _overflow !== Overflow.NONE && (_overflow === Overflow.RESIZE_HEIGHT || comp.enableWrapText); var outline = OUTLINE_SUPPORTED && comp.getComponent(LabelOutline); if (outline && outline.enabled) { _isOutlined = true; _margin = _outlineWidth = outline.width; _outlineColor = cc.color(outline.color); _outlineColor.a = _outlineColor.a * comp.node.color.a / 255; } else { _isOutlined = false; _margin = 0; } }, _calculateFillTextStartPosition: function() { var lineHeight = this._getLineHeight(); var lineCount = _splitedStrings.length; var labelX = void 0; var firstLinelabelY = void 0; labelX = _hAlign === macro.TextAlignment.RIGHT ? _canvasSize.width - _margin : _hAlign === macro.TextAlignment.CENTER ? _canvasSize.width / 2 : 0 + _margin; firstLinelabelY = _vAlign === macro.VerticalTextAlignment.TOP ? window.qq && window.qq.getSystemInfoSync ? _canvasSize.height / 2 - lineHeight * (lineCount - 1) / 2 : 0 : _vAlign === macro.VerticalTextAlignment.CENTER ? _canvasSize.height / 2 - lineHeight * (lineCount - 1) / 2 : _canvasSize.height - lineHeight * (lineCount - 1); return cc.v2(labelX, firstLinelabelY); }, _updateTexture: function(comp) { _context.clearRect(0, 0, _canvas.width, _canvas.height); _context.fillStyle = "rgba(" + _color.r + ", " + _color.g + ", " + _color.b + ", " + _invisibleAlpha + ")"; _context.fillRect(0, 0, _canvas.width, _canvas.height); _context.font = _fontDesc; var startPosition = this._calculateFillTextStartPosition(); var lineHeight = this._getLineHeight(); _context.lineJoin = "round"; _context.fillStyle = "rgba(" + _color.r + ", " + _color.g + ", " + _color.b + ", 1)"; var underlineStartPosition = void 0; for (var i = 0; i < _splitedStrings.length; ++i) { if (_isOutlined) { var strokeColor = _outlineColor || WHITE; _context.strokeStyle = "rgba(" + strokeColor.r + ", " + strokeColor.g + ", " + strokeColor.b + ", " + strokeColor.a / 255 + ")"; _context.lineWidth = 2 * _outlineWidth; _context.strokeText(_splitedStrings[i], startPosition.x, startPosition.y + i * lineHeight); } _context.fillText(_splitedStrings[i], startPosition.x, startPosition.y + i * lineHeight); if (_isUnderline) { underlineStartPosition = this._calculateUnderlineStartPosition(); _context.save(); _context.beginPath(); _context.lineWidth = _fontSize / 8; _context.strokeStyle = "rgba(" + _color.r + ", " + _color.g + ", " + _color.b + ", 1)"; _context.moveTo(underlineStartPosition.x, underlineStartPosition.y + i * lineHeight - 1); _context.lineTo(underlineStartPosition.x + _canvas.width, underlineStartPosition.y + i * lineHeight - 1); _context.stroke(); _context.restore(); } } _texture.handleLoadedTexture(); }, _calDynamicAtlas: function(comp) { if (comp.cacheMode !== Label.CacheMode.BITMAP) return; comp._frame._original || comp._frame.setRect(cc.rect(0, 0, _canvas.width, _canvas.height)); comp._calDynamicAtlas(); }, _calculateUnderlineStartPosition: function() { var lineHeight = this._getLineHeight(); var lineCount = _splitedStrings.length; var labelX = void 0; var firstLinelabelY = void 0; labelX = 0 + _margin; firstLinelabelY = _vAlign === macro.VerticalTextAlignment.TOP ? window.qq && window.qq.getSystemInfoSync ? _canvasSize.height / 2 - lineHeight * (lineCount - 1) / 2 + _fontSize / 2 : 0 : _vAlign === macro.VerticalTextAlignment.CENTER ? _canvasSize.height / 2 - lineHeight * (lineCount - 1) / 2 + _fontSize / 2 : _canvasSize.height - lineHeight * (lineCount - 1); return cc.v2(labelX, firstLinelabelY); }, _updateLabelDimensions: function() { var paragraphedStrings = _string.split("\n"); if (_overflow === Overflow.RESIZE_HEIGHT) _canvasSize.height = _splitedStrings.length * this._getLineHeight(); else if (_overflow === Overflow.NONE) { _splitedStrings = paragraphedStrings; var canvasSizeX = 0; var canvasSizeY = 0; for (var i = 0; i < paragraphedStrings.length; ++i) { var paraLength = textUtils.safeMeasureText(_context, paragraphedStrings[i]); canvasSizeX = canvasSizeX > paraLength ? canvasSizeX : paraLength; } canvasSizeY = _splitedStrings.length * this._getLineHeight(); _canvasSize.width = parseFloat(canvasSizeX.toFixed(2)) + 2 * _margin; _canvasSize.height = parseFloat(canvasSizeY.toFixed(2)); _isItalic && (_canvasSize.width += _drawFontsize * Math.tan(.20943951)); } _canvas.width !== _canvasSize.width && (_canvas.width = _canvasSize.width); _canvas.height !== _canvasSize.height && (_canvas.height = _canvasSize.height); }, _calculateTextBaseline: function() { var node = this._node; var hAlign = void 0; var vAlign = void 0; hAlign = _hAlign === macro.TextAlignment.RIGHT ? "right" : _hAlign === macro.TextAlignment.CENTER ? "center" : "left"; _context.textAlign = hAlign; vAlign = _vAlign === macro.VerticalTextAlignment.TOP ? window.qq && window.qq.getSystemInfoSync ? "middle" : "top" : _vAlign === macro.VerticalTextAlignment.CENTER ? "middle" : "bottom"; _context.textBaseline = vAlign; }, _calculateSplitedStrings: function() { var paragraphedStrings = _string.split("\n"); if (_isWrapText) { _splitedStrings = []; var canvasWidthNoMargin = _canvasSize.width - 2 * _margin; for (var i = 0; i < paragraphedStrings.length; ++i) { var allWidth = textUtils.safeMeasureText(_context, paragraphedStrings[i]); var textFragment = textUtils.fragmentText(paragraphedStrings[i], allWidth, canvasWidthNoMargin, this._measureText(_context)); _splitedStrings = _splitedStrings.concat(textFragment); } } else _splitedStrings = paragraphedStrings; }, _getFontDesc: function() { var fontDesc = _fontSize.toString() + "px "; fontDesc += _fontFamily; _isBold && (fontDesc = "bold " + fontDesc); return fontDesc; }, _getLineHeight: function() { var nodeSpacingY = _lineHeight; nodeSpacingY = 0 === nodeSpacingY ? _fontSize : nodeSpacingY * _fontSize / _drawFontsize; return 0 | nodeSpacingY; }, _calculateParagraphLength: function(paragraphedStrings, ctx) { var paragraphLength = []; for (var i = 0; i < paragraphedStrings.length; ++i) { var width = textUtils.safeMeasureText(ctx, paragraphedStrings[i]); paragraphLength.push(width); } return paragraphLength; }, _measureText: function(ctx) { return function(string) { return textUtils.safeMeasureText(ctx, string); }; }, _calculateLabelFont: function() { _fontDesc = this._getFontDesc(); _context.font = _fontDesc; if (_overflow === Overflow.SHRINK) { var paragraphedStrings = _string.split("\n"); var paragraphLength = this._calculateParagraphLength(paragraphedStrings, _context); var i = 0; var totalHeight = 0; var maxLength = 0; if (_isWrapText) { var canvasWidthNoMargin = _canvasSize.width - 2 * _margin; var canvasHeightNoMargin = _canvasSize.height - 2 * _margin; if (canvasWidthNoMargin < 0 || canvasHeightNoMargin < 0) { _fontDesc = this._getFontDesc(); _context.font = _fontDesc; return; } totalHeight = canvasHeightNoMargin + 1; maxLength = canvasWidthNoMargin + 1; var actualFontSize = _fontSize + 1; var textFragment = ""; var tryDivideByTwo = true; var startShrinkFontSize = 0 | actualFontSize; while (totalHeight > canvasHeightNoMargin || maxLength > canvasWidthNoMargin) { if (tryDivideByTwo) actualFontSize = startShrinkFontSize / 2 | 0; else { actualFontSize = startShrinkFontSize - 1; startShrinkFontSize = actualFontSize; } if (actualFontSize <= 0) { cc.logID(4003); break; } _fontSize = actualFontSize; _fontDesc = this._getFontDesc(); _context.font = _fontDesc; totalHeight = 0; for (i = 0; i < paragraphedStrings.length; ++i) { var j = 0; var allWidth = textUtils.safeMeasureText(_context, paragraphedStrings[i]); textFragment = textUtils.fragmentText(paragraphedStrings[i], allWidth, canvasWidthNoMargin, this._measureText(_context)); while (j < textFragment.length) { var measureWidth = textUtils.safeMeasureText(_context, textFragment[j]); maxLength = measureWidth; totalHeight += this._getLineHeight(); ++j; } } if (tryDivideByTwo) if (totalHeight > canvasHeightNoMargin) startShrinkFontSize = 0 | actualFontSize; else { tryDivideByTwo = false; totalHeight = canvasHeightNoMargin + 1; } } } else { totalHeight = paragraphedStrings.length * this._getLineHeight(); for (i = 0; i < paragraphedStrings.length; ++i) maxLength < paragraphLength[i] && (maxLength = paragraphLength[i]); var scaleX = (_canvasSize.width - 2 * _margin) / maxLength; var scaleY = _canvasSize.height / totalHeight; _fontSize = _drawFontsize * Math.min(1, scaleX, scaleY) | 0; _fontDesc = this._getFontDesc(); _context.font = _fontDesc; } } } }; }), { "../../../components/CCComponent": 68, "../../../components/CCLabel": 70, "../../../components/CCLabelOutline": 71, "../../../platform/CCMacro": 166, "../../../utils/text-utils": 250 } ], 211: [ (function(require, module, exports) { "use strict"; 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; }; }), {} ], 212: [ (function(require, module, exports) { var Helper = require("../../../../graphics/helper"); var PointFlags = require("../../../../graphics/types").PointFlags; var MeshBuffer = require("../../mesh-buffer"); var vfmtPosColor = require("../../vertex-format").vfmtPosColor; var renderer = require("../../../index"); var renderEngine = renderer.renderEngine; var IARenderData = renderEngine.IARenderData; var InputAssembler = renderEngine.InputAssembler; var Point = cc.Class({ name: "cc.GraphicsPoint", extends: cc.Vec2, ctor: function(x, y) { this.reset(); }, reset: function() { 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() { 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 = []; this._renderDatas = []; this._dataOffset = 0; } cc.js.mixin(Impl.prototype, { moveTo: function(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(x, y) { this._addPoint(x, y, PointFlags.PT_CORNER); this._commandx = x; this._commandy = y; }, bezierCurveTo: function(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(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(cx, cy, r, startAngle, endAngle, counterclockwise) { Helper.arc(this, cx, cy, r, startAngle, endAngle, counterclockwise); }, ellipse: function(cx, cy, rx, ry) { Helper.ellipse(this, cx, cy, rx, ry); this._curPath.complex = false; }, circle: function(cx, cy, r) { Helper.ellipse(this, cx, cy, r, r); this._curPath.complex = false; }, rect: function(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(x, y, w, h, r) { Helper.roundRect(this, x, y, w, h, r); this._curPath.complex = false; }, clear: function(comp, clean) { this._pathLength = 0; this._pathOffset = 0; this._pointsOffset = 0; this._dataOffset = 0; this._curPath = null; var datas = this._renderDatas; if (clean) { this._paths.length = 0; this._points.length = 0; 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]; var meshbuffer = _data.meshbuffer; meshbuffer.reset(); } }, close: function() { this._curPath.closed = true; }, _addPath: function() { 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(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); }, requestRenderData: function() { var renderData = new IARenderData(); var meshbuffer = new MeshBuffer(renderer._handle, vfmtPosColor); renderData.meshbuffer = meshbuffer; this._renderDatas.push(renderData); var ia = new InputAssembler(); ia._vertexBuffer = meshbuffer._vb; ia._indexBuffer = meshbuffer._ib; ia._start = 0; renderData.ia = ia; return renderData; }, getRenderDatas: function() { 0 === this._renderDatas.length && this.requestRenderData(); return this._renderDatas; } }); module.exports = Impl; }), { "../../../../graphics/helper": 108, "../../../../graphics/types": 110, "../../../index": 202, "../../mesh-buffer": 228, "../../vertex-format": 233 } ], 213: [ (function(require, module, exports) { var Graphics = require("../../../../graphics/graphics"); var PointFlags = require("../../../../graphics/types").PointFlags; var LineJoin = Graphics.LineJoin; var LineCap = Graphics.LineCap; var Earcut = require("./earcut"); var Impl = 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; var abs = Math.abs; var _renderData = null; var _impl = null; var _curColor = 0; 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 graphicsAssembler = { useModel: true, createImpl: function(graphics) { return new Impl(graphics); }, updateRenderData: function(graphics) { var datas = graphics._impl.getRenderDatas(); for (var i = 0, l = datas.length; i < l; i++) datas[i].material = graphics.getMaterial(); }, fillBuffers: function(graphics, renderer) { renderer._flush(); var tempNode = renderer.node; renderer.node = graphics.node; this.renderIA(graphics, renderer); renderer.node = tempNode; }, renderIA: function(graphics, renderer) { var node = graphics.node; var nodeColor = node.color, nodeR = nodeColor.r / 255, nodeG = nodeColor.g / 255, nodeB = nodeColor.b / 255, nodeA = nodeColor.a / 255; var impl = graphics._impl; var renderDatas = impl.getRenderDatas(); for (var index = 0, length = renderDatas.length; index < length; index++) { var renderData = renderDatas[index]; var meshbuffer = renderData.meshbuffer; renderData.ia._count = meshbuffer.indiceStart; renderer._flushIA(renderData); meshbuffer.uploadData(); } }, genRenderData: function(graphics, cverts) { var renderDatas = _impl.getRenderDatas(); var renderData = renderDatas[_impl._dataOffset]; var meshbuffer = renderData.meshbuffer; var maxVertsCount = meshbuffer.vertexStart + cverts; if (maxVertsCount > MAX_VERTEX || 3 * maxVertsCount > MAX_INDICE) { ++_impl._dataOffset; maxVertsCount = cverts; if (_impl._dataOffset < renderDatas.length) renderData = renderDatas[_impl._dataOffset]; else { renderData = _impl.requestRenderData(graphics); renderDatas[_impl._dataOffset] = renderData; } renderData.material = graphics.getMaterial(); meshbuffer = renderData.meshbuffer; } maxVertsCount > meshbuffer.vertexOffset && meshbuffer.requestStatic(cverts, 3 * cverts); return renderData; }, stroke: function(graphics) { _curColor = graphics._strokeColor._val; this._flattenPaths(graphics._impl); this._expandStroke(graphics); graphics._impl._updatePathOffset = true; }, fill: function(graphics) { _curColor = graphics._fillColor._val; this._expandFill(graphics); graphics._impl._updatePathOffset = true; }, _expandStroke: function(graphics) { var w = .5 * graphics.lineWidth, lineCap = graphics.lineCap, lineJoin = graphics.lineJoin, miterLimit = graphics.miterLimit; _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 renderData = _renderData = this.genRenderData(graphics, cverts), meshbuffer = renderData.meshbuffer, vData = meshbuffer._vData, iData = meshbuffer._iData; for (var _i = _impl._pathOffset, _l = _impl._pathLength; _i < _l; _i++) { var _path = paths[_i]; var pts = _path.points; var _pointsLength = pts.length; var offset = meshbuffer.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; } if (!loop) { var dPos = p1.sub(p0); dPos.normalizeSelf(); var dx = dPos.x; var dy = dPos.y; lineCap === LineCap.BUTT ? this._buttCap(p0, dx, dy, w, 0) : lineCap === LineCap.SQUARE ? this._buttCap(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); this._vset(p1.x - p1.dmx * w, p1.y - p1.dmy * w); } p0 = p1; p1 = pts[j + 1]; } if (loop) { var vDataoOfset = 3 * offset; this._vset(vData[vDataoOfset], vData[vDataoOfset + 1]); this._vset(vData[vDataoOfset + 3], vData[vDataoOfset + 4]); } else { var _dPos = p1.sub(p0); _dPos.normalizeSelf(); var _dx = _dPos.x; var _dy = _dPos.y; lineCap === LineCap.BUTT ? this._buttCap(p1, _dx, _dy, w, 0) : lineCap === LineCap.BUTT || lineCap === LineCap.SQUARE ? this._buttCap(p1, _dx, _dy, w, w) : lineCap === LineCap.ROUND && this._roundCapEnd(p1, _dx, _dy, w, ncap); } var indicesOffset = meshbuffer.indiceStart; for (var _start = offset + 2, _end = meshbuffer.vertexStart; _start < _end; _start++) { iData[indicesOffset++] = _start - 2; iData[indicesOffset++] = _start - 1; iData[indicesOffset++] = _start; } meshbuffer.indiceStart = indicesOffset; } _renderData = null; _impl = null; }, _expandFill: function(graphics) { _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 renderData = _renderData = this.genRenderData(graphics, cverts), meshbuffer = renderData.meshbuffer, vData = meshbuffer._vData, iData = meshbuffer._iData; for (var _i2 = _impl._pathOffset, _l2 = _impl._pathLength; _i2 < _l2; _i2++) { var _path2 = paths[_i2]; var pts = _path2.points; var _pointsLength2 = pts.length; if (0 === _pointsLength2) continue; var offset = meshbuffer.vertexStart; for (var j = 0; j < _pointsLength2; ++j) this._vset(pts[j].x, pts[j].y); var indicesOffset = meshbuffer.indiceStart; if (_path2.complex) { var earcutData = []; for (var _j = offset, end = meshbuffer.vertexStart; _j < end; _j++) { var vDataOffset = 3 * _j; 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 = meshbuffer.vertexStart; start < _end2; start++) { iData[indicesOffset++] = first; iData[indicesOffset++] = start - 1; iData[indicesOffset++] = start; } } meshbuffer.indiceStart = indicesOffset; } _renderData = null; _impl = null; }, _calculateJoins: function(impl, w, lineJoin, miterLimit) { var iw = 0; 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); 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]; } } }, _flattenPaths: function(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 (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]; } } }, _chooseBevel: function(bevel, p0, p1, w) { var x = p1.x; var y = p1.y; var x0 = void 0, y0 = void 0, x1 = void 0, y1 = void 0; 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 ]; }, _buttCap: function(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); this._vset(px - dlx * w, py - dly * w); }, _roundCapStart: function(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); this._vset(px, py); } this._vset(px + dlx * w, py + dly * w); this._vset(px - dlx * w, py - dly * w); }, _roundCapEnd: function(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); this._vset(px - dlx * w, py - dly * w); 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); this._vset(px - dlx * ax + dx * ay, py - dly * ax + dy * ay); } }, _roundJoin: function(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); this._vset(p1x - dlx0 * rw, p1.y - dly0 * rw); 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); this._vset(rx, ry); } this._vset(lx1, ly1); this._vset(p1x - dlx1 * rw, p1y - dly1 * rw); } 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); this._vset(rx0, ry0); var _n = clamp(ceil((_a2 - _a) / PI) * ncap, 2, ncap); for (var _i3 = 0; _i3 < _n; _i3++) { var _u = _i3 / (_n - 1); var _a3 = _a + _u * (_a2 - _a); var lx = p1x + cos(_a3) * lw; var ly = p1y + sin(_a3) * lw; this._vset(lx, ly); this._vset(p1x, p1y); } this._vset(p1x + dlx1 * rw, p1y + dly1 * rw); this._vset(rx1, ry1); } }, _bevelJoin: function(p0, p1, lw, rw) { var rx0 = void 0, ry0 = void 0, rx1 = void 0, ry1 = void 0; var lx0 = void 0, ly0 = void 0, lx1 = void 0, ly1 = void 0; 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); this._vset(p1.x - dlx0 * rw, p1.y - dly0 * rw); this._vset(lx1, ly1); this._vset(p1.x - dlx1 * rw, p1.y - dly1 * rw); } 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); this._vset(rx0, ry0); this._vset(p1.x + dlx1 * lw, p1.y + dly1 * lw); this._vset(rx1, ry1); } }, _vset: function(x, y) { var meshbuffer = _renderData.meshbuffer; var dataOffset = 3 * meshbuffer.vertexStart; var vData = meshbuffer._vData; var uintVData = meshbuffer._uintVData; vData[dataOffset] = x; vData[dataOffset + 1] = y; uintVData[dataOffset + 2] = _curColor; meshbuffer.vertexStart++; meshbuffer._dirty = true; } }; Graphics._assembler = graphicsAssembler; module.exports = graphicsAssembler; }), { "../../../../graphics/graphics": 107, "../../../../graphics/types": 110, "./earcut": 211, "./impl": 212 } ], 214: [ (function(require, module, exports) { require("./sprite"); require("./mask-assembler"); require("./graphics"); require("./label"); require("./motion-streak"); }), { "./graphics": 213, "./label": 216, "./mask-assembler": 219, "./motion-streak": 220, "./sprite": 222 } ], 215: [ (function(require, module, exports) { var js = require("../../../../platform/js"); var bmfontUtls = require("../../../utils/label/bmfont"); module.exports = js.addon({ createData: function(comp) { return comp.requestRenderData(); }, fillBuffers: function(comp, renderer) { var node = comp.node, renderData = comp._renderData, data = renderData._data, color = node.color._val; var matrix = node._worldMatrix, a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, tx = matrix.m12, ty = matrix.m13; var buffer = renderer._meshBuffer; var vertexCount = renderData.vertexCount; var offsetInfo = buffer.request(vertexCount, renderData.indiceCount); var indiceOffset = offsetInfo.indiceOffset, vertexOffset = offsetInfo.byteOffset >> 2, vertexId = offsetInfo.vertexOffset, vbuf = buffer._vData, uintbuf = buffer._uintVData, ibuf = buffer._iData; for (var i = 0; i < vertexCount; i++) { var vert = data[i]; vbuf[vertexOffset++] = vert.x * a + vert.y * c + tx; vbuf[vertexOffset++] = vert.x * b + vert.y * d + ty; vbuf[vertexOffset++] = vert.u; vbuf[vertexOffset++] = vert.v; uintbuf[vertexOffset++] = color; } for (var _i = 0, count = vertexCount / 4; _i < count; _i++) { var start = vertexId + 4 * _i; ibuf[indiceOffset++] = start; ibuf[indiceOffset++] = start + 1; ibuf[indiceOffset++] = start + 2; ibuf[indiceOffset++] = start + 1; ibuf[indiceOffset++] = start + 3; ibuf[indiceOffset++] = start + 2; } }, appendQuad: function(renderData, texture, rect, rotated, x, y, scale) { var dataOffset = renderData.dataLength; renderData.dataLength += 4; renderData.vertexCount = renderData.dataLength; renderData.indiceCount = renderData.dataLength / 2 * 3; var data = renderData._data; var texw = texture.width, texh = texture.height; var rectWidth = rect.width, rectHeight = rect.height; var l = void 0, b = void 0, r = void 0, t = void 0; if (rotated) { l = rect.x / texw; r = (rect.x + rectHeight) / texw; b = (rect.y + rectWidth) / texh; t = rect.y / texh; data[dataOffset].u = l; data[dataOffset].v = t; data[dataOffset + 1].u = l; data[dataOffset + 1].v = b; data[dataOffset + 2].u = r; data[dataOffset + 2].v = t; data[dataOffset + 3].u = r; data[dataOffset + 3].v = b; } else { l = rect.x / texw; r = (rect.x + rectWidth) / texw; b = (rect.y + rectHeight) / texh; t = rect.y / texh; data[dataOffset].u = l; data[dataOffset].v = b; data[dataOffset + 1].u = r; data[dataOffset + 1].v = b; data[dataOffset + 2].u = l; data[dataOffset + 2].v = t; data[dataOffset + 3].u = r; data[dataOffset + 3].v = t; } data[dataOffset].x = x; data[dataOffset].y = y - rectHeight * scale; data[dataOffset + 1].x = x + rectWidth * scale; data[dataOffset + 1].y = y - rectHeight * scale; data[dataOffset + 2].x = x; data[dataOffset + 2].y = y; data[dataOffset + 3].x = x + rectWidth * scale; data[dataOffset + 3].y = y; } }, bmfontUtls); }), { "../../../../platform/js": 181, "../../../utils/label/bmfont": 207 } ], 216: [ (function(require, module, exports) { var Label = require("../../../../components/CCLabel"); var ttfAssembler = require("./ttf"); var bmfontAssembler = require("./bmfont"); var letterAssembler = require("./letter-font"); var canvasPool = { pool: [], get: function() { var data = this.pool.pop(); if (!data) { var canvas = document.createElement("canvas"); var context = canvas.getContext("2d"); data = { canvas: canvas, context: context }; } return data; }, put: function(canvas) { if (this.pool.length >= 32) return; this.pool.push(canvas); } }; var labelAssembler = { getAssembler: function(comp) { var assembler = ttfAssembler; comp.font instanceof cc.BitmapFont ? assembler = bmfontAssembler : comp.cacheMode === Label.CacheMode.CHAR && (cc.sys.browserType === cc.sys.BROWSER_TYPE_WECHAT_GAME_SUB ? cc.warn("sorry, subdomain does not support CHAR mode currently!") : assembler = letterAssembler); return assembler; }, updateRenderData: function(label) { return label.__allocedDatas; } }; Label._assembler = labelAssembler; Label._canvasPool = canvasPool; module.exports = labelAssembler; }), { "../../../../components/CCLabel": 70, "./bmfont": 215, "./letter-font": 217, "./ttf": 218 } ], 217: [ (function(require, module, exports) { var js = require("../../../../platform/js"); var fontUtils = require("../../../utils/label/letter-font"); var WHITE = cc.color(255, 255, 255, 255); module.exports = js.addon({ createData: function(comp) { return comp.requestRenderData(); }, fillBuffers: function(comp, renderer) { var node = comp.node, renderData = comp._renderData, data = renderData._data; var matrix = node._worldMatrix, a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, tx = matrix.m12, ty = matrix.m13; WHITE._fastSetA(node.color.a); var color = WHITE._val; var buffer = renderer._meshBuffer; var vertexCount = renderData.vertexCount; var offsetInfo = buffer.request(vertexCount, renderData.indiceCount); var indiceOffset = offsetInfo.indiceOffset, vertexOffset = offsetInfo.byteOffset >> 2, vertexId = offsetInfo.vertexOffset, vbuf = buffer._vData, uintbuf = buffer._uintVData, ibuf = buffer._iData; for (var i = 0; i < vertexCount; i++) { var vert = data[i]; vbuf[vertexOffset++] = vert.x * a + vert.y * c + tx; vbuf[vertexOffset++] = vert.x * b + vert.y * d + ty; vbuf[vertexOffset++] = vert.u; vbuf[vertexOffset++] = vert.v; uintbuf[vertexOffset++] = color; } for (var _i = 0, count = vertexCount / 4; _i < count; _i++) { var start = vertexId + 4 * _i; ibuf[indiceOffset++] = start; ibuf[indiceOffset++] = start + 1; ibuf[indiceOffset++] = start + 2; ibuf[indiceOffset++] = start + 1; ibuf[indiceOffset++] = start + 3; ibuf[indiceOffset++] = start + 2; } }, appendQuad: function(renderData, texture, rect, rotated, x, y, scale) { var dataOffset = renderData.dataLength; renderData.dataLength += 4; renderData.vertexCount = renderData.dataLength; renderData.indiceCount = renderData.dataLength / 2 * 3; var data = renderData._data; var texw = texture.width, texh = texture.height; var rectWidth = rect.width, rectHeight = rect.height; var l = void 0, b = void 0, r = void 0, t = void 0; if (rotated) { l = rect.x / texw; r = (rect.x + rectHeight) / texw; b = (rect.y + rectWidth) / texh; t = rect.y / texh; data[dataOffset].u = l; data[dataOffset].v = t; data[dataOffset + 1].u = l; data[dataOffset + 1].v = b; data[dataOffset + 2].u = r; data[dataOffset + 2].v = t; data[dataOffset + 3].u = r; data[dataOffset + 3].v = b; } else { l = rect.x / texw; r = (rect.x + rectWidth) / texw; b = (rect.y + rectHeight) / texh; t = rect.y / texh; data[dataOffset].u = l; data[dataOffset].v = b; data[dataOffset + 1].u = r; data[dataOffset + 1].v = b; data[dataOffset + 2].u = l; data[dataOffset + 2].v = t; data[dataOffset + 3].u = r; data[dataOffset + 3].v = t; } data[dataOffset].x = x; data[dataOffset].y = y - rectHeight * scale; data[dataOffset + 1].x = x + rectWidth * scale; data[dataOffset + 1].y = y - rectHeight * scale; data[dataOffset + 2].x = x; data[dataOffset + 2].y = y; data[dataOffset + 3].x = x + rectWidth * scale; data[dataOffset + 3].y = y; } }, fontUtils); }), { "../../../../platform/js": 181, "../../../utils/label/letter-font": 209 } ], 218: [ (function(require, module, exports) { var js = require("../../../../platform/js"); var ttfUtls = require("../../../utils/label/ttf"); var WHITE = cc.color(255, 255, 255, 255); module.exports = js.addon({ createData: function(comp) { var renderData = comp.requestRenderData(); renderData.dataLength = 4; renderData.vertexCount = 4; renderData.indiceCount = 6; return renderData; }, fillBuffers: function(comp, renderer) { var data = comp._renderData._data, node = comp.node, matrix = node._worldMatrix, a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, tx = matrix.m12, ty = matrix.m13; WHITE._fastSetA(node.color.a); var color = WHITE._val; var buffer = renderer._meshBuffer; var offsetInfo = buffer.request(4, 6); var indiceOffset = offsetInfo.indiceOffset, vertexOffset = offsetInfo.byteOffset >> 2, vertexId = offsetInfo.vertexOffset, vbuf = buffer._vData, uintbuf = buffer._uintVData, ibuf = buffer._iData; for (var i = 0; i < 4; i++) { var vert = data[i]; vbuf[vertexOffset++] = vert.x * a + vert.y * c + tx; vbuf[vertexOffset++] = vert.x * b + vert.y * d + ty; vbuf[vertexOffset++] = vert.u; vbuf[vertexOffset++] = vert.v; uintbuf[vertexOffset++] = color; } ibuf[indiceOffset++] = vertexId; ibuf[indiceOffset++] = vertexId + 1; ibuf[indiceOffset++] = vertexId + 2; ibuf[indiceOffset++] = vertexId + 1; ibuf[indiceOffset++] = vertexId + 3; ibuf[indiceOffset++] = vertexId + 2; }, _updateVerts: function(comp) { var renderData = comp._renderData; var uv = comp._frame.uv; var node = comp.node, width = node.width, height = node.height, appx = node.anchorX * width, appy = node.anchorY * height; var data = renderData._data; data[0].x = -appx; data[0].y = -appy; data[1].x = width - appx; data[1].y = -appy; data[2].x = -appx; data[2].y = height - appy; data[3].x = width - appx; data[3].y = height - appy; data[0].u = uv[0]; data[0].v = uv[1]; data[1].u = uv[2]; data[1].v = uv[3]; data[2].u = uv[4]; data[2].v = uv[5]; data[3].u = uv[6]; data[3].v = uv[7]; } }, ttfUtls); }), { "../../../../platform/js": 181, "../../../utils/label/ttf": 210 } ], 219: [ (function(require, module, exports) { var StencilManager = require("../stencil-manager"); var Mask = require("../../../components/CCMask"); var RenderFlow = require("../../render-flow"); var spriteAssembler = require("./sprite/simple"); var graphicsAssembler = require("./graphics"); var _stencilMgr = StencilManager.sharedManager; var maskFrontAssembler = { updateRenderData: function(mask) { if (!mask._renderData) { graphicsAssembler.updateRenderData(mask._clearGraphics); mask._type === Mask.Type.IMAGE_STENCIL ? mask._renderData = spriteAssembler.createData(mask) : mask._renderData = mask.requestRenderData(); } var renderData = mask._renderData; if (mask._type === Mask.Type.IMAGE_STENCIL) if (mask.spriteFrame) { var size = mask.node._contentSize; var anchor = mask.node._anchorPoint; renderData.updateSizeNPivot(size.width, size.height, anchor.x, anchor.y); renderData.dataLength = 4; spriteAssembler.updateRenderData(mask); renderData.material = mask._material; } else mask._material = null; else { mask._graphics._material = mask._material; graphicsAssembler.updateRenderData(mask._graphics); } }, fillBuffers: function(mask, renderer) { if (mask._type !== Mask.Type.IMAGE_STENCIL || mask.spriteFrame) { _stencilMgr.pushMask(mask); _stencilMgr.clear(); graphicsAssembler.fillBuffers(mask._clearGraphics, renderer); _stencilMgr.enterLevel(); renderer.node = mask.node; renderer.material = mask._material; if (mask._type === Mask.Type.IMAGE_STENCIL) { spriteAssembler.fillBuffers(mask, renderer); renderer._flush(); } else graphicsAssembler.fillBuffers(mask._graphics, renderer); _stencilMgr.enableMask(); } mask.node._renderFlag |= RenderFlow.FLAG_UPDATE_RENDER_DATA; } }; var maskEndAssembler = { fillBuffers: function(mask, renderer) { (mask._type !== Mask.Type.IMAGE_STENCIL || mask.spriteFrame) && _stencilMgr.exitMask(); mask.node._renderFlag |= RenderFlow.FLAG_UPDATE_RENDER_DATA; } }; Mask._assembler = maskFrontAssembler; Mask._postAssembler = maskEndAssembler; module.exports = { front: maskFrontAssembler, end: maskEndAssembler }; }), { "../../../components/CCMask": 73, "../../render-flow": 204, "../stencil-manager": 232, "./graphics": 213, "./sprite/simple": 225 } ], 220: [ (function(require, module, exports) { 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 _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 = { updateRenderData: function(comp) { var dt = cc.director.getDeltaTime(); this.update(comp, dt); var renderData = comp._renderData; var size = comp.node._contentSize; var anchor = comp.node._anchorPoint; renderData.updateSizeNPivot(size.width, size.height, anchor.x, anchor.y); renderData.material = comp.getMaterial(); }, update: function(comp, dt) { var renderData = comp._renderData; renderData || (renderData = comp._renderData = comp.requestRenderData()); false; var stroke = comp._stroke / 2; var node = comp.node; var matrix = node._worldMatrix; var a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, tx = matrix.m12, ty = matrix.m13; var points = comp._points; var cur = void 0; if (points.length > 1) { var difx = points[0].point.x - tx; var dify = points[0].point.y - ty; difx * difx + dify * dify < comp.minSeg && (cur = points[0]); } if (!cur) { cur = new Point(); points.splice(0, 0, cur); } cur.setPoint(tx, ty); cur.time = comp._fadeTime + dt; renderData.dataLength = 0; if (points.length < 2) return; var data = renderData._data; var color = comp._color, cr = color.r, cg = color.g, cb = color.b, ca = color.a; var prev = points[1]; prev.distance = cur.point.sub(prev.point, _vec2).mag(); _vec2.normalizeSelf(); prev.setDir(_vec2.x, _vec2.y); cur.setDir(_vec2.x, _vec2.y); var fadeTime = comp._fadeTime; var findLast = false; for (var i = points.length - 1; i >= 0; i--) { var p = points[i]; var point = p.point; var dir = p.dir; p.time -= dt; if (p.time < 0) { points.splice(i, 1); continue; } var progress = p.time / fadeTime; var next = points[i - 1]; if (!findLast) { if (!next) { points.splice(i, 1); continue; } point.x = next.point.x - dir.x * progress; point.y = next.point.y - dir.y * progress; } findLast = true; normal(_normal, dir); renderData.dataLength += 2; var da = progress * ca; var _c = (da << 24 >>> 0) + (cb << 16) + (cg << 8) + cr; var dataIndex = data.length - 1; data[dataIndex].x = point.x - _normal.x * stroke; data[dataIndex].y = point.y - _normal.y * stroke; data[dataIndex].u = 0; data[dataIndex].v = progress; data[dataIndex].color = _c; dataIndex--; data[dataIndex].x = point.x + _normal.x * stroke; data[dataIndex].y = point.y + _normal.y * stroke; data[dataIndex].u = 1; data[dataIndex].v = progress; data[dataIndex].color = _c; } renderData.vertexCount = renderData.dataLength; renderData.indiceCount = renderData.vertexCount < 2 ? 0 : 3 * (renderData.vertexCount - 2); }, fillBuffers: function(comp, renderer) { var node = comp.node, renderData = comp._renderData, data = renderData._data; var buffer = renderer._meshBuffer, vertexCount = renderData.vertexCount; var offsetInfo = buffer.request(vertexCount, renderData.indiceCount); var indiceOffset = offsetInfo.indiceOffset, vertexOffset = offsetInfo.byteOffset >> 2, vertexId = offsetInfo.vertexOffset, vbuf = buffer._vData, uintbuf = buffer._uintVData, ibuf = buffer._iData; var vert = void 0; for (var i = 0, l = renderData.vertexCount; i < l; i++) { vert = data[i]; vbuf[vertexOffset++] = vert.x; vbuf[vertexOffset++] = vert.y; vbuf[vertexOffset++] = vert.u; vbuf[vertexOffset++] = vert.v; uintbuf[vertexOffset++] = vert.color; } for (var _i = 0, _l = renderData.vertexCount; _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; } }; module.exports = MotionStreak._assembler = motionStreakAssembler; }), { "../../../components/CCMotionStreak": 74, "../../render-flow": 204 } ], 221: [ (function(require, module, exports) { var Sprite = require("../../../../components/CCSprite"); var FillType = Sprite.FillType; module.exports = { useModel: false, updateRenderData: function(sprite) { var frame = sprite.spriteFrame; sprite._calDynamicAtlas(); var renderData = sprite._renderData; if (renderData && frame) { var uvDirty = renderData.uvDirty, vertDirty = renderData.vertDirty; if (!uvDirty && !vertDirty) return sprite.__allocedDatas; 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; uvDirty && this.updateUVs(sprite, fillStart, fillEnd); if (vertDirty) { this.updateVerts(sprite, fillStart, fillEnd); this.updateWorldVerts(sprite); } } }, updateUVs: function(sprite, fillStart, fillEnd) { var spriteFrame = sprite._spriteFrame, renderData = sprite._renderData, data = renderData._data; var atlasWidth = spriteFrame._texture.width; var atlasHeight = spriteFrame._texture.height; var textureRect = spriteFrame._rect; var ul = void 0, vb = void 0, ur = void 0, vt = void 0; var quadUV0 = void 0, quadUV1 = void 0, quadUV2 = void 0, quadUV3 = void 0, quadUV4 = void 0, quadUV5 = void 0, quadUV6 = void 0, quadUV7 = void 0; if (spriteFrame._rotated) { ul = textureRect.x / atlasWidth; vb = (textureRect.y + textureRect.width) / atlasHeight; ur = (textureRect.x + textureRect.height) / atlasWidth; vt = textureRect.y / atlasHeight; quadUV0 = quadUV2 = ul; quadUV4 = quadUV6 = ur; quadUV3 = quadUV7 = vb; quadUV1 = quadUV5 = vt; } else { ul = textureRect.x / atlasWidth; vb = (textureRect.y + textureRect.height) / atlasHeight; ur = (textureRect.x + textureRect.width) / atlasWidth; vt = textureRect.y / atlasHeight; quadUV0 = quadUV4 = ul; quadUV2 = quadUV6 = ur; quadUV1 = quadUV3 = vb; quadUV5 = quadUV7 = vt; } switch (sprite._fillType) { case FillType.HORIZONTAL: data[0].u = quadUV0 + (quadUV2 - quadUV0) * fillStart; data[0].v = quadUV1 + (quadUV3 - quadUV1) * fillStart; data[1].u = quadUV0 + (quadUV2 - quadUV0) * fillEnd; data[1].v = quadUV1 + (quadUV3 - quadUV1) * fillEnd; data[2].u = quadUV4 + (quadUV6 - quadUV4) * fillStart; data[2].v = quadUV5 + (quadUV7 - quadUV5) * fillStart; data[3].u = quadUV4 + (quadUV6 - quadUV4) * fillEnd; data[3].v = quadUV5 + (quadUV7 - quadUV5) * fillEnd; break; case FillType.VERTICAL: data[0].u = quadUV0 + (quadUV4 - quadUV0) * fillStart; data[0].v = quadUV1 + (quadUV5 - quadUV1) * fillStart; data[1].u = quadUV2 + (quadUV6 - quadUV2) * fillStart; data[1].v = quadUV3 + (quadUV7 - quadUV3) * fillStart; data[2].u = quadUV0 + (quadUV4 - quadUV0) * fillEnd; data[2].v = quadUV1 + (quadUV5 - quadUV1) * fillEnd; data[3].u = quadUV2 + (quadUV6 - quadUV2) * fillEnd; data[3].v = quadUV3 + (quadUV7 - quadUV3) * fillEnd; break; default: cc.errorID(2626); } renderData.uvDirty = false; }, updateVerts: function(sprite, fillStart, fillEnd) { var renderData = sprite._renderData, data = renderData._data, 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 = void 0, progressEnd = void 0; switch (sprite._fillType) { case FillType.HORIZONTAL: progressStart = l + (r - l) * fillStart; progressEnd = l + (r - l) * fillEnd; l = progressStart; r = progressEnd; break; case FillType.VERTICAL: progressStart = b + (t - b) * fillStart; progressEnd = b + (t - b) * fillEnd; b = progressStart; t = progressEnd; break; default: cc.errorID(2626); } data[4].x = l; data[4].y = b; data[5].x = r; data[5].y = b; data[6].x = l; data[6].y = t; data[7].x = r; data[7].y = t; renderData.vertDirty = false; }, createData: function(sprite) { var renderData = sprite.requestRenderData(); renderData.dataLength = 8; renderData.vertexCount = 4; renderData.indiceCount = 6; return renderData; }, updateWorldVerts: function(sprite) { var node = sprite.node, data = sprite._renderData._data; var matrix = node._worldMatrix, a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, tx = matrix.m12, ty = matrix.m13; for (var i = 0; i < 4; i++) { var local = data[i + 4]; var world = data[i]; world.x = local.x * a + local.y * c + tx; world.y = local.x * b + local.y * d + ty; } }, fillBuffers: function(sprite, renderer) { renderer.worldMatDirty && this.updateWorldVerts(sprite); var data = sprite._renderData._data, node = sprite.node, color = node._color._val, matrix = node._worldMatrix, a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, tx = matrix.m12, ty = matrix.m13; var buffer = renderer._meshBuffer; var offsetInfo = buffer.request(4, 6); var indiceOffset = offsetInfo.indiceOffset, vertexOffset = offsetInfo.byteOffset >> 2, vertexId = offsetInfo.vertexOffset, vbuf = buffer._vData, uintbuf = buffer._uintVData; for (var i = 0; i < 4; i++) { var vert = data[i]; vbuf[vertexOffset++] = vert.x; vbuf[vertexOffset++] = vert.y; vbuf[vertexOffset++] = vert.u; vbuf[vertexOffset++] = vert.v; uintbuf[vertexOffset++] = color; } var ibuf = buffer._iData; ibuf[indiceOffset++] = vertexId; ibuf[indiceOffset++] = vertexId + 1; ibuf[indiceOffset++] = vertexId + 2; ibuf[indiceOffset++] = vertexId + 1; ibuf[indiceOffset++] = vertexId + 3; ibuf[indiceOffset++] = vertexId + 2; } }; }), { "../../../../components/CCSprite": 83 } ], 222: [ (function(require, module, exports) { var Sprite = require("../../../../components/CCSprite"); var SpriteType = Sprite.Type; var FillType = Sprite.FillType; var simpleRenderUtil = require("./simple"); var slicedRenderUtil = require("./sliced"); var tiledRenderUtil = require("./tiled"); var radialFilledRenderUtil = require("./radial-filled"); var barFilledRenderUtil = require("./bar-filled"); var meshRenderUtil = require("./mesh"); var spriteAssembler = { getAssembler: function(sprite) { var util = simpleRenderUtil; switch (sprite.type) { case SpriteType.SLICED: util = slicedRenderUtil; break; case SpriteType.TILED: util = tiledRenderUtil; break; case SpriteType.FILLED: util = sprite._fillType === FillType.RADIAL ? radialFilledRenderUtil : barFilledRenderUtil; break; case SpriteType.MESH: util = meshRenderUtil; } return util; }, updateRenderData: function(sprite) { return sprite.__allocedDatas; } }; Sprite._assembler = spriteAssembler; module.exports = spriteAssembler; }), { "../../../../components/CCSprite": 83, "./bar-filled": 221, "./mesh": 223, "./radial-filled": 224, "./simple": 225, "./sliced": 226, "./tiled": 227 } ], 223: [ (function(require, module, exports) { module.exports = { useModel: false, createData: function(sprite) { return sprite.requestRenderData(); }, updateRenderData: function(sprite) { var frame = sprite.spriteFrame; sprite._calDynamicAtlas(); var renderData = sprite._renderData; if (renderData && frame) { var vertices = frame.vertices; if (vertices) { if (renderData.vertexCount !== vertices.x.length) { renderData.vertexCount = vertices.x.length; renderData.indiceCount = vertices.triangles.length; renderData.dataLength = 2 * renderData.vertexCount; renderData.uvDirty = renderData.vertDirty = true; } renderData.uvDirty && this.updateUVs(sprite); var vertDirty = renderData.vertDirty; if (vertDirty) { this.updateVerts(sprite); this.updateWorldVerts(sprite); } } } }, updateUVs: function(sprite) { var material = sprite.getMaterial(); var texture = material.effect.getProperty("texture"); var texw = texture._width, texh = texture._height; var vertices = sprite.spriteFrame.vertices, u = vertices.nu, v = vertices.nv; var renderData = sprite._renderData; var data = renderData._data; for (var i = 0, l = u.length; i < l; i++) { var vertice = data[i]; vertice.u = u[i]; vertice.v = v[i]; } renderData.uvDirty = false; }, updateVerts: function(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 renderData = sprite._renderData; var data = renderData._data; if (sprite.trim) for (var _i = 0, _l = x.length; _i < _l; _i++) { var _vertice = data[_i + _l]; _vertice.x = (x[_i] - trimX) * scaleX - appx; _vertice.y = (originalHeight - y[_i] - trimY) * scaleY - appy; } else for (var i = 0, l = x.length; i < l; i++) { var vertice = data[i + l]; vertice.x = x[i] * scaleX - appx; vertice.y = (originalHeight - y[i]) * scaleY - appy; } renderData.vertDirty = false; }, updateWorldVerts: function(sprite) { var node = sprite.node, renderData = sprite._renderData, data = renderData._data; var matrix = node._worldMatrix; var a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, tx = matrix.m12, ty = matrix.m13; for (var i = 0, l = renderData.vertexCount; i < l; i++) { var local = data[i + l]; var world = data[i]; world.x = local.x * a + local.y * c + tx; world.y = local.x * b + local.y * d + ty; } }, fillBuffers: function(sprite, renderer) { var node = sprite.node, color = node._color._val, renderData = sprite._renderData, data = renderData._data; var vertices = sprite.spriteFrame.vertices; if (!vertices) return; renderer.worldMatDirty && this.updateWorldVerts(sprite); var buffer = renderer._meshBuffer; var offsetInfo = buffer.request(renderData.vertexCount, renderData.indiceCount); var indiceOffset = offsetInfo.indiceOffset, vertexOffset = offsetInfo.byteOffset >> 2, vertexId = offsetInfo.vertexOffset, vbuf = buffer._vData, uintbuf = buffer._uintVData, ibuf = buffer._iData; for (var i = 0, l = renderData.vertexCount; i < l; i++) { var vertice = data[i]; vbuf[vertexOffset++] = vertice.x; vbuf[vertexOffset++] = vertice.y; vbuf[vertexOffset++] = vertice.u; vbuf[vertexOffset++] = vertice.v; uintbuf[vertexOffset++] = color; } var triangles = vertices.triangles; for (var _i2 = 0, _l2 = triangles.length; _i2 < _l2; _i2++) ibuf[indiceOffset++] = vertexId + triangles[_i2]; } }; }), {} ], 224: [ (function(require, module, exports) { var PI_2 = 2 * Math.PI; module.exports = { useModel: false, _vertPos: [ cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0) ], _vertices: [ 0, 0, 0, 0 ], _uvs: [ 0, 0, 0, 0, 0, 0, 0, 0 ], _intersectPoint_1: [ cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0) ], _intersectPoint_2: [ cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0) ], _center: cc.v2(0, 0), _triangles: [], createData: function(sprite) { return sprite.requestRenderData(); }, updateRenderData: function(sprite) { var frame = sprite.spriteFrame; sprite._calDynamicAtlas(); var renderData = sprite._renderData; if (renderData && frame && (renderData.vertDirty || renderData.uvDirty)) { var data = renderData._data; 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; var fillEnd = fillStart + fillRange; this._calculateVertices(sprite); this._calculateUVs(frame); var center = this._center; var vertPos = this._vertPos, vertices = this._vertices; var triangles = this._triangles; this._calcInsectedPoints(vertices[0], vertices[2], vertices[1], vertices[3], center, fillStart, this._intersectPoint_1); this._calcInsectedPoints(vertices[0], vertices[2], vertices[1], vertices[3], center, fillStart + fillRange, this._intersectPoint_2); var offset = 0; for (var triangleIndex = 0; triangleIndex < 4; ++triangleIndex) { var triangle = triangles[triangleIndex]; if (!triangle) continue; if (fillRange >= PI_2) { renderData.dataLength = offset + 3; this._generateTriangle(data, offset, center, vertPos[triangle[0]], vertPos[triangle[1]]); offset += 3; continue; } var startAngle = this._getVertAngle(center, vertPos[triangle[0]]); var endAngle = this._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) { renderData.dataLength = offset + 3; endAngle >= fillEnd ? this._generateTriangle(data, offset, center, vertPos[triangle[0]], this._intersectPoint_2[triangleIndex]) : this._generateTriangle(data, offset, center, vertPos[triangle[0]], vertPos[triangle[1]]); offset += 3; } else if (endAngle <= fillStart) ; else if (endAngle <= fillEnd) { renderData.dataLength = offset + 3; this._generateTriangle(data, offset, center, this._intersectPoint_1[triangleIndex], vertPos[triangle[1]]); offset += 3; } else { renderData.dataLength = offset + 3; this._generateTriangle(data, offset, center, this._intersectPoint_1[triangleIndex], this._intersectPoint_2[triangleIndex]); offset += 3; } startAngle += PI_2; endAngle += PI_2; } } renderData.indiceCount = renderData.vertexCount = offset; renderData.vertDirty = renderData.uvDirty = false; } }, _getVertAngle: function(start, end) { var placementX = void 0, placementY = void 0; 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; }, _generateTriangle: function(data, offset, vert0, vert1, vert2) { var vertices = this._vertices; var v0x = vertices[0]; var v0y = vertices[1]; var v1x = vertices[2]; var v1y = vertices[3]; data[offset].x = vert0.x; data[offset].y = vert0.y; data[offset + 1].x = vert1.x; data[offset + 1].y = vert1.y; data[offset + 2].x = vert2.x; data[offset + 2].y = vert2.y; var progressX = void 0, progressY = void 0; progressX = (vert0.x - v0x) / (v1x - v0x); progressY = (vert0.y - v0y) / (v1y - v0y); this._generateUV(progressX, progressY, data, offset); progressX = (vert1.x - v0x) / (v1x - v0x); progressY = (vert1.y - v0y) / (v1y - v0y); this._generateUV(progressX, progressY, data, offset + 1); progressX = (vert2.x - v0x) / (v1x - v0x); progressY = (vert2.y - v0y) / (v1y - v0y); this._generateUV(progressX, progressY, data, offset + 2); }, _generateUV: function(progressX, progressY, data, offset) { var uvs = this._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; var uv = data[offset]; uv.u = px1 + (px2 - px1) * progressY; uv.v = py1 + (py2 - py1) * progressY; }, _calcInsectedPoints: function(left, right, bottom, top, center, angle, intersectPoints) { var sinAngle = Math.sin(angle); var cosAngle = Math.cos(angle); var tanAngle = void 0, cotAngle = void 0; 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; } } }, _calculateVertices: function(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 = this._vertices; vertices[0] = l; vertices[1] = b; vertices[2] = r; vertices[3] = t; var center = this._center, fillCenter = sprite._fillCenter, cx = center.x = Math.min(Math.max(0, fillCenter.x), 1) * (r - l) + l, cy = center.y = Math.min(Math.max(0, fillCenter.y), 1) * (t - b) + b; var vertPos = this._vertPos; vertPos[0].x = vertPos[3].x = l; vertPos[1].x = vertPos[2].x = r; vertPos[0].y = vertPos[1].y = b; vertPos[2].y = vertPos[3].y = t; var triangles = this._triangles; 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 ]); }, _calculateUVs: function(spriteFrame) { var atlasWidth = spriteFrame._texture.width; var atlasHeight = spriteFrame._texture.height; var textureRect = spriteFrame._rect; var u0 = void 0, u1 = void 0, v0 = void 0, v1 = void 0; var uvs = this._uvs; if (spriteFrame._rotated) { u0 = textureRect.x / atlasWidth; u1 = (textureRect.x + textureRect.height) / atlasWidth; v0 = textureRect.y / atlasHeight; v1 = (textureRect.y + textureRect.width) / atlasHeight; uvs[0] = uvs[2] = u0; uvs[4] = uvs[6] = u1; uvs[3] = uvs[7] = v1; uvs[1] = uvs[5] = v0; } else { u0 = textureRect.x / atlasWidth; u1 = (textureRect.x + textureRect.width) / atlasWidth; v0 = textureRect.y / atlasHeight; v1 = (textureRect.y + textureRect.height) / atlasHeight; uvs[0] = uvs[4] = u0; uvs[2] = uvs[6] = u1; uvs[1] = uvs[3] = v1; uvs[5] = uvs[7] = v0; } }, fillBuffers: function(sprite, renderer) { var renderData = sprite._renderData, data = renderData._data, node = sprite.node, color = node._color._val; var matrix = node._worldMatrix, a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, tx = matrix.m12, ty = matrix.m13; var buffer = renderer._meshBuffer; var offsetInfo = buffer.request(renderData.vertexCount, renderData.indiceCount); var indiceOffset = offsetInfo.indiceOffset, vertexOffset = offsetInfo.byteOffset >> 2, vertexId = offsetInfo.vertexOffset, ibuf = buffer._iData, vbuf = buffer._vData, uintbuf = buffer._uintVData; var count = data.length; for (var i = 0; i < count; i++) { var vert = data[i]; vbuf[vertexOffset++] = vert.x * a + vert.y * c + tx; vbuf[vertexOffset++] = vert.x * b + vert.y * d + ty; vbuf[vertexOffset++] = vert.u; vbuf[vertexOffset++] = vert.v; uintbuf[vertexOffset++] = color; } for (var _i = 0; _i < count; _i++) ibuf[indiceOffset + _i] = vertexId + _i; } }; }), {} ], 225: [ (function(require, module, exports) { module.exports = { useModel: false, updateRenderData: function(sprite) { var frame = sprite._spriteFrame; sprite._calDynamicAtlas(); var renderData = sprite._renderData; renderData && frame && renderData.vertDirty && this.updateVerts(sprite); }, fillBuffers: function(sprite, renderer) { if (!sprite._spriteFrame.uv || !sprite._renderData._data) return; var data = sprite._renderData._data, node = sprite.node, color = node._color._val, matrix = node._worldMatrix, a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, tx = matrix.m12, ty = matrix.m13; var buffer = renderer._meshBuffer; var offsetInfo = buffer.request(4, 6); var indiceOffset = offsetInfo.indiceOffset, vertexOffset = offsetInfo.byteOffset >> 2, vertexId = offsetInfo.vertexOffset, vbuf = buffer._vData, uintbuf = buffer._uintVData, ibuf = buffer._iData; var uv = sprite._spriteFrame.uv; vbuf[vertexOffset + 2] = uv[0]; vbuf[vertexOffset + 3] = uv[1]; vbuf[vertexOffset + 7] = uv[2]; vbuf[vertexOffset + 8] = uv[3]; vbuf[vertexOffset + 12] = uv[4]; vbuf[vertexOffset + 13] = uv[5]; vbuf[vertexOffset + 17] = uv[6]; vbuf[vertexOffset + 18] = uv[7]; var data0 = data[0], data3 = data[3], vl = data0.x, vr = data3.x, vb = data0.y, vt = data3.y; 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; vbuf[vertexOffset] = al + cb + tx; vbuf[vertexOffset + 1] = bl + db + ty; vbuf[vertexOffset + 5] = ar + cb + tx; vbuf[vertexOffset + 6] = br + db + ty; vbuf[vertexOffset + 10] = al + ct + tx; vbuf[vertexOffset + 11] = bl + dt + ty; vbuf[vertexOffset + 15] = ar + ct + tx; vbuf[vertexOffset + 16] = br + dt + ty; uintbuf[vertexOffset + 4] = color; uintbuf[vertexOffset + 9] = color; uintbuf[vertexOffset + 14] = color; uintbuf[vertexOffset + 19] = color; ibuf[indiceOffset++] = vertexId; ibuf[indiceOffset++] = vertexId + 1; ibuf[indiceOffset++] = vertexId + 2; ibuf[indiceOffset++] = vertexId + 1; ibuf[indiceOffset++] = vertexId + 3; ibuf[indiceOffset++] = vertexId + 2; }, createData: function(sprite) { var renderData = sprite.requestRenderData(); renderData.dataLength = 4; renderData.vertexCount = 4; renderData.indiceCount = 6; return renderData; }, updateVerts: function(sprite) { var renderData = sprite._renderData, node = sprite.node, data = renderData._data, cw = node.width, ch = node.height, appx = node.anchorX * cw, appy = node.anchorY * ch, l = void 0, b = void 0, r = void 0, t = void 0; 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; } data[0].x = l; data[0].y = b; data[3].x = r; data[3].y = t; renderData.vertDirty = false; } }; }), {} ], 226: [ (function(require, module, exports) { module.exports = { useModel: false, createData: function(sprite) { var renderData = sprite.requestRenderData(); renderData.dataLength = 20; renderData.vertexCount = 16; renderData.indiceCount = 54; return renderData; }, updateRenderData: function(sprite, batchData) { var frame = sprite.spriteFrame; sprite._calDynamicAtlas(); var renderData = sprite._renderData; if (renderData && frame) { var vertDirty = renderData.vertDirty; if (vertDirty) { this.updateVerts(sprite); this.updateWorldVerts(sprite); } } }, updateVerts: function(sprite) { var renderData = sprite._renderData, data = renderData._data, 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; data[0].x = -appx; data[0].y = -appy; data[1].x = leftWidth * xScale - appx; data[1].y = bottomHeight * yScale - appy; data[2].x = data[1].x + sizableWidth; data[2].y = data[1].y + sizableHeight; data[3].x = width - appx; data[3].y = height - appy; renderData.vertDirty = false; }, fillBuffers: function(sprite, renderer) { renderer.worldMatDirty && this.updateWorldVerts(sprite); var renderData = sprite._renderData, node = sprite.node, color = node._color._val, data = renderData._data; var buffer = renderer._meshBuffer, vertexCount = renderData.vertexCount; var uvSliced = sprite.spriteFrame.uvSliced; var offsetInfo = buffer.request(vertexCount, renderData.indiceCount); var indiceOffset = offsetInfo.indiceOffset, vertexOffset = offsetInfo.byteOffset >> 2, vertexId = offsetInfo.vertexOffset, vbuf = buffer._vData, uintbuf = buffer._uintVData, ibuf = buffer._iData; for (var i = 4; i < 20; ++i) { var vert = data[i]; var uvs = uvSliced[i - 4]; vbuf[vertexOffset++] = vert.x; vbuf[vertexOffset++] = vert.y; vbuf[vertexOffset++] = uvs.u; vbuf[vertexOffset++] = uvs.v; uintbuf[vertexOffset++] = color; } for (var r = 0; r < 3; ++r) for (var c = 0; c < 3; ++c) { var start = vertexId + 4 * r + c; ibuf[indiceOffset++] = start; ibuf[indiceOffset++] = start + 1; ibuf[indiceOffset++] = start + 4; ibuf[indiceOffset++] = start + 1; ibuf[indiceOffset++] = start + 5; ibuf[indiceOffset++] = start + 4; } }, updateWorldVerts: function(sprite) { var node = sprite.node, data = sprite._renderData._data; var matrix = node._worldMatrix, a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, tx = matrix.m12, ty = matrix.m13; for (var row = 0; row < 4; ++row) { var rowD = data[row]; for (var col = 0; col < 4; ++col) { var colD = data[col]; var world = data[4 + 4 * row + col]; world.x = colD.x * a + rowD.y * c + tx; world.y = colD.x * b + rowD.y * d + ty; } } } }; }), {} ], 227: [ (function(require, module, exports) { module.exports = { useModel: false, createData: function(sprite) { return sprite.requestRenderData(); }, updateRenderData: function(sprite) { var frame = sprite.spriteFrame; sprite._calDynamicAtlas(); var renderData = sprite._renderData; if (!frame || !renderData || !(renderData.uvDirty || renderData.vertDirty)) return; var texture = frame._texture; var texw = texture.width, texh = texture.height, rect = frame._rect; var node = sprite.node, contentWidth = Math.abs(node.width), contentHeight = Math.abs(node.height), appx = node.anchorX * contentWidth, appy = node.anchorY * contentHeight; var rectWidth = rect.width, rectHeight = rect.height, hRepeat = contentWidth / rectWidth, vRepeat = contentHeight / rectHeight, row = Math.ceil(vRepeat), col = Math.ceil(hRepeat); var data = renderData._data; renderData.dataLength = Math.max(8, row + 1, col + 1); for (var i = 0; i <= col; ++i) data[i].x = Math.min(rectWidth * i, contentWidth) - appx; for (var _i = 0; _i <= row; ++_i) data[_i].y = Math.min(rectHeight * _i, contentHeight) - appy; renderData.vertexCount = row * col * 4; renderData.indiceCount = row * col * 6; renderData.uvDirty = false; renderData.vertDirty = false; }, fillBuffers: function(sprite, renderer) { var node = sprite.node, color = node._color._val, renderData = sprite._renderData, data = renderData._data; var buffer = renderer._meshBuffer; var offsetInfo = buffer.request(renderData.vertexCount, renderData.indiceCount); var indiceOffset = offsetInfo.indiceOffset, vertexOffset = offsetInfo.byteOffset >> 2, vertexId = offsetInfo.vertexOffset, vbuf = buffer._vData, uintbuf = buffer._uintVData, ibuf = buffer._iData; var rotated = sprite.spriteFrame._rotated; var uv = sprite.spriteFrame.uv; var rect = sprite.spriteFrame._rect; var contentWidth = Math.abs(node.width); var contentHeight = Math.abs(node.height); var hRepeat = contentWidth / rect.width; var vRepeat = contentHeight / rect.height; var row = Math.ceil(vRepeat), col = Math.ceil(hRepeat); var matrix = node._worldMatrix; var a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, tx = matrix.m12, ty = matrix.m13; var x = void 0, x1 = void 0, y = void 0, y1 = void 0, coefu = void 0, coefv = void 0; for (var yindex = 0, ylength = row; yindex < ylength; ++yindex) { y = data[yindex].y; y1 = data[yindex + 1].y; coefv = Math.min(1, vRepeat - yindex); for (var xindex = 0, xlength = col; xindex < xlength; ++xindex) { coefu = Math.min(1, hRepeat - xindex); x = data[xindex].x; x1 = data[xindex + 1].x; vbuf[vertexOffset] = x * a + y * c + tx; vbuf[vertexOffset + 1] = x * b + y * d + ty; vbuf[vertexOffset + 5] = x1 * a + y * c + tx; vbuf[vertexOffset + 6] = x1 * b + y * d + ty; vbuf[vertexOffset + 10] = x * a + y1 * c + tx; vbuf[vertexOffset + 11] = x * b + y1 * d + ty; vbuf[vertexOffset + 15] = x1 * a + y1 * c + tx; vbuf[vertexOffset + 16] = x1 * b + y1 * d + ty; if (rotated) { vbuf[vertexOffset + 2] = uv[0]; vbuf[vertexOffset + 3] = uv[1]; vbuf[vertexOffset + 7] = uv[0]; vbuf[vertexOffset + 8] = uv[1] + (uv[7] - uv[1]) * coefu; vbuf[vertexOffset + 12] = uv[0] + (uv[6] - uv[0]) * coefv; vbuf[vertexOffset + 13] = uv[1]; vbuf[vertexOffset + 17] = vbuf[vertexOffset + 12]; vbuf[vertexOffset + 18] = vbuf[vertexOffset + 8]; } else { vbuf[vertexOffset + 2] = uv[0]; vbuf[vertexOffset + 3] = uv[1]; vbuf[vertexOffset + 7] = uv[0] + (uv[6] - uv[0]) * coefu; vbuf[vertexOffset + 8] = uv[1]; vbuf[vertexOffset + 12] = uv[0]; vbuf[vertexOffset + 13] = uv[1] + (uv[7] - uv[1]) * coefv; vbuf[vertexOffset + 17] = vbuf[vertexOffset + 7]; vbuf[vertexOffset + 18] = vbuf[vertexOffset + 13]; } uintbuf[vertexOffset + 4] = color; uintbuf[vertexOffset + 9] = color; uintbuf[vertexOffset + 14] = color; uintbuf[vertexOffset + 19] = color; vertexOffset += 20; } } var length = renderData.indiceCount; for (var i = 0; i < length; i += 6) { ibuf[indiceOffset++] = vertexId; ibuf[indiceOffset++] = vertexId + 1; ibuf[indiceOffset++] = vertexId + 2; ibuf[indiceOffset++] = vertexId + 1; ibuf[indiceOffset++] = vertexId + 3; ibuf[indiceOffset++] = vertexId + 2; vertexId += 4; } } }; }), {} ], 228: [ (function(require, module, exports) { var renderEngine = require("../render-engine"); var gfx = renderEngine.gfx; var MeshBuffer = cc.Class({ name: "cc.MeshBuffer", ctor: function(batcher, vertexFormat) { this.byteStart = 0; this.byteOffset = 0; this.indiceStart = 0; this.indiceOffset = 0; this.vertexStart = 0; this.vertexOffset = 0; this._vertexFormat = vertexFormat; this._vertexBytes = this._vertexFormat._bytes; this._arrOffset = 0; this._vbArr = []; this._vb = new gfx.VertexBuffer(batcher._device, vertexFormat, gfx.USAGE_DYNAMIC, new ArrayBuffer(), 0); this._vbArr[0] = this._vb; this._ibArr = []; this._ib = new gfx.IndexBuffer(batcher._device, gfx.INDEX_FMT_UINT16, gfx.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() { 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; }, checkAndSwitchBuffer: function(vertexCount) { if (this.vertexOffset + vertexCount > 65535) { this.uploadData(); this._batcher._flush(); var offset = ++this._arrOffset; this.byteStart = 0; this.byteOffset = 0; this.vertexStart = 0; this.vertexOffset = 0; this.indiceStart = 0; this.indiceOffset = 0; if (offset < this._vbArr.length) { this._vb = this._vbArr[offset]; this._ib = this._ibArr[offset]; } else { this._vb = new gfx.VertexBuffer(this._batcher._device, this._vertexFormat, gfx.USAGE_DYNAMIC, new ArrayBuffer(), 0); this._vbArr[offset] = this._vb; this._vb._bytes = this._vData.byteLength; this._ib = new gfx.IndexBuffer(this._batcher._device, gfx.INDEX_FMT_UINT16, gfx.USAGE_STATIC, new ArrayBuffer(), 0); this._ibArr[offset] = this._ib; this._ib._bytes = this._iData.byteLength; } } }, requestStatic: function(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; this.vertexOffset += vertexCount; offsetInfo.indiceOffset = this.indiceOffset; this.indiceOffset += indiceCount; offsetInfo.byteOffset = this.byteOffset; this.byteOffset = byteOffset; this._dirty = true; }, request: function(vertexCount, indiceCount) { if (this._batcher._buffer !== this) { this._batcher._flush(); this._batcher._buffer = this; } this.requestStatic(vertexCount, indiceCount); return this._offsetInfo; }, _reallocBuffer: function() { this._reallocVData(true); this._reallocIData(true); }, _reallocVData: function(copyOldData) { var oldVData = void 0; 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]; this._vb._bytes = this._vData.byteLength; }, _reallocIData: function(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]; } this._ib._bytes = this._iData.byteLength; }, reset: function() { this._arrOffset = 0; this._vb = this._vbArr[0]; this._ib = this._ibArr[0]; this.byteStart = 0; this.byteOffset = 0; this.indiceStart = 0; this.indiceOffset = 0; this.vertexStart = 0; this.vertexOffset = 0; this._dirty = false; }, destroy: function() { for (var key in this._vbArr) { var vb = this._vbArr[key]; vb.destroy(); } this._vbArr = void 0; for (var _key in this._ibArr) { var ib = this._ibArr[_key]; ib.destroy(); } this._ibArr = void 0; this._ib = void 0; this._vb = void 0; } }); cc.MeshBuffer = module.exports = MeshBuffer; }), { "../render-engine": 203 } ], 229: [ (function(require, module, exports) { var renderEngine = require("../render-engine"); var defaultVertexFormat = require("./vertex-format").vfmtPosUvColor; var StencilManager = require("./stencil-manager"); var QuadBuffer = require("./quad-buffer"); var MeshBuffer = require("./mesh-buffer"); var SpineBuffer = require("./spine-buffer"); var idGenerater = new (require("../../platform/id-generater"))("VertextFormat"); var RecyclePool = renderEngine.RecyclePool; var InputAssembler = renderEngine.InputAssembler; var _buffers = {}; var empty_material = new renderEngine.Material(); empty_material.updateHash(); var ModelBatcher = function(device, renderScene) { this._renderScene = renderScene; this._device = device; this._stencilMgr = StencilManager.sharedManager; this.walking = false; this.material = empty_material; this.cullingMask = 1; this._iaPool = new RecyclePool(function() { return new InputAssembler(); }, 16); this._modelPool = new RecyclePool(function() { return new renderEngine.Model(); }, 16); this._quadBuffer = this.getBuffer("quad", defaultVertexFormat); this._meshBuffer = this.getBuffer("mesh", defaultVertexFormat); this._buffer = this._quadBuffer; 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() { this._iaPool.reset(); var scene = this._renderScene; var models = this._batchedModels; for (var i = 0; i < models.length; ++i) { models[i].clearInputAssemblers(); models[i].clearEffects(); scene.removeModel(models[i]); } this._modelPool.reset(); models.length = 0; this._sortKey = 0; for (var key in _buffers) _buffers[key].reset(); this._buffer = this._quadBuffer; this.node = this._dummyNode; this.material = empty_material; this.cullingMask = 1; this.parentOpacity = 1; this.parentOpacityDirty = 0; this.worldMatDirty = 0; this._stencilMgr.reset(); }, _flush: function() { var material = this.material, buffer = this._buffer, indiceStart = buffer.indiceStart, indiceOffset = buffer.indiceOffset, indiceCount = indiceOffset - indiceStart; if (!this.walking || !material || indiceCount <= 0) return; var effect = material.effect; var ia = this._iaPool.add(); ia._vertexBuffer = buffer._vb; ia._indexBuffer = buffer._ib; ia._start = indiceStart; ia._count = indiceCount; this._stencilMgr.handleEffect(effect); var model = this._modelPool.add(); this._batchedModels.push(model); model.sortKey = this._sortKey++; model._cullingMask = this.cullingMask; model.setNode(this.node); model.addEffect(effect); model.addInputAssembler(ia); this._renderScene.addModel(model); buffer.byteStart = buffer.byteOffset; buffer.indiceStart = buffer.indiceOffset; buffer.vertexStart = buffer.vertexOffset; }, _flushIA: function(iaRenderData) { var material = iaRenderData.material; if (!iaRenderData.ia || !material) return; this.material = material; var effect = this._stencilMgr.handleEffect(material.effect); var model = this._modelPool.add(); this._batchedModels.push(model); model.sortKey = this._sortKey++; model._cullingMask = this.cullingMask; model.setNode(this.node); model.addEffect(effect); model.addInputAssembler(iaRenderData.ia); this._renderScene.addModel(model); }, _commitComp: function(comp, assembler, cullingMask) { if (this.material._hash !== comp._material._hash || this.cullingMask !== cullingMask) { this._flush(); this.node = assembler.useModel ? comp.node : this._dummyNode; this.material = comp._material; this.cullingMask = cullingMask; } assembler.fillBuffers(comp, this); }, _commitIA: function(comp, assembler, cullingMask) { this._flush(); this.cullingMask = cullingMask; this.material = comp._material; this.node = assembler.useModel ? comp.node : this._dummyNode; assembler.renderIA(comp, this); }, terminate: function() { cc.dynamicAtlasManager && cc.dynamicAtlasManager.enabled && cc.dynamicAtlasManager.update(); this._flush(); for (var key in _buffers) _buffers[key].uploadData(); this.walking = false; }, getBuffer: function(type, vertextFormat) { vertextFormat.name || (vertextFormat.name = idGenerater.getNewId()); var key = type + vertextFormat.name; 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; }), { "../../platform/id-generater": 177, "../render-engine": 203, "./mesh-buffer": 228, "./quad-buffer": 230, "./spine-buffer": 231, "./stencil-manager": 232, "./vertex-format": 233 } ], 230: [ (function(require, module, exports) { var MeshBuffer = require("./mesh-buffer"); var QuadBuffer = cc.Class({ name: "cc.QuadBuffer", extends: MeshBuffer, _fillQuadBuffer: function() { 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() { 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; }, _reallocBuffer: function() { this._reallocVData(true); this._reallocIData(); this._fillQuadBuffer(); } }); cc.QuadBuffer = module.exports = QuadBuffer; }), { "./mesh-buffer": 228 } ], 231: [ (function(require, module, exports) { var SpineBuffer = cc.Class({ name: "cc.SpineBuffer", extends: require("./mesh-buffer"), requestStatic: function(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(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": 228 } ], 232: [ (function(require, module, exports) { var renderEngine = require("../render-engine"); var gfx = renderEngine.gfx; var Stage = cc.Enum({ DISABLED: 0, CLEAR: 1, ENTER_LEVEL: 2, ENABLED: 3, EXIT_LEVEL: 4 }); function StencilManager() { this._maxLevel = 8; this._maskStack = []; this.stage = Stage.DISABLED; } StencilManager.prototype = { constructor: StencilManager, reset: function() { this._maskStack.length = 0; this.stage = Stage.DISABLED; }, handleEffect: function(effect) { var technique = effect.getTechnique("transparent"); var passes = technique.passes; if (this.stage === Stage.DISABLED) { this.stage = Stage.DISABLED; for (var i = 0; i < passes.length; ++i) { var pass = passes[i]; pass._stencilTest && pass.disableStencilTest(); } return effect; } var mask = void 0, func = void 0, ref = void 0, stencilMask = void 0, writeMask = void 0, failOp = void 0, zFailOp = gfx.STENCIL_OP_KEEP, zPassOp = gfx.STENCIL_OP_KEEP; if (this.stage === Stage.ENABLED) { mask = this._maskStack[this._maskStack.length - 1]; func = gfx.DS_FUNC_EQUAL; failOp = gfx.STENCIL_OP_KEEP; ref = this.getStencilRef(); stencilMask = ref; writeMask = this.getWriteMask(); } else if (this.stage === Stage.CLEAR) { mask = this._maskStack[this._maskStack.length - 1]; func = gfx.DS_FUNC_NEVER; failOp = mask.inverted ? gfx.STENCIL_OP_REPLACE : gfx.STENCIL_OP_ZERO; ref = this.getWriteMask(); stencilMask = ref; writeMask = ref; } else if (this.stage === Stage.ENTER_LEVEL) { mask = this._maskStack[this._maskStack.length - 1]; func = gfx.DS_FUNC_NEVER; failOp = mask.inverted ? gfx.STENCIL_OP_ZERO : gfx.STENCIL_OP_REPLACE; ref = this.getWriteMask(); stencilMask = ref; writeMask = ref; } for (var _i = 0; _i < passes.length; ++_i) { var _pass = passes[_i]; _pass.setStencilFront(func, ref, stencilMask, failOp, zFailOp, zPassOp, writeMask); _pass.setStencilBack(func, ref, stencilMask, failOp, zFailOp, zPassOp, writeMask); } return effect; }, pushMask: function(mask) { this._maskStack.length + 1 > this._maxLevel && cc.errorID(9e3, this._maxLevel); this._maskStack.push(mask); }, clear: function() { this.stage = Stage.CLEAR; }, enterLevel: function() { this.stage = Stage.ENTER_LEVEL; }, enableMask: function() { this.stage = Stage.ENABLED; }, exitMask: function() { 0 === this._maskStack.length && cc.errorID(9001); this._maskStack.pop(); 0 === this._maskStack.length ? this.stage = Stage.DISABLED : this.stage = Stage.ENABLED; }, getWriteMask: function() { return 1 << this._maskStack.length - 1; }, getExitWriteMask: function() { return 1 << this._maskStack.length; }, getStencilRef: function() { var result = 0; for (var i = 0; i < this._maskStack.length; ++i) result += 1 << i; return result; }, getInvertedRef: function() { var result = 0; for (var i = 0; i < this._maskStack.length - 1; ++i) result += 1 << i; return result; } }; StencilManager.sharedManager = new StencilManager(); StencilManager.Stage = Stage; module.exports = cc.StencilManager = StencilManager; }), { "../render-engine": 203 } ], 233: [ (function(require, module, exports) { var renderEngine = require("../render-engine"); var gfx = renderEngine.gfx; var vfmt3D = new gfx.VertexFormat([ { name: gfx.ATTR_POSITION, type: gfx.ATTR_TYPE_FLOAT32, num: 3 }, { name: gfx.ATTR_UV0, type: gfx.ATTR_TYPE_FLOAT32, num: 2 }, { name: gfx.ATTR_COLOR, type: gfx.ATTR_TYPE_UINT8, num: 4, normalize: true } ]); vfmt3D.name = "vfmt3D"; gfx.VertexFormat.XYZ_UV_Color = vfmt3D; var vfmtPosUvColor = new gfx.VertexFormat([ { name: gfx.ATTR_POSITION, type: gfx.ATTR_TYPE_FLOAT32, num: 2 }, { name: gfx.ATTR_UV0, type: gfx.ATTR_TYPE_FLOAT32, num: 2 }, { name: gfx.ATTR_COLOR, type: gfx.ATTR_TYPE_UINT8, num: 4, normalize: true } ]); vfmtPosUvColor.name = "vfmtPosUvColor"; gfx.VertexFormat.XY_UV_Color = vfmtPosUvColor; var vfmtPosUvTwoColor = new gfx.VertexFormat([ { name: gfx.ATTR_POSITION, type: gfx.ATTR_TYPE_FLOAT32, num: 2 }, { name: gfx.ATTR_UV0, type: gfx.ATTR_TYPE_FLOAT32, num: 2 }, { name: gfx.ATTR_COLOR, type: gfx.ATTR_TYPE_UINT8, num: 4, normalize: true }, { name: gfx.ATTR_COLOR0, type: gfx.ATTR_TYPE_UINT8, num: 4, normalize: true } ]); vfmtPosUvTwoColor.name = "vfmtPosUvTwoColor"; gfx.VertexFormat.XY_UV_Two_Color = vfmtPosUvTwoColor; var vfmtPosUv = new gfx.VertexFormat([ { name: gfx.ATTR_POSITION, type: gfx.ATTR_TYPE_FLOAT32, num: 2 }, { name: gfx.ATTR_UV0, type: gfx.ATTR_TYPE_FLOAT32, num: 2 } ]); vfmtPosUv.name = "vfmtPosUv"; gfx.VertexFormat.XY_UV = vfmtPosUv; var vfmtPosColor = 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 } ]); vfmtPosColor.name = "vfmtPosColor"; gfx.VertexFormat.XY_Color = vfmtPosColor; module.exports = { vfmt3D: vfmt3D, vfmtPosUvColor: vfmtPosUvColor, vfmtPosUvTwoColor: vfmtPosUvTwoColor, vfmtPosUv: vfmtPosUv, vfmtPosColor: vfmtPosColor }; }), { "../render-engine": 203 } ], 234: [ (function(require, module, exports) { require("../platform/CCSys"); var EXTNAME_RE = /(\.[^\.\/\?\\]*)(\?.*)?$/; var DIRNAME_RE = /((.*)(\/|\\|\\\\))?(.*?\..*$)?/; var NORMALIZE_RE = /[^\.\/]+\/\.\.\//; cc.path = { join: function() { var l = arguments.length; var result = ""; for (var i = 0; i < l; i++) result = (result + ("" === result ? "" : "/") + arguments[i]).replace(/(\/|\\\\)$/, ""); return result; }, extname: function(pathStr) { var temp = EXTNAME_RE.exec(pathStr); return temp ? temp[1] : ""; }, mainFileName: function(fileName) { if (fileName) { var idx = fileName.lastIndexOf("."); if (-1 !== idx) return fileName.substring(0, idx); } return fileName; }, basename: function(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 null; 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(pathStr) { var temp = DIRNAME_RE.exec(pathStr); return temp ? temp[2] : ""; }, changeExtname: function(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(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(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(path) { return path.replace(/[\/\\]$/, ""); } }; module.exports = cc.path; }), { "../platform/CCSys": 170 } ], 235: [ (function(require, module, exports) { var AffineTransform = function(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) { out.a = mat.m00; out.b = mat.m01; out.c = mat.m04; out.d = mat.m05; out.tx = mat.m12; out.ty = mat.m13; 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; }), {} ], 236: [ (function(require, module, exports) { 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" === (__typeofVal = typeof typeOrClassName, "object" === __typeofVal ? __realTypeOfObj(typeOrClassName) : __typeofVal)) 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: [], _activeX: null, _active: true, _visible: true, _level: 0, _components: [], _prefab: null, _persistNode: { get: function() { return (this._objFlags & DontDestroy) > 0; }, set: function(value) { value ? this._objFlags |= DontDestroy : this._objFlags &= ~DontDestroy; } }, name: { get: function() { return this._name; }, set: function(value) { false; this._name = value; } }, uuid: { get: function() { return this._id; } }, children: { get: function() { return this._children; } }, childrenCount: { get: function() { return this._children.length; } }, active: { get: function() { return this._active; }, set: function(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); } } } }, visibleX: { get: function() { return this._visible; }, set: function(value) { value = !!value; if (this._visible !== value) { this._visible = value; if (value) if (this._active) { if (null !== this._activeX) { this.x = this._activeX; this._activeX = null; } } else this.active = true; else if (this._active) { this._activeX = this.x; this.x -= 3e3; } } } }, activeInHierarchy: { get: function() { return this._activeInHierarchy; } } }, ctor: function(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 = []; this._renderFlag = RenderFlow.FLAG_TRANSFORM; }, getParent: function() { return this._parent; }, setParent: function(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); this._level = value._level + 1; 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(attrs) { js.mixin(this, attrs); }, getChildByUuid: function(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(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(child) { false; cc.assertID(child, 1606); cc.assertID(null === child._parent, 1605); child.setParent(this); }, insertChild: function(child, siblingIndex) { child.parent = this; child.setSiblingIndex(siblingIndex); }, getSiblingIndex: function() { return this._parent ? this._parent._children.indexOf(this) : 0; }, setSiblingIndex: function(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(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; } 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() {}, removeFromParent: function(cleanup) { if (this._parent) { void 0 === cleanup && (cleanup = true); this._parent.removeChild(this, cleanup); } }, removeChild: function(child, cleanup) { if (this._children.indexOf(child) > -1) { (cleanup || void 0 === cleanup) && child.cleanup(); child.parent = null; } }, removeAllChildren: function(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(parent) { var child = this; do { if (child === parent) return true; child = child._parent; } while (child); return false; }, getComponent: function(typeOrClassName) { var constructor = getConstructor(typeOrClassName); if (constructor) return findComponent(this, constructor); return null; }, getComponents: function(typeOrClassName) { var constructor = getConstructor(typeOrClassName), components = []; constructor && findComponents(this, constructor, components); return components; }, getComponentInChildren: function(typeOrClassName) { var constructor = getConstructor(typeOrClassName); if (constructor) return findChildComponent(this._children, constructor); return null; }, getComponentsInChildren: function(typeOrClassName) { var constructor = getConstructor(typeOrClassName), components = []; if (constructor) { findComponents(this, constructor, components); findChildComponents(this._children, constructor, components); } return components; }, _checkMultipleComp: false, addComponent: function(typeOrClassName) { false; var constructor; if ("string" === (__typeofVal = typeof typeOrClassName, "object" === __typeofVal ? __realTypeOfObj(typeOrClassName) : __typeofVal)) { 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" !== (__typeofVal = typeof constructor, "object" === __typeofVal ? __realTypeOfObj(constructor) : __typeofVal)) { cc.errorID(3809); return null; } if (!js.isChildClassOf(constructor, cc.Component)) { cc.errorID(3810); return null; } false; 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(component) { if (!component) { cc.errorID(3813); return; } component instanceof cc.Component || (component = this.getComponent(component)); component && component.destroy(); }, _getDependComponent: false, _removeComponent: function(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() { cc.Object.prototype.destroy.call(this) && (this.active = false); }, destroyAllChildren: function() { var children = this._children; for (var i = 0; i < children.length; ++i) children[i].destroy(); }, _onSetParent: function(value) {}, _onPostActivated: function() {}, _onBatchRestored: function() {}, _onBatchCreated: function() {}, _onHierarchyChanged: function(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(cloned) { cloned || (cloned = cc.instantiate._clone(this, this)); var thisPrefabInfo = this._prefab; var PrefabUtils; false; var syncing = thisPrefabInfo && this === thisPrefabInfo.root && thisPrefabInfo.sync; syncing || false; cloned._parent = null; cloned._onBatchRestored(); 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() { 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": 101, "../platform/CCObject": 167, "../platform/id-generater": 177, "../platform/js": 181, "../renderer/render-flow": 204, "./misc": 243 } ], 237: [ (function(require, module, exports) { 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 }; }), {} ], 238: [ (function(require, module, exports) { 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": 243 } ], 239: [ (function(require, module, exports) { cc.find = module.exports = function(path, referenceNode) { if (null == path) { cc.errorID(5600); 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; }; }), {} ], 240: [ (function(require, module, exports) { var eventRegx = /^(click)(\s)*=|(param)(\s)*=/; var imageAttrReg = /(\s)*src(\s)*=|(\s)*height(\s)*=|(\s)*width(\s)*=|(\s)*click(\s)*=|(\s)*param(\s)*=|(\s)*emoji(\s)*=/; var HtmlTextParser = function() { this._parsedObject = {}; this._specialSymbolArray = []; 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(htmlString) { this._resultObjectArray = []; this._stack = []; var startIndex = 0; var length = htmlString.length; while (startIndex < length) { var tagBeginIndex = htmlString.indexOf("<", startIndex); if (tagBeginIndex < 0) { this._stack.pop(); this._processResult(htmlString.substring(startIndex)); startIndex = length; } else { this._processResult(htmlString.substring(startIndex, tagBeginIndex)); var tagEndIndex = htmlString.indexOf(">", startIndex); -1 === tagEndIndex ? tagEndIndex = tagBeginIndex : "/" === htmlString.charAt(tagBeginIndex + 1) ? this._stack.pop() : this._addToStack(htmlString.substring(tagBeginIndex + 1, tagEndIndex)); startIndex = tagEndIndex + 1; } } return this._resultObjectArray; }, _attributeToObject: function(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(); if ("src" === tagName) { obj.isImage = true; tagValue.endsWith("/") && (tagValue = tagValue.substring(0, tagValue.length - 1)); if (0 === tagValue.indexOf("'")) { isValidImageTag = true; tagValue = tagValue.substring(1, tagValue.length - 1); } else if (0 === tagValue.indexOf('"')) { isValidImageTag = true; tagValue = tagValue.substring(1, tagValue.length - 1); } obj.src = tagValue; } else if ("height" === tagName) obj.imageHeight = parseInt(tagValue); else if ("width" === tagName) obj.imageWidth = parseInt(tagValue); else if ("click" === tagName) obj.event = this._processEventHandler(tagName + "=" + tagValue); else if ("emoji" === tagName) { tagValue.endsWith("/") && (tagValue = tagValue.substring(0, tagValue.length - 1)); if (0 === tagValue.indexOf("'")) { isValidImageTag = true; tagValue = tagValue.substring(1, tagValue.length - 1); } else if (0 === tagValue.indexOf('"')) { isValidImageTag = true; tagValue = tagValue.substring(1, tagValue.length - 1); } obj.emoji = 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(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(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(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(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; }), {} ], 241: [ (function(require, module, exports) { require("./CCPath"); true; require("./profiler/CCProfiler"); require("./find"); require("./mutable-forward-iterator"); }), { "./CCPath": 234, "./find": 239, "./mutable-forward-iterator": 244, "./profiler/CCProfiler": 247 } ], 242: [ (function(require, module, exports) { var js = require("../platform/js"); var renderEngine = require("../renderer/render-engine"); var math = renderEngine.math; var mat4Pool = new js.Pool(128); mat4Pool.get = function() { var matrix = this._get(); matrix ? math.mat4.identity(matrix) : matrix = math.mat4.create(); return matrix; }; var quatPool = new js.Pool(64); quatPool.get = function() { var quat = this._get(); if (quat) { quat.x = quat.y = quat.z = 0; quat.w = 1; } else quat = math.quat.create(); return quat; }; module.exports = { mat4: mat4Pool, quat: quatPool }; }), { "../platform/js": 181, "../renderer/render-engine": 203 } ], 243: [ (function(require, module, exports) { 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": 181 } ], 244: [ (function(require, module, exports) { 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; }), {} ], 245: [ (function(require, module, exports) { var Node = require("../CCNode"); var EventType = Node.EventType; var DirtyFlag = Node._LocalDirtyFlag; var math = require("../renderer/render-engine").math; var RenderFlow = require("../renderer/render-flow"); var ONE_DEGREE = Math.PI / 180; var POSITION_ON = 1; var SCALE_ON = 2; var ROTATION_ON = 4; var _updateLocalMatrix2d = null; var _calculWorldMatrix2d = null; function _updateLocalMatrix3d() { if (this._localMatDirty) { var t = this._matrix; math.mat4.fromRTS(t, this._quat, this._position, this._scale); if (this._skewX || this._skewY) { var a = t.m00, b = t.m01, c = t.m04, d = t.m05; var skx = Math.tan(this._skewX * ONE_DEGREE); var sky = Math.tan(this._skewY * ONE_DEGREE); Infinity === skx && (skx = 99999999); Infinity === sky && (sky = 99999999); t.m00 = a + c * sky; t.m01 = b + d * sky; t.m04 = c + a * skx; t.m05 = d + b * skx; } this._localMatDirty = 0; this._worldMatDirty = true; } } function _calculWorldMatrix3d() { this._localMatDirty && this._updateLocalMatrix(); if (this._parent) { var parentMat = this._parent._worldMatrix; math.mat4.mul(this._worldMatrix, parentMat, this._matrix); } else math.mat4.copy(this._worldMatrix, this._matrix); this._worldMatDirty = false; } function getPosition() { return new cc.Vec3(this._position); } function setPosition(newPosOrX, y, z) { var x = void 0; if (void 0 === y) { x = newPosOrX.x; y = newPosOrX.y; z = newPosOrX.z || 0; } else { x = newPosOrX; z = z || 0; } var pos = this._position; if (pos.x === x && pos.y === y && pos.z === z) return; var oldPosition; false; pos.x = x; pos.y = y; pos.z = z; this.setLocalDirty(DirtyFlag.POSITION); this._renderFlag |= RenderFlow.FLAG_WORLD_TRANSFORM; this._eventMask & POSITION_ON && this.emit(EventType.POSITION_CHANGED); } function getQuat() { return math.quat.clone(this._quat); } function setQuat(quat, y, z, w) { var x = void 0; if (void 0 === y) { x = quat.x; y = quat.y; z = quat.z; w = quat.w; } var old = this._quat; if (old.x !== x || old.y !== y || old.z !== z || old.w !== w) { old.x = x; old.y = y; old.z = z; old.w = w; this.setLocalDirty(DirtyFlag.ROTATION); this._renderFlag |= RenderFlow.FLAG_TRANSFORM; this._eventMask & ROTATION_ON && this.emit(EventType.ROTATION_CHANGED); } } function getScale() { return cc.v3(this._scale); } function setScale(x, y, z) { if (x && "number" !== (__typeofVal = typeof x, "object" === __typeofVal ? __realTypeOfObj(x) : __typeofVal)) { y = x.y; z = x.z || 1; x = x.x; } else if (void 0 !== x && void 0 === y) { y = x; z = x; } else void 0 === z && (z = 1); if (this._scale.x !== x || this._scale.y !== y || this._scale.z !== z) { this._scale.x = x; this._scale.y = y; this._scale.z = z; this.setLocalDirty(DirtyFlag.SCALE); this._renderFlag |= RenderFlow.FLAG_TRANSFORM; this._eventMask & SCALE_ON && this.emit(EventType.SCALE_CHANGED); } } cc._polyfill3D = module.exports = { enabled: false, enable: function() { var proto = cc.Node.prototype; if (!_updateLocalMatrix2d) { _updateLocalMatrix2d = proto._updateLocalMatrix; _calculWorldMatrix2d = proto._calculWorldMatrix; } if (!this.enabled) { proto._updateLocalMatrix = _updateLocalMatrix3d; proto._calculWorldMatrix = _calculWorldMatrix3d; proto.getPosition = getPosition; proto.setPosition = setPosition; proto.getScale = getScale; proto.setScale = setScale; proto.getQuat = getQuat; proto.setQuat = setQuat; this.enabled = true; } }, disable: function() { if (this.enabled) { cc.Node.prototype._updateLocalMatrix = _updateLocalMatrix2d; cc.Node.prototype._calculWorldMatrix = _calculWorldMatrix2d; this.enabled = false; } } }; }), { "../CCNode": 30, "../renderer/render-engine": 203, "../renderer/render-flow": 204 } ], 246: [ (function(require, module, exports) { var math = require("../renderer").renderEngine.math; cc._PrefabInfo = cc.Class({ name: "cc.PrefabInfo", properties: { root: null, asset: null, fileId: "", sync: false, _synced: { default: false, serializable: false } } }); module.exports = { syncWithPrefab: function(node) { var _prefab = node._prefab; _prefab._synced = true; 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 x = node._position.x; var y = node._position.y; var _quat = node._quat; var _localZOrder = node._localZOrder; var _globalZOrder = node._globalZOrder; 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._position.x = x; node._position.y = y; math.quat.copy(node._quat, _quat); node._localZOrder = _localZOrder; node._globalZOrder = _globalZOrder; } }; }), { "../renderer": 202 } ], 247: [ (function(require, module, exports) { var macro = require("../../platform/CCMacro"); var PerfCounter = require("./perf-counter"); var _showFPS = false; var _fontSize = 15; var _atlas = null; var _stats = null; var _rootNode = null; var _label = null; function generateAtlas() { if (_atlas) return; var textureWidth = 256, textureHeight = 256; var canvas = document.createElement("canvas"); canvas.style.width = canvas.width = textureWidth; canvas.style.height = canvas.height = textureHeight; var ctx = canvas.getContext("2d"); ctx.font = _fontSize + "px Arial"; ctx.textBaseline = "top"; ctx.textAlign = "left"; ctx.fillStyle = "#fff"; var space = 2; var x = space; var y = space; var lineHeight = _fontSize; _atlas = new cc.LabelAtlas(); _atlas._fntConfig = { atlasName: "profiler-arial", commonHeight: lineHeight, fontSize: _fontSize, kerningDict: {}, fontDefDictionary: {} }; _atlas._name = "profiler-arial"; _atlas.fontSize = _fontSize; var dict = _atlas._fntConfig.fontDefDictionary; for (var i = 32; i <= 126; i++) { var char = String.fromCharCode(i); var width = ctx.measureText(char).width; if (x + width >= textureWidth) { x = space; y += lineHeight + space; } ctx.fillText(char, x, y); dict[i] = { xAdvance: width, xOffset: 0, yOffset: 0, rect: { x: x, y: y, width: width, height: lineHeight } }; x += width + space; } var texture = new cc.Texture2D(); texture.initWithElement(canvas); var spriteFrame = new cc.SpriteFrame(); spriteFrame.setTexture(texture); _atlas.spriteFrame = spriteFrame; } function generateStats() { if (_stats) return; _stats = { frame: { desc: "Frame time (ms)", min: 0, max: 50, average: 500 }, fps: { desc: "Framerate (FPS)", below: 30, average: 500 }, draws: { desc: "Draw call" }, 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; left.parent = _rootNode; var leftLabel = left.addComponent(cc.Label); leftLabel.font = _atlas; leftLabel.fontSize = _fontSize; leftLabel.lineHeight = _fontSize; var right = new cc.Node("RIGHT-PANEL"); right.anchorX = 1; right.anchorY = 0; right.x = 200; right.parent = _rootNode; var rightLabel = right.addComponent(cc.Label); rightLabel.horizontalAlign = cc.Label.HorizontalAlign.RIGHT; rightLabel.font = _atlas; rightLabel.fontSize = _fontSize; rightLabel.lineHeight = _fontSize; _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"; } _label.left.string = left; _label.right.string = right; } cc.profiler = module.exports = { isShowingStats: function() { return _showFPS; }, hideStats: function() { 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() { if (!_showFPS) { generateAtlas(); 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": 166, "./perf-counter": 249 } ], 248: [ (function(require, module, exports) { var Counter = cc.Class({ name: "cc.Counter", ctor: function(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() { return this._value; }, set: function(v) { this._value = v; } } }, _average: function(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(now) { this._average(this._value, now); }, human: function() { var v = this._opts.average ? this._averageValue : this._value; return Math.round(100 * v) / 100; }, alarm: function() { return this._opts.below && this._value < this._opts.below || this._opts.over && this._value > this._opts.over; } }); module.exports = Counter; }), {} ], 249: [ (function(require, module, exports) { var Counter = require("./counter"); var PerfCounter = cc.Class({ name: "cc.PerfCounter", extends: Counter, ctor: function(id, opts, now) { this._time = now; }, start: function(now) { this._time = now; }, end: function(now) { this._value = now - this._time; this._average(this._value); }, tick: function() { this.end(); this.start(); }, frame: function(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": 248 } ], 250: [ (function(require, module, exports) { var textUtils = { 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]/, label_firstEmoji: /^[\uD83C\uDF00-\uDFFF\uDC00-\uDE4F]/, label_lastEmoji: /([\uDF00-\uDFFF\uDC00-\uDE4F]+|\S)$/, 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(ch) { return this.__CHINESE_REG.test(ch) || this.__JAPANESE_REG.test(ch) || this.__KOREAN_REG.test(ch); }, isUnicodeSpace: function(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(ctx, string) { var metric = ctx.measureText(string); return metric && metric.width || 0; }, fragmentText: function(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 = text.substr(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 = text.substr(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 = text.substr(fuzzyLen); width = allWidth - measureText(tmpText); } fuzzyLen -= pushNum; if (0 === fuzzyLen) { fuzzyLen = 1; sLine = sLine.substr(1); } var sText = text.substr(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 = text.substr(fuzzyLen); sText = text.substr(0, fuzzyLen); } if (this.label_firstEmoji.test(sLine)) { result = this.label_lastEmoji.exec(sText); if (result && sText !== result[0]) { fuzzyLen -= result[0].length; sLine = text.substr(fuzzyLen); sText = text.substr(0, fuzzyLen); } } if (this.label_firstEnglish.test(sLine)) { result = this.label_lastEnglish.exec(sText); if (result && sText !== result[0]) { fuzzyLen -= result[0].length; sLine = text.substr(fuzzyLen); sText = text.substr(0, fuzzyLen); } } if (0 === wrappedWords.length) wrappedWords.push(sText); else { sText = sText.trim(); sText.length > 0 && wrappedWords.push(sText); } text = sLine || tmpText; allWidth = measureText(text); } if (0 === wrappedWords.length) wrappedWords.push(text); else { text = text.trim(); text.length > 0 && wrappedWords.push(text); } return wrappedWords; } }; module.exports = textUtils; }), {} ], 251: [ (function(require, module, exports) { var Texture2D = require("../assets/CCTexture2D"); var textureUtil = { loadImage: function(url, cb, target) { cc.assertID(url, 3103); var tex = cc.loader.getRes(url); if (tex) { if (tex.loaded) { cb && cb.call(target, tex); return tex; } tex.once("load", (function() { cb && cb.call(target, tex); }), target); return tex; } tex = new Texture2D(); tex.url = url; cc.loader.load({ url: url, texture: tex }, (function(err, texture) { if (err) return cb && cb.call(target, err || new Error("Unknown error")); texture.handleLoadedTexture(); cb && cb.call(target, null, texture); })); return tex; }, cacheImage: function(url, image) { if (url && image) { var tex = new Texture2D(); tex.initWithElement(image); var item = { id: url, url: url, error: null, content: tex, complete: false }; cc.loader.flowOut(item); return tex; } }, postLoadTexture: function(texture, callback) { if (texture.loaded) { callback && callback(); return; } if (!texture.url) { callback && callback(); return; } cc.loader.load({ url: texture.url, skips: [ "Loader" ] }, (function(err, image) { if (image) { if (true, image instanceof cc.Texture2D) return cc.error("internal error: loader handle pipe must be skipped"); texture.loaded || (texture._nativeAsset = image); } callback && callback(err); })); } }; cc.textureUtil = module.exports = textureUtil; }), { "../assets/CCTexture2D": 50 } ], 252: [ (function(require, module, exports) { var ValueType = require("./value-type"); var js = require("../platform/js"); var Color = (function() { function Color(r, g, b, a) { if ("object" === (__typeofVal = typeof r, "object" === __typeofVal ? __realTypeOfObj(r) : __typeofVal)) { g = r.g; b = r.b; a = r.a; r = r.r; } r = r || 0; g = g || 0; b = b || 0; a = "number" === (__typeofVal = typeof a, "object" === __typeofVal ? __realTypeOfObj(a) : __typeofVal) ? a : 255; this._val = (a << 24 >>> 0) + (b << 16) + (g << 8) + r; } js.extend(Color, ValueType); require("../platform/CCClass").fastDefine("cc.Color", Color, { r: 0, g: 0, b: 0, a: 255 }); var DefaultColors = { WHITE: [ 255, 255, 255, 255 ], BLACK: [ 0, 0, 0, 255 ], TRANSPARENT: [ 0, 0, 0, 0 ], GRAY: [ 127.5, 127.5, 127.5 ], RED: [ 255, 0, 0 ], GREEN: [ 0, 255, 0 ], BLUE: [ 0, 0, 255 ], YELLOW: [ 255, 235, 4 ], ORANGE: [ 255, 127, 0 ], CYAN: [ 0, 255, 255 ], MAGENTA: [ 255, 0, 255 ] }; for (var colorName in DefaultColors) js.get(Color, colorName, (function(rgba) { return function() { return new Color(rgba[0], rgba[1], rgba[2], rgba[3]); }; })(DefaultColors[colorName])); var proto = Color.prototype; proto.clone = function() { var ret = new Color(); ret._val = this._val; return ret; }; proto.equals = function(other) { return other && this._val === other._val; }; proto.lerp = function(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() { return "rgba(" + this.r.toFixed() + ", " + this.g.toFixed() + ", " + this.b.toFixed() + ", " + this.a.toFixed() + ")"; }; proto.getR = function() { return 255 & this._val; }; proto.setR = function(red) { red = ~~cc.misc.clampf(red, 0, 255); this._val = (4294967040 & this._val | red) >>> 0; return this; }; proto.getG = function() { return (65280 & this._val) >> 8; }; proto.setG = function(green) { green = ~~cc.misc.clampf(green, 0, 255); this._val = (4294902015 & this._val | green << 8) >>> 0; return this; }; proto.getB = function() { return (16711680 & this._val) >> 16; }; proto.setB = function(blue) { blue = ~~cc.misc.clampf(blue, 0, 255); this._val = (4278255615 & this._val | blue << 16) >>> 0; return this; }; proto.getA = function() { return (4278190080 & this._val) >>> 24; }; proto.setA = function(alpha) { alpha = ~~cc.misc.clampf(alpha, 0, 255); this._val = (16777215 & this._val | alpha << 24) >>> 0; return this; }; proto._fastSetA = function(alpha) { this._val = (16777215 & this._val | alpha << 24) >>> 0; }; js.getset(proto, "r", proto.getR, proto.setR, true); js.getset(proto, "g", proto.getG, proto.setG, true); js.getset(proto, "b", proto.getB, proto.setB, true); js.getset(proto, "a", proto.getA, proto.setA, true); proto.toCSS = function(opt) { return "rgba" === opt ? "rgba(" + (0 | this.r) + "," + (0 | this.g) + "," + (0 | this.b) + "," + (this.a / 255).toFixed(2) + ")" : "rgb" === opt ? "rgb(" + (0 | this.r) + "," + (0 | this.g) + "," + (0 | this.b) + ")" : "#" + this.toHEX(opt); }; proto.fromHEX = function(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(fmt) { var prefix = "0"; var hex = [ (this.r < 16 ? prefix : "") + (0 | this.r).toString(16), (this.g < 16 ? prefix : "") + (0 | this.g).toString(16), (this.b < 16 ? prefix : "") + (0 | this.b).toString(16) ]; var i = -1; if ("#rgb" === fmt) for (i = 0; i < hex.length; ++i) hex[i].length > 1 && (hex[i] = hex[i][0]); else if ("#rrggbb" === fmt) for (i = 0; i < hex.length; ++i) 1 === hex[i].length && (hex[i] = "0" + hex[i]); else "#rrggbbaa" === fmt && hex.push((this.a < 16 ? prefix : "") + (0 | this.a).toString(16)); return hex.join(""); }; proto.toRGBValue = function() { return 16777215 & this._val; }; proto.fromHSV = function(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; s = s; v = v; var i = Math.floor(h); var f = h - i; var p = v * (1 - s); var q = v * (1 - s * f); var t = v * (1 - s * (1 - f)); 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) + r; return this; }; proto.toHSV = function() { 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(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 Color; })(); cc.Color = Color; cc.color = function color(r, g, b, a) { if ("string" === (__typeofVal = typeof r, "object" === __typeofVal ? __realTypeOfObj(r) : __typeofVal)) { var result = new cc.Color(); return result.fromHEX(r); } if ("object" === (__typeofVal = typeof r, "object" === __typeofVal ? __realTypeOfObj(r) : __typeofVal)) return new cc.Color(r.r, r.g, r.b, r.a); return new cc.Color(r, g, b, a); }; module.exports = cc.Color; }), { "../platform/CCClass": 161, "../platform/js": 181, "./value-type": 258 } ], 253: [ (function(require, module, exports) { require("./value-type"); require("./vec2"); require("./vec3"); require("./quat"); require("./mat4"); require("./size"); require("./rect"); require("./color"); cc.vmath = require("../renderer/render-engine").math; }), { "../renderer/render-engine": 203, "./color": 252, "./mat4": 254, "./quat": 255, "./rect": 256, "./size": 257, "./value-type": 258, "./vec2": 259, "./vec3": 260 } ], 254: [ (function(require, module, exports) { var ValueType = require("./value-type"); var js = require("../platform/js"); var CCClass = require("../platform/CCClass"); var math = require("../renderer/render-engine").math; var mat4 = math.mat4; function Mat4(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) { var t = this; t.m00 = m00; t.m01 = m01; t.m02 = m02; t.m03 = m03; t.m04 = m10; t.m05 = m11; t.m06 = m12; t.m07 = m13; t.m08 = m20; t.m09 = m21; t.m10 = m22; t.m11 = m23; t.m12 = m30; t.m13 = m31; t.m14 = m32; t.m15 = m33; } js.extend(Mat4, ValueType); CCClass.fastDefine("cc.Mat4", Mat4, { m00: 1, m01: 0, m02: 0, m03: 0, m04: 0, m05: 1, m06: 0, m07: 0, m08: 0, m09: 0, m10: 1, m11: 0, m12: 0, m13: 0, m14: 0, m15: 1 }); js.mixin(Mat4.prototype, { clone: function() { var t = this; return new Mat4(t.m00, t.m01, t.m02, t.m03, t.m04, t.m05, t.m06, t.m07, t.m08, t.m09, t.m10, t.m11, t.m12, t.m13, t.m14, t.m15); }, set: function(s) { var t = this; t.m00 = s.m00; t.m01 = s.m01; t.m02 = s.m02; t.m03 = s.m03; t.m04 = s.m04; t.m05 = s.m05; t.m06 = s.m06; t.m07 = s.m07; t.m08 = s.m08; t.m09 = s.m09; t.m10 = s.m10; t.m11 = s.m11; t.m12 = s.m12; t.m13 = s.m13; t.m14 = s.m14; t.m15 = s.m15; return this; }, equals: function(other) { return mat4.exactEquals(this, other); }, fuzzyEquals: function(other) { return mat4.equals(this, other); }, toString: function() { var t = this; return "[\n" + t.m00 + ", " + t.m01 + ", " + t.m02 + ", " + t.m03 + ",\n" + t.m04 + ", " + t.m05 + ", " + t.m06 + ", " + t.m07 + ",\n" + t.m08 + ", " + t.m09 + ", " + t.m10 + ", " + t.m11 + ",\n" + t.m12 + ", " + t.m13 + ", " + t.m14 + ", " + t.m15 + "\n]"; }, identity: function() { return mat4.identity(this); }, transpose: function(out) { out = out || new cc.Mat4(); return mat4.transpose(out, this); }, invert: function(out) { out = out || new cc.Mat4(); return mat4.invert(out, this); }, adjoint: function(out) { out = out || new cc.Mat4(); return mat4.adjoint(out, this); }, determinant: function() { return mat4.determinant(this); }, add: function(other, out) { out = out || new cc.Mat4(); return mat4.add(out, this, other); }, sub: function(other, out) { out = out || new cc.Mat4(); return mat4.subtract(out, this, other); }, mul: function(other, out) { out = out || new cc.Mat4(); return mat4.multiply(out, this, other); }, mulScalar: function(number, out) { out = out || new cc.Mat4(); return mat4.mulScalar(out, this, number); }, translate: function(v, out) { out = out || new cc.Mat4(); return mat4.translate(out, this, v); }, scale: function(v, out) { out = out || new cc.Mat4(); return mat4.scale(out, this, v); }, rotate: function(rad, axis, out) { out = out || new cc.Mat4(); return mat4.rotate(out, this, rad, axis); }, getTranslation: function(out) { out = out || new cc.Vec3(); return mat4.getTranslation(out, this); }, getScale: function(out) { out = out || new cc.Vec3(); return mat4.getScaling(out, this); }, getRotation: function(out) { out = out || new cc.Quat(); return mat4.getRotation(out, this); }, fromRTS: function(q, v, s) { return mat4.fromRTS(this, q, v, s); }, fromQuat: function(quat) { return mat4.fromQuat(this, quat); } }); cc.mat4 = function mat4(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) { return new Mat4(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33); }; }), { "../platform/CCClass": 161, "../platform/js": 181, "../renderer/render-engine": 203, "./value-type": 258 } ], 255: [ (function(require, module, exports) { var ValueType = require("./value-type"); var js = require("../platform/js"); var CCClass = require("../platform/CCClass"); function Quat(x, y, z, w) { if (x && "object" === (__typeofVal = typeof x, "object" === __typeofVal ? __realTypeOfObj(x) : __typeofVal)) { z = x.z; y = x.y; x = x.x; w = x.w; } this.x = x || 0; this.y = y || 0; this.z = z || 0; this.w = w || 1; } js.extend(Quat, ValueType); CCClass.fastDefine("cc.Quat", Quat, { x: 0, y: 0, z: 0, w: 1 }); var proto = Quat.prototype; proto.clone = function() { return new Quat(this.x, this.y, this.z, this.w); }; proto.set = function(newValue) { this.x = newValue.x; this.y = newValue.y; this.z = newValue.z; this.w = newValue.w; return this; }; proto.equals = function(other) { return other && this.x === other.x && this.y === other.y && this.z === other.z && this.w === other.w; }; proto.getRoll = function() { var sinr = 2 * (this.w * this.x + this.y * this.z); var cosr = 1 - 2 * (this.x * this.x + this.y * this.y); return 180 * Math.atan2(sinr, cosr) / Math.PI; }; proto.getPitch = function() { var sinp = 2 * (this.w * this.y - this.z * this.x); var pitch = sinp > 1 ? 1 : sinp; pitch = sinp < -1 ? -1 : sinp; pitch = 180 * Math.asin(pitch) / Math.PI; return pitch; }; proto.getYaw = function() { var siny = 2 * (this.w * this.z + this.x * this.y); var cosy = 1 - 2 * (this.y * this.y + this.z * this.z); return 180 * Math.atan2(siny, cosy) / Math.PI; }; cc.quat = function quat(x, y, z, w) { return new Quat(x, y, z, w); }; module.exports = cc.Quat = Quat; }), { "../platform/CCClass": 161, "../platform/js": 181, "./value-type": 258 } ], 256: [ (function(require, module, exports) { var ValueType = require("./value-type"); var js = require("../platform/js"); function Rect(x, y, w, h) { if (x && "object" === (__typeofVal = typeof x, "object" === __typeofVal ? __realTypeOfObj(x) : __typeofVal)) { 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; } js.extend(Rect, ValueType); require("../platform/CCClass").fastDefine("cc.Rect", Rect, { x: 0, y: 0, width: 0, height: 0 }); Rect.fromMinMax = function(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); }; var proto = Rect.prototype; proto.clone = function() { return new Rect(this.x, this.y, this.width, this.height); }; proto.equals = function(other) { return other && this.x === other.x && this.y === other.y && this.width === other.width && this.height === other.height; }; proto.lerp = function(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(source) { this.x = source.x; this.y = source.y; this.width = source.width; this.height = source.height; }; proto.intersects = function(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(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(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(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(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(out, mat) { var ol = this.x; var ob = this.y; var or = ol + this.width; var ot = ob + this.height; var lbx = mat.m00 * ol + mat.m04 * ob + mat.m12; var lby = mat.m01 * ol + mat.m05 * ob + mat.m13; var rbx = mat.m00 * or + mat.m04 * ob + mat.m12; var rby = mat.m01 * or + mat.m05 * ob + mat.m13; var ltx = mat.m00 * ol + mat.m04 * ot + mat.m12; var lty = mat.m01 * ol + mat.m05 * ot + mat.m13; var rtx = mat.m00 * or + mat.m04 * ot + mat.m12; var rty = mat.m01 * or + mat.m05 * ot + mat.m13; 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() { return "(" + this.x.toFixed(2) + ", " + this.y.toFixed(2) + ", " + this.width.toFixed(2) + ", " + this.height.toFixed(2) + ")"; }; js.getset(proto, "xMin", (function() { return this.x; }), (function(value) { this.width += this.x - value; this.x = value; })); js.getset(proto, "yMin", (function() { return this.y; }), (function(value) { this.height += this.y - value; this.y = value; })); js.getset(proto, "xMax", (function() { return this.x + this.width; }), (function(value) { this.width = value - this.x; })); js.getset(proto, "yMax", (function() { return this.y + this.height; }), (function(value) { this.height = value - this.y; })); js.getset(proto, "center", (function() { return new cc.Vec2(this.x + .5 * this.width, this.y + .5 * this.height); }), (function(value) { this.x = value.x - .5 * this.width; this.y = value.y - .5 * this.height; })); js.getset(proto, "origin", (function() { return new cc.Vec2(this.x, this.y); }), (function(value) { this.x = value.x; this.y = value.y; })); js.getset(proto, "size", (function() { return new cc.Size(this.width, this.height); }), (function(value) { this.width = value.width; this.height = value.height; })); cc.Rect = Rect; cc.rect = function rect(x, y, w, h) { return new Rect(x, y, w, h); }; module.exports = cc.Rect; }), { "../platform/CCClass": 161, "../platform/js": 181, "./value-type": 258 } ], 257: [ (function(require, module, exports) { var ValueType = require("./value-type"); var js = require("../platform/js"); function Size(width, height) { if (width && "object" === (__typeofVal = typeof width, "object" === __typeofVal ? __realTypeOfObj(width) : __typeofVal)) { height = width.height; width = width.width; } this.width = width || 0; this.height = height || 0; } js.extend(Size, ValueType); require("../platform/CCClass").fastDefine("cc.Size", Size, { width: 0, height: 0 }); js.get(Size, "ZERO", (function() { return new Size(0, 0); })); var proto = Size.prototype; proto.clone = function() { return new Size(this.width, this.height); }; proto.equals = function(other) { return other && this.width === other.width && this.height === other.height; }; proto.lerp = function(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(source) { this.width = source.width; this.height = source.height; }; proto.toString = function() { return "(" + this.width.toFixed(2) + ", " + this.height.toFixed(2) + ")"; }; cc.size = function(w, h) { return new Size(w, h); }; cc.Size = module.exports = Size; }), { "../platform/CCClass": 161, "../platform/js": 181, "./value-type": 258 } ], 258: [ (function(require, module, exports) { var js = require("../platform/js"); function ValueType() {} js.setClassName("cc.ValueType", ValueType); var proto = ValueType.prototype; false; proto.toString = function() { return "" + {}; }; cc.ValueType = module.exports = ValueType; }), { "../platform/js": 181 } ], 259: [ (function(require, module, exports) { var ValueType = require("./value-type"); var js = require("../platform/js"); var CCClass = require("../platform/CCClass"); var math = require("../renderer/render-engine").math; var misc = require("../utils/misc"); function Vec2(x, y) { if (x && "object" === (__typeofVal = typeof x, "object" === __typeofVal ? __realTypeOfObj(x) : __typeofVal)) { y = x.y; x = x.x; } this.x = x || 0; this.y = y || 0; } js.extend(Vec2, ValueType); CCClass.fastDefine("cc.Vec2", Vec2, { x: 0, y: 0 }); var proto = Vec2.prototype; proto.clone = function() { return new Vec2(this.x, this.y); }; proto.set = function(newValue) { this.x = newValue.x; this.y = newValue.y; return this; }; proto.equals = function(other) { return other && this.x === other.x && this.y === other.y; }; proto.fuzzyEquals = function(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() { return "(" + this.x.toFixed(2) + ", " + this.y.toFixed(2) + ")"; }; proto.lerp = function(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(min_inclusive, max_inclusive) { this.x = misc.clampf(this.x, min_inclusive.x, max_inclusive.x); this.y = misc.clampf(this.y, min_inclusive.y, max_inclusive.y); return this; }; proto.addSelf = function(vector) { this.x += vector.x; this.y += vector.y; return this; }; proto.add = function(vector, out) { out = out || new Vec2(); out.x = this.x + vector.x; out.y = this.y + vector.y; return out; }; proto.subSelf = function(vector) { this.x -= vector.x; this.y -= vector.y; return this; }; proto.sub = function(vector, out) { out = out || new Vec2(); out.x = this.x - vector.x; out.y = this.y - vector.y; return out; }; proto.mulSelf = function(num) { this.x *= num; this.y *= num; return this; }; proto.mul = function(num, out) { out = out || new Vec2(); out.x = this.x * num; out.y = this.y * num; return out; }; proto.scaleSelf = function(vector) { this.x *= vector.x; this.y *= vector.y; return this; }; proto.scale = function(vector, out) { out = out || new Vec2(); out.x = this.x * vector.x; out.y = this.y * vector.y; return out; }; proto.divSelf = function(num) { this.x /= num; this.y /= num; return this; }; proto.div = function(num, out) { out = out || new Vec2(); out.x = this.x / num; out.y = this.y / num; return out; }; proto.negSelf = function() { this.x = -this.x; this.y = -this.y; return this; }; proto.neg = function(out) { out = out || new Vec2(); out.x = -this.x; out.y = -this.y; return out; }; proto.dot = function(vector) { return this.x * vector.x + this.y * vector.y; }; proto.cross = function(vector) { return this.x * vector.y - this.y * vector.x; }; proto.mag = function() { return Math.sqrt(this.x * this.x + this.y * this.y); }; proto.magSqr = function() { return this.x * this.x + this.y * this.y; }; proto.normalizeSelf = function() { 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(out) { out = out || new Vec2(); out.x = this.x; out.y = this.y; out.normalizeSelf(); return out; }; proto.angle = function(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.clampf(theta, -1, 1); return Math.acos(theta); }; proto.signAngle = function(vector) { var angle = this.angle(vector); return this.cross(vector) < 0 ? -angle : angle; }; proto.rotate = function(radians, out) { out = out || new Vec2(); out.x = this.x; out.y = this.y; return out.rotateSelf(radians); }; proto.rotateSelf = function(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(vector) { return vector.mul(this.dot(vector) / vector.dot(vector)); }; proto.transformMat4 = function(m, out) { out = out || new Vec2(); math.vec2.transformMat4(out, this, m); }; js.get(Vec2, "ONE", (function() { return new Vec2(1, 1); })); js.get(Vec2, "ZERO", (function() { return new Vec2(0, 0); })); js.get(Vec2, "UP", (function() { return new Vec2(0, 1); })); js.get(Vec2, "RIGHT", (function() { return new Vec2(1, 0); })); cc.Vec2 = Vec2; cc.v2 = function v2(x, y) { return new Vec2(x, y); }; cc.p = cc.v2; module.exports = cc.Vec2; }), { "../platform/CCClass": 161, "../platform/js": 181, "../renderer/render-engine": 203, "../utils/misc": 243, "./value-type": 258 } ], 260: [ (function(require, module, exports) { var ValueType = require("./value-type"); var js = require("../platform/js"); var CCClass = require("../platform/CCClass"); var math = require("../renderer/render-engine").math; var misc = require("../utils/misc"); function Vec3(x, y, z) { if (x && "object" === (__typeofVal = typeof x, "object" === __typeofVal ? __realTypeOfObj(x) : __typeofVal)) { z = x.z; y = x.y; x = x.x; } this.x = x || 0; this.y = y || 0; this.z = z || 0; } js.extend(Vec3, ValueType); CCClass.fastDefine("cc.Vec3", Vec3, { x: 0, y: 0, z: 0 }); var proto = Vec3.prototype; proto.clone = function() { return new Vec3(this.x, this.y, this.z); }; proto.set = function(newValue) { this.x = newValue.x; this.y = newValue.y; this.z = newValue.z; return this; }; proto.equals = function(other) { return other && this.x === other.x && this.y === other.y && this.z === other.z; }; proto.fuzzyEquals = function(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() { return "(" + this.x.toFixed(2) + ", " + this.y.toFixed(2) + ", " + this.z.toFixed(2) + ")"; }; proto.lerp = function(to, ratio, out) { out = out || new Vec3(); math.vec3.lerp(out, this, to, ratio); return out; }; proto.clampf = function(min_inclusive, max_inclusive) { this.x = misc.clampf(this.x, min_inclusive.x, max_inclusive.x); this.y = misc.clampf(this.y, min_inclusive.y, max_inclusive.y); this.z = misc.clampf(this.z, min_inclusive.z, max_inclusive.z); return this; }; proto.addSelf = function(vector) { this.x += vector.x; this.y += vector.y; this.z += vector.z; return this; }; proto.add = function(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.subSelf = function(vector) { this.x -= vector.x; this.y -= vector.y; this.z -= vector.z; return this; }; proto.sub = function(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.mulSelf = function(num) { this.x *= num; this.y *= num; this.z *= num; return this; }; proto.mul = function(num, out) { out = out || new Vec3(); out.x = this.x * num; out.y = this.y * num; out.z = this.z * num; return out; }; proto.scaleSelf = function(vector) { this.x *= vector.x; this.y *= vector.y; this.z *= vector.z; return this; }; proto.scale = function(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.divSelf = function(num) { this.x /= num; this.y /= num; this.z /= num; return this; }; proto.div = function(num, out) { out = out || new Vec3(); out.x = this.x / num; out.y = this.y / num; out.z = this.z / num; return out; }; proto.negSelf = function() { this.x = -this.x; this.y = -this.y; this.z = -this.z; return this; }; proto.neg = function(out) { out = out || new Vec3(); out.x = -this.x; out.y = -this.y; out.z = -this.z; return out; }; proto.dot = function(vector) { return this.x * vector.x + this.y * vector.y + this.z * vector.z; }; proto.cross = function(vector, out) { out = out || new Vec3(); math.vec3.cross(out, this, vector); return out; }; proto.mag = function() { return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); }; proto.magSqr = function() { return this.x * this.x + this.y * this.y + this.z * this.z; }; proto.normalizeSelf = function() { math.vec3.normalize(this, this); return this; }; proto.normalize = function(out) { out = out || new Vec3(); math.vec3.normalize(out, this); return out; }; proto.transformMat4 = function(m, out) { out = out || new Vec3(); math.vec3.transformMat4(out, this, m); }; cc.v3 = function v3(x, y, z) { return new Vec3(x, y, z); }; module.exports = cc.Vec3 = Vec3; }), { "../platform/CCClass": 161, "../platform/js": 181, "../renderer/render-engine": 203, "../utils/misc": 243, "./value-type": 258 } ], 261: [ (function(require, module, exports) { var js = cc.js; true; var ERR; (function() { 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)); } } 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); })); } function markAsRemovedInObject(ownerObj, removedProps, ownerName) { if (!ownerObj) return; removedProps.forEach((function(prop) { function error() { cc.errorID(1406, ownerName, prop); } js.getset(ownerObj, prop, error); })); } 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() { 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(); } } 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.warnID(1400, "cc.info", "cc.log"); return cc.log; })); js.get(cc, "spriteFrameCache", (function() { cc.errorID(1404); })); js.get(cc.SpriteFrame.prototype, "_textureLoaded", (function() { cc.errorID(1400, "spriteFrame._textureLoaded", "spriteFrame.textureLoaded()"); return this.textureLoaded(); })); markAsRemoved(cc.SpriteFrame, [ "addLoadedEventListener" ]); js.get(cc, "textureCache", (function() { cc.errorID(1406, "cc", "textureCache"); })); var Texture2D = cc.Texture2D; js.obsolete(Texture2D.prototype, "texture.releaseTexture", "texture.destroy"); js.get(Texture2D.prototype, "getName", (function() { cc.warnID(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.warnID(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.warnID(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" ], "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.loader.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" }, "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.Pipeline, [ "flowInDeps", "getItems" ], "cc.loader"); 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: "convertToNodeSpace", convertTouchToNodeSpaceAR: "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" }); markAsRemoved(cc.Component, [ "isRunning" ]); provideClearError(cc.Sprite.prototype, { setInsetLeft: "cc.SpriteFrame insetLeft", setInsetRight: "cc.SpriteFrame insetRight", setInsetTop: "cc.SpriteFrame insetTop", setInsetBottom: "cc.SpriteFrame insetBottom" }); markFunctionWarning(cc.Camera.prototype, { getNodeToCameraTransform: "getWorldToCameraMatrix" }); markAsRemoved(cc.Camera, [ "addTarget", "removeTarget", "getTargets" ]); ERR = '"%s" is not defined in the Scene, it is only defined in normal nodes.'; false, Object.defineProperties(cc.Scene.prototype, { active: { get: function() { cc.error(ERR, "active"); return true; }, set: function() { cc.error(ERR, "active"); } }, activeInHierarchy: { get: function() { cc.error(ERR, "activeInHierarchy"); return true; } }, getComponent: { get: function() { cc.error(ERR, "getComponent"); return function() { return null; }; } }, addComponent: { get: function() { cc.error(ERR, "addComponent"); return function() { return null; }; } } }); 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.dot(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", BlendFunc: "cc.macro.BlendFactor" }, "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)" }); js.get(cc, "lerp", (function() { cc.warnID(1400, "cc.lerp", "cc.misc.lerp"); return cc.misc.lerp; })); js.get(cc, "random0To1", (function() { cc.warnID(1400, "cc.random0To1", "Math.random"); return Math.random; })); js.get(cc, "degreesToRadians", (function() { cc.warnID(1400, "cc.degreesToRadians", "cc.misc.degreesToRadians"); return cc.misc.degreesToRadians; })); js.get(cc, "radiansToDegrees", (function() { cc.warnID(1400, "cc.radiansToDegrees", "cc.misc.radiansToDegrees"); return cc.misc.radiansToDegrees; })); js.get(cc, "clampf", (function() { cc.warnID(1400, "cc.clampf", "cc.misc.clampf"); return cc.misc.clampf; })); js.get(cc, "clamp01", (function() { cc.warnID(1400, "cc.clamp01", "cc.misc.clamp01"); return cc.misc.clamp01; })); js.get(cc, "ImageFormat", (function() { cc.warnID(1400, "cc.ImageFormat", "cc.macro.ImageFormat"); return cc.macro.ImageFormat; })); js.get(cc, "KEY", (function() { cc.warnID(1400, "cc.KEY", "cc.macro.KEY"); return cc.macro.KEY; })); js.get(cc, "Easing", (function() { cc.warnID(1400, "cc.Easing", "cc.easing"); return cc.easing; })); js.get(cc, "pool", (function() { cc.errorID(1407); return js.Pool; })); js.get(cc, "isChildClassOf", (function() { cc.errorID(1400, "cc.isChildClassOf", "cc.js.isChildClassOf"); return cc.js.isChildClassOf; })); "undefined" !== (__typeofVal = typeof dragonBones, "object" === __typeofVal ? __realTypeOfObj(dragonBones) : __typeofVal) && js.obsolete(dragonBones.CCFactory, "dragonBones.CCFactory.getFactory", "getInstance"); })(); }), {} ], 262: [ (function(require, module, exports) { require("./core/CCGame"); require("./actions"); }), { "./actions": 8, "./core/CCGame": 29 } ], 263: [ (function(require, module, exports) { var zlib = require("../compression/zlib.min"); var debug = require("../core/CCDebug"); var PNGReader = function(data) { var chunkSize, colors, delayDen, delayNum, frame, i, index, key, section, ccshort, text, _i, _j, _ref; this.data = data; this.pos = 8; this.palette = []; this.imgData = []; this.transparency = {}; this.animation = null; this.text = {}; frame = null; while (true) { chunkSize = this.readUInt32(); section = function() { var _i, _results; _results = []; for (i = _i = 0; _i < 4; i = ++_i) _results.push(String.fromCharCode(this.data[this.pos++])); return _results; }.call(this).join(""); switch (section) { case "IHDR": this.width = this.readUInt32(); this.height = this.readUInt32(); this.bits = this.data[this.pos++]; this.colorType = this.data[this.pos++]; this.compressionMethod = this.data[this.pos++]; this.filterMethod = this.data[this.pos++]; this.interlaceMethod = this.data[this.pos++]; break; case "acTL": this.animation = { numFrames: this.readUInt32(), numPlays: this.readUInt32() || Infinity, frames: [] }; break; case "PLTE": this.palette = this.read(chunkSize); break; case "fcTL": frame && this.animation.frames.push(frame); this.pos += 4; frame = { width: this.readUInt32(), height: this.readUInt32(), xOffset: this.readUInt32(), yOffset: this.readUInt32() }; delayNum = this.readUInt16(); delayDen = this.readUInt16() || 100; frame.delay = 1e3 * delayNum / delayDen; frame.disposeOp = this.data[this.pos++]; frame.blendOp = this.data[this.pos++]; frame.data = []; break; case "IDAT": case "fdAT": if ("fdAT" === section) { this.pos += 4; chunkSize -= 4; } data = (null != frame ? frame.data : void 0) || this.imgData; for (i = _i = 0; 0 <= chunkSize ? _i < chunkSize : _i > chunkSize; i = 0 <= chunkSize ? ++_i : --_i) data.push(this.data[this.pos++]); break; case "tRNS": this.transparency = {}; switch (this.colorType) { case 3: this.transparency.indexed = this.read(chunkSize); ccshort = 255 - this.transparency.indexed.length; if (ccshort > 0) for (i = _j = 0; 0 <= ccshort ? _j < ccshort : _j > ccshort; i = 0 <= ccshort ? ++_j : --_j) this.transparency.indexed.push(255); break; case 0: this.transparency.grayscale = this.read(chunkSize)[0]; break; case 2: this.transparency.rgb = this.read(chunkSize); } break; case "tEXt": text = this.read(chunkSize); index = text.indexOf(0); key = String.fromCharCode.apply(String, text.slice(0, index)); this.text[key] = String.fromCharCode.apply(String, text.slice(index + 1)); break; case "IEND": frame && this.animation.frames.push(frame); this.colors = function() { switch (this.colorType) { case 0: case 3: case 4: return 1; case 2: case 6: return 3; } }.call(this); this.hasAlphaChannel = 4 === (_ref = this.colorType) || 6 === _ref; colors = this.colors + (this.hasAlphaChannel ? 1 : 0); this.pixelBitlength = this.bits * colors; this.colorSpace = function() { switch (this.colors) { case 1: return "DeviceGray"; case 3: return "DeviceRGB"; } }.call(this); Uint8Array != Array && (this.imgData = new Uint8Array(this.imgData)); return; default: this.pos += chunkSize; } this.pos += 4; if (this.pos > this.data.length) throw new Error(debug.getError(6017)); } }; PNGReader.prototype = { constructor: PNGReader, read: function(bytes) { var i, _i, _results; _results = []; for (i = _i = 0; 0 <= bytes ? _i < bytes : _i > bytes; i = 0 <= bytes ? ++_i : --_i) _results.push(this.data[this.pos++]); return _results; }, readUInt32: function() { var b1, b2, b3, b4; b1 = this.data[this.pos++] << 24; b2 = this.data[this.pos++] << 16; b3 = this.data[this.pos++] << 8; b4 = this.data[this.pos++]; return b1 | b2 | b3 | b4; }, readUInt16: function() { var b1, b2; b1 = this.data[this.pos++] << 8; b2 = this.data[this.pos++]; return b1 | b2; }, decodePixels: function(data) { var ccbyte, c, col, i, left, length, p, pa, paeth, pb, pc, pixelBytes, pixels, pos, row, scanlineLength, upper, upperLeft, _i, _j, _k, _l, _m; null == data && (data = this.imgData); if (0 === data.length) return new Uint8Array(0); var inflate = new zlib.Inflate(data, { index: 0, verify: false }); data = inflate.decompress(); pixelBytes = this.pixelBitlength / 8; scanlineLength = pixelBytes * this.width; pixels = new Uint8Array(scanlineLength * this.height); length = data.length; row = 0; pos = 0; c = 0; while (pos < length) { switch (data[pos++]) { case 0: for (i = _i = 0; _i < scanlineLength; i = _i += 1) pixels[c++] = data[pos++]; break; case 1: for (i = _j = 0; _j < scanlineLength; i = _j += 1) { ccbyte = data[pos++]; left = i < pixelBytes ? 0 : pixels[c - pixelBytes]; pixels[c++] = (ccbyte + left) % 256; } break; case 2: for (i = _k = 0; _k < scanlineLength; i = _k += 1) { ccbyte = data[pos++]; col = (i - i % pixelBytes) / pixelBytes; upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + i % pixelBytes]; pixels[c++] = (upper + ccbyte) % 256; } break; case 3: for (i = _l = 0; _l < scanlineLength; i = _l += 1) { ccbyte = data[pos++]; col = (i - i % pixelBytes) / pixelBytes; left = i < pixelBytes ? 0 : pixels[c - pixelBytes]; upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + i % pixelBytes]; pixels[c++] = (ccbyte + Math.floor((left + upper) / 2)) % 256; } break; case 4: for (i = _m = 0; _m < scanlineLength; i = _m += 1) { ccbyte = data[pos++]; col = (i - i % pixelBytes) / pixelBytes; left = i < pixelBytes ? 0 : pixels[c - pixelBytes]; if (0 === row) upper = upperLeft = 0; else { upper = pixels[(row - 1) * scanlineLength + col * pixelBytes + i % pixelBytes]; upperLeft = col && pixels[(row - 1) * scanlineLength + (col - 1) * pixelBytes + i % pixelBytes]; } p = left + upper - upperLeft; pa = Math.abs(p - left); pb = Math.abs(p - upper); pc = Math.abs(p - upperLeft); paeth = pa <= pb && pa <= pc ? left : pb <= pc ? upper : upperLeft; pixels[c++] = (ccbyte + paeth) % 256; } break; default: throw new Error(debug.getError(6018, data[pos - 1])); } row++; } return pixels; }, copyToImageData: function(imageData, pixels) { var alpha, colors, data, i, input, j, k, length, palette, v, _ref; colors = this.colors; palette = null; alpha = this.hasAlphaChannel; if (this.palette.length) { palette = null != (_ref = this._decodedPalette) ? _ref : this._decodedPalette = this.decodePalette(); colors = 4; alpha = true; } data = imageData.data || imageData; length = data.length; input = palette || pixels; i = j = 0; if (1 === colors) while (i < length) { k = palette ? 4 * pixels[i / 4] : j; v = input[k++]; data[i++] = v; data[i++] = v; data[i++] = v; data[i++] = alpha ? input[k++] : 255; j = k; } else while (i < length) { k = palette ? 4 * pixels[i / 4] : j; data[i++] = input[k++]; data[i++] = input[k++]; data[i++] = input[k++]; data[i++] = alpha ? input[k++] : 255; j = k; } }, decodePalette: function() { var c, i, palette, pos, ret, transparency, _i, _ref, _ref1; palette = this.palette; transparency = this.transparency.indexed || []; ret = new Uint8Array((transparency.length || 0) + palette.length); pos = 0; c = 0; for (i = _i = 0, _ref = palette.length; _i < _ref; i = _i += 3) { ret[pos++] = palette[i]; ret[pos++] = palette[i + 1]; ret[pos++] = palette[i + 2]; ret[pos++] = null != (_ref1 = transparency[c++]) ? _ref1 : 255; } return ret; }, render: function(canvas) { var ctx, data; canvas.width = this.width; canvas.height = this.height; ctx = canvas.getContext("2d"); data = ctx.createImageData(this.width, this.height); this.copyToImageData(data, this.decodePixels()); return ctx.putImageData(data, 0, 0); } }; module.exports = PNGReader; }), { "../compression/zlib.min": 26, "../core/CCDebug": 27 } ], 264: [ (function(require, module, exports) { 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": 34, "../core/assets/CCSpriteFrame": 47 } ], 265: [ (function(require, module, exports) { var macro = require("../core/platform/CCMacro"); var ParticleAsset = require("./CCParticleAsset"); var RenderComponent = require("../core/components/CCRenderComponent"); var codec = require("../compression/ZipUtils"); var PNGReader = require("./CCPNGReader"); var tiffReader = require("./CCTIFFReader"); var textureUtil = require("../core/utils/texture-util"); var renderEngine = require("../core/renderer/render-engine"); var RenderFlow = require("../core/renderer/render-flow"); var ParticleSimulator = require("./particle-simulator"); var gfx = renderEngine.gfx; var BlendFactor = macro.BlendFactor; function getImageFormatByData(imgData) { if (imgData.length > 8 && 137 === imgData[0] && 80 === imgData[1] && 78 === imgData[2] && 71 === imgData[3] && 13 === imgData[4] && 10 === imgData[5] && 26 === imgData[6] && 10 === imgData[7]) return macro.ImageFormat.PNG; if (imgData.length > 2 && (73 === imgData[0] && 73 === imgData[1] || 77 === imgData[0] && 77 === imgData[1] || 255 === imgData[0] && 216 === imgData[1])) return macro.ImageFormat.TIFF; return macro.ImageFormat.UNKNOWN; } var EmitterMode = cc.Enum({ GRAVITY: 0, RADIUS: 1 }); var PositionType = cc.Enum({ FREE: 0, RELATIVE: 1, GROUPED: 2 }); var properties = { preview: { default: true, editorOnly: true, notify: false, animatable: false, tooltip: false }, _custom: false, custom: { get: function() { return this._custom; }, set: function(value) { false; if (this._custom !== value) { this._custom = value; this._applyFile(); false; } }, animatable: false, tooltip: false }, _file: { default: null, type: ParticleAsset }, file: { get: function() { return this._file; }, set: function(value, force) { if (this._file !== value || false) { this._file = value; if (value) { this._applyFile(); false; } else this.custom = true; } }, animatable: false, type: ParticleAsset, tooltip: false }, _spriteFrame: { default: null, type: cc.SpriteFrame }, spriteFrame: { get: function() { return this._spriteFrame; }, set: function(value, force) { var lastSprite = this._renderSpriteFrame; false; if (lastSprite === value) return; this._renderSpriteFrame = value; value && !value._uuid || (this._spriteFrame = value); if ((lastSprite && lastSprite.getTexture()) !== (value && value.getTexture())) { this._texture = null; this._applySpriteFrame(lastSprite); } false; }, type: cc.SpriteFrame, tooltip: false }, _texture: { default: null, type: cc.Texture2D, editorOnly: true }, texture: { get: function() { return this._texture; }, set: function(value) { value && cc.warnID(6017); }, type: cc.Texture2D, tooltip: false, readonly: true, visible: false, animatable: false }, _srcBlendFactor: BlendFactor.SRC_ALPHA, _dstBlendFactor: BlendFactor.ONE_MINUS_SRC_ALPHA, srcBlendFactor: { get: function() { return this._srcBlendFactor; }, set: function(value) { if (this._srcBlendFactor === value) return; this._srcBlendFactor = value; this._updateBlendFunc(true); }, animatable: false, type: BlendFactor, tooltip: false }, dstBlendFactor: { get: function() { return this._dstBlendFactor; }, set: function(value) { if (this._dstBlendFactor === value) return; this._dstBlendFactor = value; this._updateBlendFunc(true); }, animatable: false, type: BlendFactor, tooltip: false }, particleCount: { visible: false, get: function() { return this._simulator.particles.length; }, readonly: true }, _stopped: true, stopped: { get: function() { return this._stopped; }, animatable: false, visible: false }, playOnLoad: true, autoRemoveOnFinish: { default: false, animatable: false, tooltip: false }, active: { get: function() { return this._simulator.active; }, visible: false }, totalParticles: 150, duration: -1, emissionRate: 10, life: 1, lifeVar: 0, _startColor: null, startColor: { type: cc.Color, get: function() { return this._startColor; }, set: function(val) { this._startColor.r = val.r; this._startColor.g = val.g; this._startColor.b = val.b; this._startColor.a = val.a; } }, _startColorVar: null, startColorVar: { type: cc.Color, get: function() { return this._startColorVar; }, set: function(val) { this._startColorVar.r = val.r; this._startColorVar.g = val.g; this._startColorVar.b = val.b; this._startColorVar.a = val.a; } }, _endColor: null, endColor: { type: cc.Color, get: function() { return this._endColor; }, set: function(val) { this._endColor.r = val.r; this._endColor.g = val.g; this._endColor.b = val.b; this._endColor.a = val.a; } }, _endColorVar: null, endColorVar: { type: cc.Color, get: function() { return this._endColorVar; }, set: function(val) { this._endColorVar.r = val.r; this._endColorVar.g = val.g; this._endColorVar.b = val.b; this._endColorVar.a = val.a; } }, angle: 90, angleVar: 20, startSize: 50, startSizeVar: 0, endSize: 0, endSizeVar: 0, startSpin: 0, startSpinVar: 0, endSpin: 0, endSpinVar: 0, sourcePos: cc.Vec2.ZERO, posVar: cc.Vec2.ZERO, positionType: { default: PositionType.FREE, type: PositionType }, emitterMode: { default: EmitterMode.GRAVITY, type: EmitterMode }, gravity: cc.Vec2.ZERO, speed: 180, speedVar: 50, tangentialAccel: 80, tangentialAccelVar: 0, radialAccel: 0, radialAccelVar: 0, rotationIsDir: false, startRadius: 0, startRadiusVar: 0, endRadius: 0, endRadiusVar: 0, rotatePerS: 0, rotatePerSVar: 0 }; var ParticleSystem = cc.Class({ name: "cc.ParticleSystem", extends: RenderComponent, editor: false, ctor: function() { this._previewTimer = null; this._focused = false; this._simulator = new ParticleSimulator(this); this._startColor = cc.color(255, 255, 255, 255); this._startColorVar = cc.color(0, 0, 0, 0); this._endColor = cc.color(255, 255, 255, 0); this._endColorVar = cc.color(0, 0, 0, 0); this._renderSpriteFrame = null; }, properties: properties, statics: { DURATION_INFINITY: -1, START_SIZE_EQUAL_TO_END_SIZE: -1, START_RADIUS_EQUAL_TO_END_RADIUS: -1, EmitterMode: EmitterMode, PositionType: PositionType, _PNGReader: PNGReader, _TIFFReader: tiffReader }, onFocusInEditor: false, onLostFocusInEditor: false, _convertTextureToSpriteFrame: false, __preload: function() { false; if (this._file) if (this._custom) { var missCustomTexture = !this._texture; missCustomTexture && this._applyFile(); } else this._applyFile(); else this._custom && this.spriteFrame && !this._renderSpriteFrame && this._applySpriteFrame(this.spriteFrame); true; this.playOnLoad && this.resetSystem(); false; }, onLoad: function() { this._ia || ParticleSystem._assembler.createIA(this); }, onEnable: function() { this._super(); this.node._renderFlag &= ~RenderFlow.FLAG_RENDER; this._activateMaterial(); }, onDestroy: function() { this.autoRemoveOnFinish && (this.autoRemoveOnFinish = false); this._super(); }, lateUpdate: function(dt) { !this._simulator.finished && this._material && this._simulator.step(dt); }, addParticle: function() {}, stopSystem: function() { this._stopped = true; this._simulator.stop(); }, resetSystem: function() { this._stopped = false; this._simulator.reset(); this._activateMaterial(); }, isFull: function() { return this.particleCount >= this.totalParticles; }, setTextureWithRect: function(texture, rect) { texture instanceof cc.Texture2D && (this.spriteFrame = new cc.SpriteFrame(texture, rect)); }, _applyFile: function() { var file = this._file; if (file) { var self = this; cc.loader.load(file.nativeUrl, (function(err, content) { if (err || !content) { cc.errorID(6029); return; } if (!self.isValid) return; self._plistFile = file.nativeUrl; self._custom || self._initWithDictionary(content); self._spriteFrame ? !self._renderSpriteFrame && self._spriteFrame && self._applySpriteFrame(self.spriteFrame) : file.spriteFrame ? self.spriteFrame = file.spriteFrame : self._custom && self._initTextureWithDictionary(content); })); } }, _initTextureWithDictionary: function(dict) { var imgPath = cc.path.changeBasename(this._plistFile, dict["textureFileName"] || ""); if (dict["textureFileName"]) textureUtil.loadImage(imgPath, (function(error, texture) { if (error) { dict["textureFileName"] = void 0; this._initTextureWithDictionary(dict); } else this.spriteFrame = new cc.SpriteFrame(texture); }), this); else if (dict["textureImageData"]) { var textureData = dict["textureImageData"]; if (!(textureData && textureData.length > 0)) return false; var tex = cc.loader.getRes(imgPath); if (!tex) { var buffer = codec.unzipBase64AsArray(textureData, 1); if (!buffer) { cc.logID(6030); return false; } var imageFormat = getImageFormatByData(buffer); if (imageFormat !== macro.ImageFormat.TIFF && imageFormat !== macro.ImageFormat.PNG) { cc.logID(6031); return false; } var canvasObj = document.createElement("canvas"); if (imageFormat === macro.ImageFormat.PNG) { var myPngObj = new PNGReader(buffer); myPngObj.render(canvasObj); } else tiffReader.parseTIFF(buffer, canvasObj); tex = textureUtil.cacheImage(imgPath, canvasObj); } tex || cc.logID(6032); this.spriteFrame = new cc.SpriteFrame(tex); } return true; }, _initWithDictionary: function(dict) { this.totalParticles = parseInt(dict["maxParticles"] || 0); this.life = parseFloat(dict["particleLifespan"] || 0); this.lifeVar = parseFloat(dict["particleLifespanVariance"] || 0); var _tempEmissionRate = dict["emissionRate"]; this.emissionRate = _tempEmissionRate || Math.min(this.totalParticles / this.life, Number.MAX_VALUE); this.duration = parseFloat(dict["duration"] || 0); this.srcBlendFactor = parseInt(dict["blendFuncSource"] || macro.SRC_ALPHA); this.dstBlendFactor = parseInt(dict["blendFuncDestination"] || macro.ONE_MINUS_SRC_ALPHA); var locStartColor = this._startColor; locStartColor.r = 255 * parseFloat(dict["startColorRed"] || 0); locStartColor.g = 255 * parseFloat(dict["startColorGreen"] || 0); locStartColor.b = 255 * parseFloat(dict["startColorBlue"] || 0); locStartColor.a = 255 * parseFloat(dict["startColorAlpha"] || 0); var locStartColorVar = this._startColorVar; locStartColorVar.r = 255 * parseFloat(dict["startColorVarianceRed"] || 0); locStartColorVar.g = 255 * parseFloat(dict["startColorVarianceGreen"] || 0); locStartColorVar.b = 255 * parseFloat(dict["startColorVarianceBlue"] || 0); locStartColorVar.a = 255 * parseFloat(dict["startColorVarianceAlpha"] || 0); var locEndColor = this._endColor; locEndColor.r = 255 * parseFloat(dict["finishColorRed"] || 0); locEndColor.g = 255 * parseFloat(dict["finishColorGreen"] || 0); locEndColor.b = 255 * parseFloat(dict["finishColorBlue"] || 0); locEndColor.a = 255 * parseFloat(dict["finishColorAlpha"] || 0); var locEndColorVar = this._endColorVar; locEndColorVar.r = 255 * parseFloat(dict["finishColorVarianceRed"] || 0); locEndColorVar.g = 255 * parseFloat(dict["finishColorVarianceGreen"] || 0); locEndColorVar.b = 255 * parseFloat(dict["finishColorVarianceBlue"] || 0); locEndColorVar.a = 255 * parseFloat(dict["finishColorVarianceAlpha"] || 0); this.startSize = parseFloat(dict["startParticleSize"] || 0); this.startSizeVar = parseFloat(dict["startParticleSizeVariance"] || 0); this.endSize = parseFloat(dict["finishParticleSize"] || 0); this.endSizeVar = parseFloat(dict["finishParticleSizeVariance"] || 0); this.sourcePos.x = 0; this.sourcePos.y = 0; this.posVar.x = parseFloat(dict["sourcePositionVariancex"] || 0); this.posVar.y = parseFloat(dict["sourcePositionVariancey"] || 0); this.angle = parseFloat(dict["angle"] || 0); this.angleVar = parseFloat(dict["angleVariance"] || 0); this.startSpin = parseFloat(dict["rotationStart"] || 0); this.startSpinVar = parseFloat(dict["rotationStartVariance"] || 0); this.endSpin = parseFloat(dict["rotationEnd"] || 0); this.endSpinVar = parseFloat(dict["rotationEndVariance"] || 0); this.emitterMode = parseInt(dict["emitterType"] || EmitterMode.GRAVITY); if (this.emitterMode === EmitterMode.GRAVITY) { this.gravity.x = parseFloat(dict["gravityx"] || 0); this.gravity.y = parseFloat(dict["gravityy"] || 0); this.speed = parseFloat(dict["speed"] || 0); this.speedVar = parseFloat(dict["speedVariance"] || 0); this.radialAccel = parseFloat(dict["radialAcceleration"] || 0); this.radialAccelVar = parseFloat(dict["radialAccelVariance"] || 0); this.tangentialAccel = parseFloat(dict["tangentialAcceleration"] || 0); this.tangentialAccelVar = parseFloat(dict["tangentialAccelVariance"] || 0); var locRotationIsDir = dict["rotationIsDir"] || ""; if (null !== locRotationIsDir) { locRotationIsDir = locRotationIsDir.toString().toLowerCase(); this.rotationIsDir = "true" === locRotationIsDir || "1" === locRotationIsDir; } else this.rotationIsDir = false; } else { if (this.emitterMode !== EmitterMode.RADIUS) { cc.warnID(6009); return false; } this.startRadius = parseFloat(dict["maxRadius"] || 0); this.startRadiusVar = parseFloat(dict["maxRadiusVariance"] || 0); this.endRadius = parseFloat(dict["minRadius"] || 0); this.endRadiusVar = parseFloat(dict["minRadiusVariance"] || 0); this.rotatePerS = parseFloat(dict["rotatePerSecond"] || 0); this.rotatePerSVar = parseFloat(dict["rotatePerSecondVariance"] || 0); } this._initTextureWithDictionary(dict); return true; }, _onTextureLoaded: function() { this._texture = this._renderSpriteFrame.getTexture(); this._simulator.updateUVs(true); this._activateMaterial(); }, _applySpriteFrame: function(oldFrame) { oldFrame && oldFrame.off && oldFrame.off("load", this._onTextureLoaded, this); var spriteFrame = this._renderSpriteFrame = this._renderSpriteFrame || this._spriteFrame; if (spriteFrame) if (spriteFrame.textureLoaded()) this._onTextureLoaded(null); else { spriteFrame.once("load", this._onTextureLoaded, this); spriteFrame.ensureLoadTexture(); } }, _updateMaterial: function(material) { this._material = material; this._updateBlendFunc(); material.updateHash(); }, _updateBlendFunc: function(updateHash) { if (this._material) { var pass = this._material._mainTech.passes[0]; pass.setBlend(gfx.BLEND_FUNC_ADD, this._srcBlendFactor, this._dstBlendFactor, gfx.BLEND_FUNC_ADD, this._srcBlendFactor, this._dstBlendFactor); updateHash && this._material.updateHash(); } }, _activateMaterial: function() { if (!this._material) { this._material = new renderEngine.SpriteMaterial(); this._material.useTexture = true; this._material.useModel = true; this._material.useColor = false; } if (this._texture && this._texture.loaded) { this.markForUpdateRenderData(true); this.markForCustomIARender(true); this._material.texture = this._texture; this._updateMaterial(this._material); } else { this.markForCustomIARender(false); this._renderSpriteFrame && this._applySpriteFrame(); } }, _finishedSimulation: function() { false; this.disableRender(); this.autoRemoveOnFinish && this._stopped && this.node.destroy(); } }); cc.ParticleSystem = module.exports = ParticleSystem; }), { "../compression/ZipUtils": 23, "../core/components/CCRenderComponent": 78, "../core/platform/CCMacro": 166, "../core/renderer/render-engine": 203, "../core/renderer/render-flow": 204, "../core/utils/texture-util": 251, "./CCPNGReader": 263, "./CCParticleAsset": 264, "./CCTIFFReader": 266, "./particle-simulator": 268, "fire-url": void 0 } ], 266: [ (function(require, module, exports) { var debug = require("../core/CCDebug"); var tiffReader = { _littleEndian: false, _tiffData: null, _fileDirectories: [], getUint8: function(offset) { return this._tiffData[offset]; }, getUint16: function(offset) { return this._littleEndian ? this._tiffData[offset + 1] << 8 | this._tiffData[offset] : this._tiffData[offset] << 8 | this._tiffData[offset + 1]; }, getUint32: function(offset) { var a = this._tiffData; return this._littleEndian ? a[offset + 3] << 24 | a[offset + 2] << 16 | a[offset + 1] << 8 | a[offset] : a[offset] << 24 | a[offset + 1] << 16 | a[offset + 2] << 8 | a[offset + 3]; }, checkLittleEndian: function() { var BOM = this.getUint16(0); if (18761 === BOM) this.littleEndian = true; else { if (19789 !== BOM) { console.log(BOM); throw TypeError(debug.getError(6019)); } this.littleEndian = false; } return this.littleEndian; }, hasTowel: function() { if (42 !== this.getUint16(2)) throw RangeError(debug.getError(6020)); return true; }, getFieldTypeName: function(fieldType) { var typeNames = this.fieldTypeNames; if (fieldType in typeNames) return typeNames[fieldType]; return null; }, getFieldTagName: function(fieldTag) { var tagNames = this.fieldTagNames; if (fieldTag in tagNames) return tagNames[fieldTag]; cc.logID(6021, fieldTag); return "Tag" + fieldTag; }, getFieldTypeLength: function(fieldTypeName) { if (-1 !== [ "BYTE", "ASCII", "SBYTE", "UNDEFINED" ].indexOf(fieldTypeName)) return 1; if (-1 !== [ "SHORT", "SSHORT" ].indexOf(fieldTypeName)) return 2; if (-1 !== [ "LONG", "SLONG", "FLOAT" ].indexOf(fieldTypeName)) return 4; if (-1 !== [ "RATIONAL", "SRATIONAL", "DOUBLE" ].indexOf(fieldTypeName)) return 8; return null; }, getFieldValues: function(fieldTagName, fieldTypeName, typeCount, valueOffset) { var fieldValues = []; var fieldTypeLength = this.getFieldTypeLength(fieldTypeName); var fieldValueSize = fieldTypeLength * typeCount; if (fieldValueSize <= 4) false === this.littleEndian ? fieldValues.push(valueOffset >>> 8 * (4 - fieldTypeLength)) : fieldValues.push(valueOffset); else for (var i = 0; i < typeCount; i++) { var indexOffset = fieldTypeLength * i; if (fieldTypeLength >= 8) if (-1 !== [ "RATIONAL", "SRATIONAL" ].indexOf(fieldTypeName)) { fieldValues.push(this.getUint32(valueOffset + indexOffset)); fieldValues.push(this.getUint32(valueOffset + indexOffset + 4)); } else cc.logID(8e3); else fieldValues.push(this.getBytes(fieldTypeLength, valueOffset + indexOffset)); } "ASCII" === fieldTypeName && fieldValues.forEach((function(e, i, a) { a[i] = String.fromCharCode(e); })); return fieldValues; }, getBytes: function(numBytes, offset) { if (numBytes <= 0) cc.logID(8001); else { if (numBytes <= 1) return this.getUint8(offset); if (numBytes <= 2) return this.getUint16(offset); if (numBytes <= 3) return this.getUint32(offset) >>> 8; if (numBytes <= 4) return this.getUint32(offset); cc.logID(8002); } }, getBits: function(numBits, byteOffset, bitOffset) { bitOffset = bitOffset || 0; var extraBytes = Math.floor(bitOffset / 8); var newByteOffset = byteOffset + extraBytes; var totalBits = bitOffset + numBits; var shiftRight = 32 - numBits; var shiftLeft, rawBits; if (totalBits <= 0) cc.logID(6023); else if (totalBits <= 8) { shiftLeft = 24 + bitOffset; rawBits = this.getUint8(newByteOffset); } else if (totalBits <= 16) { shiftLeft = 16 + bitOffset; rawBits = this.getUint16(newByteOffset); } else if (totalBits <= 32) { shiftLeft = bitOffset; rawBits = this.getUint32(newByteOffset); } else cc.logID(6022); return { bits: rawBits << shiftLeft >>> shiftRight, byteOffset: newByteOffset + Math.floor(totalBits / 8), bitOffset: totalBits % 8 }; }, parseFileDirectory: function(byteOffset) { var numDirEntries = this.getUint16(byteOffset); var tiffFields = []; for (var i = byteOffset + 2, entryCount = 0; entryCount < numDirEntries; i += 12, entryCount++) { var fieldTag = this.getUint16(i); var fieldType = this.getUint16(i + 2); var typeCount = this.getUint32(i + 4); var valueOffset = this.getUint32(i + 8); var fieldTagName = this.getFieldTagName(fieldTag); var fieldTypeName = this.getFieldTypeName(fieldType); var fieldValues = this.getFieldValues(fieldTagName, fieldTypeName, typeCount, valueOffset); tiffFields[fieldTagName] = { type: fieldTypeName, values: fieldValues }; } this._fileDirectories.push(tiffFields); var nextIFDByteOffset = this.getUint32(i); 0 !== nextIFDByteOffset && this.parseFileDirectory(nextIFDByteOffset); }, clampColorSample: function(colorSample, bitsPerSample) { var multiplier = Math.pow(2, 8 - bitsPerSample); return Math.floor(colorSample * multiplier + (multiplier - 1)); }, parseTIFF: function(tiffData, canvas) { canvas = canvas || document.createElement("canvas"); this._tiffData = tiffData; this.canvas = canvas; this.checkLittleEndian(); if (!this.hasTowel()) return; var firstIFDByteOffset = this.getUint32(4); this._fileDirectories.length = 0; this.parseFileDirectory(firstIFDByteOffset); var fileDirectory = this._fileDirectories[0]; var imageWidth = fileDirectory["ImageWidth"].values[0]; var imageLength = fileDirectory["ImageLength"].values[0]; this.canvas.width = imageWidth; this.canvas.height = imageLength; var strips = []; var compression = fileDirectory["Compression"] ? fileDirectory["Compression"].values[0] : 1; var samplesPerPixel = fileDirectory["SamplesPerPixel"].values[0]; var sampleProperties = []; var bitsPerPixel = 0; var hasBytesPerPixel = false; fileDirectory["BitsPerSample"].values.forEach((function(bitsPerSample, i, bitsPerSampleValues) { sampleProperties[i] = { bitsPerSample: bitsPerSample, hasBytesPerSample: false, bytesPerSample: void 0 }; if (bitsPerSample % 8 === 0) { sampleProperties[i].hasBytesPerSample = true; sampleProperties[i].bytesPerSample = bitsPerSample / 8; } bitsPerPixel += bitsPerSample; }), this); if (bitsPerPixel % 8 === 0) { hasBytesPerPixel = true; var bytesPerPixel = bitsPerPixel / 8; } var stripOffsetValues = fileDirectory["StripOffsets"].values; var numStripOffsetValues = stripOffsetValues.length; if (fileDirectory["StripByteCounts"]) var stripByteCountValues = fileDirectory["StripByteCounts"].values; else { cc.logID(8003); if (1 !== numStripOffsetValues) throw Error(debug.getError(6024)); var stripByteCountValues = [ Math.ceil(imageWidth * imageLength * bitsPerPixel / 8) ]; } for (var i = 0; i < numStripOffsetValues; i++) { var stripOffset = stripOffsetValues[i]; strips[i] = []; var stripByteCount = stripByteCountValues[i]; for (var byteOffset = 0, bitOffset = 0, jIncrement = 1, getHeader = true, pixel = [], numBytes = 0, sample = 0, currentSample = 0; byteOffset < stripByteCount; byteOffset += jIncrement) switch (compression) { case 1: for (var m = 0, pixel = []; m < samplesPerPixel; m++) { if (!sampleProperties[m].hasBytesPerSample) { var sampleInfo = this.getBits(sampleProperties[m].bitsPerSample, stripOffset + byteOffset, bitOffset); pixel.push(sampleInfo.bits); byteOffset = sampleInfo.byteOffset - stripOffset; bitOffset = sampleInfo.bitOffset; throw RangeError(debug.getError(6025)); } var sampleOffset = sampleProperties[m].bytesPerSample * m; pixel.push(this.getBytes(sampleProperties[m].bytesPerSample, stripOffset + byteOffset + sampleOffset)); } strips[i].push(pixel); if (!hasBytesPerPixel) { jIncrement = 0; throw RangeError(debug.getError(6026)); } jIncrement = bytesPerPixel; break; case 2: case 3: case 4: case 5: case 6: case 7: break; case 32773: if (getHeader) { getHeader = false; var blockLength = 1; var iterations = 1; var header = this.getInt8(stripOffset + byteOffset); header >= 0 && header <= 127 ? blockLength = header + 1 : header >= -127 && header <= -1 ? iterations = 1 - header : getHeader = true; } else { var currentByte = this.getUint8(stripOffset + byteOffset); for (var m = 0; m < iterations; m++) { if (!sampleProperties[sample].hasBytesPerSample) throw RangeError(debug.getError(6025)); currentSample = currentSample << 8 * numBytes | currentByte; numBytes++; if (numBytes === sampleProperties[sample].bytesPerSample) { pixel.push(currentSample); currentSample = numBytes = 0; sample++; } if (sample === samplesPerPixel) { strips[i].push(pixel); pixel = []; sample = 0; } } blockLength--; 0 === blockLength && (getHeader = true); } jIncrement = 1; } } if (canvas.getContext) { var ctx = this.canvas.getContext("2d"); ctx.fillStyle = "rgba(255, 255, 255, 0)"; var rowsPerStrip = fileDirectory["RowsPerStrip"] ? fileDirectory["RowsPerStrip"].values[0] : imageLength; var numStrips = strips.length; var imageLengthModRowsPerStrip = imageLength % rowsPerStrip; var rowsInLastStrip = 0 === imageLengthModRowsPerStrip ? rowsPerStrip : imageLengthModRowsPerStrip; var numRowsInStrip = rowsPerStrip; var numRowsInPreviousStrip = 0; var photometricInterpretation = fileDirectory["PhotometricInterpretation"].values[0]; var extraSamplesValues = []; var numExtraSamples = 0; if (fileDirectory["ExtraSamples"]) { extraSamplesValues = fileDirectory["ExtraSamples"].values; numExtraSamples = extraSamplesValues.length; } if (fileDirectory["ColorMap"]) { var colorMapValues = fileDirectory["ColorMap"].values; var colorMapSampleSize = Math.pow(2, sampleProperties[0].bitsPerSample); } for (var i = 0; i < numStrips; i++) { i + 1 === numStrips && (numRowsInStrip = rowsInLastStrip); var numPixels = strips[i].length; var yPadding = numRowsInPreviousStrip * i; for (var y = 0, j = 0; y < numRowsInStrip, j < numPixels; y++) for (var x = 0; x < imageWidth; x++, j++) { var pixelSamples = strips[i][j]; var red = 0; var green = 0; var blue = 0; var opacity = 1; if (numExtraSamples > 0) for (var k = 0; k < numExtraSamples; k++) if (1 === extraSamplesValues[k] || 2 === extraSamplesValues[k]) { opacity = pixelSamples[3 + k] / 256; break; } switch (photometricInterpretation) { case 0: if (sampleProperties[0].hasBytesPerSample) var invertValue = Math.pow(16, 2 * sampleProperties[0].bytesPerSample); pixelSamples.forEach((function(sample, index, samples) { samples[index] = invertValue - sample; })); case 1: red = green = blue = this.clampColorSample(pixelSamples[0], sampleProperties[0].bitsPerSample); break; case 2: red = this.clampColorSample(pixelSamples[0], sampleProperties[0].bitsPerSample); green = this.clampColorSample(pixelSamples[1], sampleProperties[1].bitsPerSample); blue = this.clampColorSample(pixelSamples[2], sampleProperties[2].bitsPerSample); break; case 3: if (void 0 === colorMapValues) throw Error(debug.getError(6027)); var colorMapIndex = pixelSamples[0]; red = this.clampColorSample(colorMapValues[colorMapIndex], 16); green = this.clampColorSample(colorMapValues[colorMapSampleSize + colorMapIndex], 16); blue = this.clampColorSample(colorMapValues[2 * colorMapSampleSize + colorMapIndex], 16); break; default: throw RangeError(debug.getError(6028, photometricInterpretation)); } ctx.fillStyle = "rgba(" + red + ", " + green + ", " + blue + ", " + opacity + ")"; ctx.fillRect(x, yPadding + y, 1, 1); } numRowsInPreviousStrip = numRowsInStrip; } } return this.canvas; }, fieldTagNames: { 315: "Artist", 258: "BitsPerSample", 265: "CellLength", 264: "CellWidth", 320: "ColorMap", 259: "Compression", 33432: "Copyright", 306: "DateTime", 338: "ExtraSamples", 266: "FillOrder", 289: "FreeByteCounts", 288: "FreeOffsets", 291: "GrayResponseCurve", 290: "GrayResponseUnit", 316: "HostComputer", 270: "ImageDescription", 257: "ImageLength", 256: "ImageWidth", 271: "Make", 281: "MaxSampleValue", 280: "MinSampleValue", 272: "Model", 254: "NewSubfileType", 274: "Orientation", 262: "PhotometricInterpretation", 284: "PlanarConfiguration", 296: "ResolutionUnit", 278: "RowsPerStrip", 277: "SamplesPerPixel", 305: "Software", 279: "StripByteCounts", 273: "StripOffsets", 255: "SubfileType", 263: "Threshholding", 282: "XResolution", 283: "YResolution", 326: "BadFaxLines", 327: "CleanFaxData", 343: "ClipPath", 328: "ConsecutiveBadFaxLines", 433: "Decode", 434: "DefaultImageColor", 269: "DocumentName", 336: "DotRange", 321: "HalftoneHints", 346: "Indexed", 347: "JPEGTables", 285: "PageName", 297: "PageNumber", 317: "Predictor", 319: "PrimaryChromaticities", 532: "ReferenceBlackWhite", 339: "SampleFormat", 559: "StripRowCounts", 330: "SubIFDs", 292: "T4Options", 293: "T6Options", 325: "TileByteCounts", 323: "TileLength", 324: "TileOffsets", 322: "TileWidth", 301: "TransferFunction", 318: "WhitePoint", 344: "XClipPathUnits", 286: "XPosition", 529: "YCbCrCoefficients", 531: "YCbCrPositioning", 530: "YCbCrSubSampling", 345: "YClipPathUnits", 287: "YPosition", 37378: "ApertureValue", 40961: "ColorSpace", 36868: "DateTimeDigitized", 36867: "DateTimeOriginal", 34665: "Exif IFD", 36864: "ExifVersion", 33434: "ExposureTime", 41728: "FileSource", 37385: "Flash", 40960: "FlashpixVersion", 33437: "FNumber", 42016: "ImageUniqueID", 37384: "LightSource", 37500: "MakerNote", 37377: "ShutterSpeedValue", 37510: "UserComment", 33723: "IPTC", 34675: "ICC Profile", 700: "XMP", 42112: "GDAL_METADATA", 42113: "GDAL_NODATA", 34377: "Photoshop" }, fieldTypeNames: { 1: "BYTE", 2: "ASCII", 3: "SHORT", 4: "LONG", 5: "RATIONAL", 6: "SBYTE", 7: "UNDEFINED", 8: "SSHORT", 9: "SLONG", 10: "SRATIONAL", 11: "FLOAT", 12: "DOUBLE" } }; module.exports = tiffReader; }), { "../core/CCDebug": 27 } ], 267: [ (function(require, module, exports) { require("./CCParticleAsset"); require("./CCParticleSystem"); require("./particle-simulator"); require("./particle-system-assembler"); }), { "./CCParticleAsset": 264, "./CCParticleSystem": 265, "./particle-simulator": 268, "./particle-system-assembler": 269 } ], 268: [ (function(require, module, exports) { var AffineTrans = require("../core/utils/affine-transform"); var js = require("../core/platform/js"); var misc = require("../core/utils/misc"); var ZERO_VEC2 = cc.v2(0, 0); var _trans = AffineTrans.create(); var _pos = cc.v2(); var _tpa = cc.v2(); var _tpb = cc.v2(); var _tpc = cc.v2(); var Particle = function() { this.pos = cc.v2(0, 0); this.startPos = cc.v2(0, 0); this.color = cc.color(0, 0, 0, 255); this.deltaColor = { r: 0, g: 0, b: 0, a: 255 }; this.size = 0; this.deltaSize = 0; this.rotation = 0; this.deltaRotation = 0; this.timeToLive = 0; this.drawPos = cc.v2(0, 0); this.dir = cc.v2(0, 0); this.radialAccel = 0; this.tangentialAccel = 0; this.angle = 0; this.degreesPerSecond = 0; this.radius = 0; this.deltaRadius = 0; }; var pool = new js.Pool(function(par) { par.pos.set(ZERO_VEC2); par.startPos.set(ZERO_VEC2); par.color._val = 4278190080; par.deltaColor.r = par.deltaColor.g = par.deltaColor.b = 0; par.deltaColor.a = 255; par.size = 0; par.deltaSize = 0; par.rotation = 0; par.deltaRotation = 0; par.timeToLive = 0; par.drawPos.set(ZERO_VEC2); par.dir.set(ZERO_VEC2); par.radialAccel = 0; par.tangentialAccel = 0; par.angle = 0; par.degreesPerSecond = 0; par.radius = 0; par.deltaRadius = 0; }, 1024); pool.get = function() { return this._get() || new Particle(); }; var Simulator = function(system) { this.sys = system; this.particles = []; this.active = false; this.finished = false; this.elapsed = 0; this.emitCounter = 0; this._uvFilled = 0; }; Simulator.prototype.stop = function() { this.active = false; this.elapsed = this.sys.duration; this.emitCounter = 0; }; Simulator.prototype.reset = function() { this.active = true; this.elapsed = 0; this.emitCounter = 0; this.finished = false; var particles = this.particles; for (var id = 0; id < particles.length; ++id) pool.put(particles[id]); particles.length = 0; }; Simulator.prototype.emitParticle = function(pos) { var psys = this.sys; var clampf = misc.clampf; var particle = pool.get(); this.particles.push(particle); particle.timeToLive = psys.life + psys.lifeVar * (Math.random() - .5) * 2; var timeToLive = particle.timeToLive = Math.max(0, particle.timeToLive); particle.pos.x = psys.sourcePos.x + psys.posVar.x * (Math.random() - .5) * 2; particle.pos.y = psys.sourcePos.y + psys.posVar.y * (Math.random() - .5) * 2; var sr = void 0, sg = void 0, sb = void 0, sa = void 0; var startColor = psys._startColor, startColorVar = psys._startColorVar; var endColor = psys._endColor, endColorVar = psys._endColorVar; particle.color.r = sr = clampf(startColor.r + startColorVar.r * (Math.random() - .5) * 2, 0, 255); particle.color.g = sg = clampf(startColor.g + startColorVar.g * (Math.random() - .5) * 2, 0, 255); particle.color.b = sb = clampf(startColor.b + startColorVar.b * (Math.random() - .5) * 2, 0, 255); particle.color.a = sa = clampf(startColor.a + startColorVar.a * (Math.random() - .5) * 2, 0, 255); particle.deltaColor.r = (clampf(endColor.r + endColorVar.r * (Math.random() - .5) * 2, 0, 255) - sr) / timeToLive; particle.deltaColor.g = (clampf(endColor.g + endColorVar.g * (Math.random() - .5) * 2, 0, 255) - sg) / timeToLive; particle.deltaColor.b = (clampf(endColor.b + endColorVar.b * (Math.random() - .5) * 2, 0, 255) - sb) / timeToLive; particle.deltaColor.a = (clampf(endColor.a + endColorVar.a * (Math.random() - .5) * 2, 0, 255) - sa) / timeToLive; var startS = psys.startSize + psys.startSizeVar * (Math.random() - .5) * 2; startS = Math.max(0, startS); particle.size = startS; if (psys.endSize === cc.ParticleSystem.START_SIZE_EQUAL_TO_END_SIZE) particle.deltaSize = 0; else { var endS = psys.endSize + psys.endSizeVar * (Math.random() - .5) * 2; endS = Math.max(0, endS); particle.deltaSize = (endS - startS) / timeToLive; } var startA = psys.startSpin + psys.startSpinVar * (Math.random() - .5) * 2; var endA = psys.endSpin + psys.endSpinVar * (Math.random() - .5) * 2; particle.rotation = startA; particle.deltaRotation = (endA - startA) / timeToLive; particle.startPos.x = pos.x; particle.startPos.y = pos.y; var a = misc.degreesToRadians(psys.angle + psys.angleVar * (Math.random() - .5) * 2); if (psys.emitterMode === cc.ParticleSystem.EmitterMode.GRAVITY) { var s = psys.speed + psys.speedVar * (Math.random() - .5) * 2; particle.dir.x = Math.cos(a); particle.dir.y = Math.sin(a); particle.dir.mulSelf(s); particle.radialAccel = psys.radialAccel + psys.radialAccelVar * (Math.random() - .5) * 2; particle.tangentialAccel = psys.tangentialAccel + psys.tangentialAccelVar * (Math.random() - .5) * 2; psys.rotationIsDir && (particle.rotation = -misc.radiansToDegrees(Math.atan2(particle.dir.y, particle.dir.x))); } else { var startRadius = psys.startRadius + psys.startRadiusVar * (Math.random() - .5) * 2; var endRadius = psys.endRadius + psys.endRadiusVar * (Math.random() - .5) * 2; particle.radius = startRadius; particle.deltaRadius = psys.endRadius === cc.ParticleSystem.START_RADIUS_EQUAL_TO_END_RADIUS ? 0 : (endRadius - startRadius) / timeToLive; particle.angle = a; particle.degreesPerSecond = misc.degreesToRadians(psys.rotatePerS + psys.rotatePerSVar * (Math.random() - .5) * 2); } }; Simulator.prototype.updateUVs = function(force) { var particleCount = this.particles.length; if (this.sys._buffer && this.sys._renderSpriteFrame) { var FLOAT_PER_PARTICLE = 4 * this.sys._vertexFormat._bytes / 4; var vbuf = this.sys._buffer._vData; var uv = this.sys._renderSpriteFrame.uv; var start = force ? 0 : this._uvFilled; for (var i = start; i < particleCount; i++) { var offset = i * FLOAT_PER_PARTICLE; vbuf[offset + 2] = uv[0]; vbuf[offset + 3] = uv[1]; vbuf[offset + 7] = uv[2]; vbuf[offset + 8] = uv[3]; vbuf[offset + 12] = uv[4]; vbuf[offset + 13] = uv[5]; vbuf[offset + 17] = uv[6]; vbuf[offset + 18] = uv[7]; } this._uvFilled = particleCount; } }; Simulator.prototype.updateParticleBuffer = function(particle, pos, buffer, offset) { var vbuf = buffer._vData; var uintbuf = buffer._uintVData; var x = pos.x, y = pos.y; var size_2 = particle.size / 2; if (particle.rotation) { var x1 = -size_2, y1 = -size_2; var x2 = size_2, y2 = size_2; var rad = -misc.degreesToRadians(particle.rotation); var cr = Math.cos(rad), sr = Math.sin(rad); vbuf[offset] = x1 * cr - y1 * sr + x; vbuf[offset + 1] = x1 * sr + y1 * cr + y; vbuf[offset + 5] = x2 * cr - y1 * sr + x; vbuf[offset + 6] = x2 * sr + y1 * cr + y; vbuf[offset + 10] = x1 * cr - y2 * sr + x; vbuf[offset + 11] = x1 * sr + y2 * cr + y; vbuf[offset + 15] = x2 * cr - y2 * sr + x; vbuf[offset + 16] = x2 * sr + y2 * cr + y; } else { vbuf[offset] = x - size_2; vbuf[offset + 1] = y - size_2; vbuf[offset + 5] = x + size_2; vbuf[offset + 6] = y - size_2; vbuf[offset + 10] = x - size_2; vbuf[offset + 11] = y + size_2; vbuf[offset + 15] = x + size_2; vbuf[offset + 16] = y + size_2; } uintbuf[offset + 4] = particle.color._val; uintbuf[offset + 9] = particle.color._val; uintbuf[offset + 14] = particle.color._val; uintbuf[offset + 19] = particle.color._val; }; Simulator.prototype.step = function(dt) { var psys = this.sys; var node = psys.node; var particles = this.particles; var FLOAT_PER_PARTICLE = 4 * psys._vertexFormat._bytes / 4; node._updateWorldMatrix(); AffineTrans.fromMat4(_trans, node._worldMatrix); if (psys.positionType === cc.ParticleSystem.PositionType.FREE) AffineTrans.transformVec2(_pos, ZERO_VEC2, _trans); else if (psys.positionType === cc.ParticleSystem.PositionType.RELATIVE) { _pos.x = node._position.x; _pos.y = node._position.y; } AffineTrans.invert(_trans, _trans); var worldToNodeTrans = _trans; if (this.active && psys.emissionRate) { var rate = 1 / psys.emissionRate; particles.length < psys.totalParticles && (this.emitCounter += dt); while (particles.length < psys.totalParticles && this.emitCounter > rate) { this.emitParticle(_pos); this.emitCounter -= rate; } this.elapsed += dt; -1 !== psys.duration && psys.duration < this.elapsed && psys.stopSystem(); } var buffer = psys._buffer; var particleCount = particles.length; buffer.reset(); buffer.request(4 * particleCount, 6 * particleCount); particleCount > this._uvFilled && this.updateUVs(); var particleIdx = 0; while (particleIdx < particles.length) { _tpa.x = _tpa.y = _tpb.x = _tpb.y = _tpc.x = _tpc.y = 0; var particle = particles[particleIdx]; particle.timeToLive -= dt; if (particle.timeToLive > 0) { if (psys.emitterMode === cc.ParticleSystem.EmitterMode.GRAVITY) { var tmp = _tpc, radial = _tpa, tangential = _tpb; if (particle.pos.x || particle.pos.y) { radial.set(particle.pos); radial.normalizeSelf(); } tangential.set(radial); radial.mulSelf(particle.radialAccel); var newy = tangential.x; tangential.x = -tangential.y; tangential.y = newy; tangential.mulSelf(particle.tangentialAccel); tmp.set(radial); tmp.addSelf(tangential); tmp.addSelf(psys.gravity); tmp.mulSelf(dt); particle.dir.addSelf(tmp); tmp.set(particle.dir); tmp.mulSelf(dt); particle.pos.addSelf(tmp); } else { particle.angle += particle.degreesPerSecond * dt; particle.radius += particle.deltaRadius * dt; particle.pos.x = -Math.cos(particle.angle) * particle.radius; particle.pos.y = -Math.sin(particle.angle) * particle.radius; } particle.color.r += particle.deltaColor.r * dt; particle.color.g += particle.deltaColor.g * dt; particle.color.b += particle.deltaColor.b * dt; particle.color.a += particle.deltaColor.a * dt; particle.size += particle.deltaSize * dt; particle.size < 0 && (particle.size = 0); particle.rotation += particle.deltaRotation * dt; var newPos = _tpa; if (psys.positionType === cc.ParticleSystem.PositionType.FREE || psys.positionType === cc.ParticleSystem.PositionType.RELATIVE) { var diff = _tpb, startPos = _tpc; AffineTrans.transformVec2(diff, _pos, worldToNodeTrans); AffineTrans.transformVec2(startPos, particle.startPos, worldToNodeTrans); diff.subSelf(startPos); newPos.set(particle.pos); newPos.subSelf(diff); } else newPos.set(particle.pos); var offset = FLOAT_PER_PARTICLE * particleIdx; this.updateParticleBuffer(particle, newPos, buffer, offset); ++particleIdx; } else { var deadParticle = particles[particleIdx]; particleIdx !== particles.length - 1 && (particles[particleIdx] = particles[particles.length - 1]); pool.put(deadParticle); particles.length--; } } if (particles.length > 0) { buffer.uploadData(); psys._ia._count = 6 * particles.length; } else if (!this.active) { this.finished = true; psys._finishedSimulation(); } }; module.exports = Simulator; }), { "../core/platform/js": 181, "../core/utils/affine-transform": 235, "../core/utils/misc": 243 } ], 269: [ (function(require, module, exports) { var ParticleSystem = require("./CCParticleSystem"); var renderer = require("../core/renderer/"); var renderEngine = require("../core/renderer/render-engine"); var vfmtPosUvColor = require("../core/renderer/webgl/vertex-format").vfmtPosUvColor; var QuadBuffer = require("../core/renderer/webgl/quad-buffer"); var particleSystemAssembler = { useModel: true, createIA: function(comp) { var device = renderer.device; comp._vertexFormat = vfmtPosUvColor; comp._buffer = new QuadBuffer(renderer._handle, vfmtPosUvColor); comp._ia = new renderEngine.InputAssembler(); comp._ia._vertexBuffer = comp._buffer._vb; comp._ia._indexBuffer = comp._buffer._ib; comp._ia._start = 0; comp._ia._count = 0; }, updateRenderData: function(comp) { if (!comp._renderData) { comp._renderData = new renderEngine.IARenderData(); comp._renderData.ia = comp._ia; } comp._renderData.material = comp._material; }, renderIA: function(comp, renderer) { renderer._flushIA(comp._renderData); } }; ParticleSystem._assembler = particleSystemAssembler; module.exports = particleSystemAssembler; }), { "../core/renderer/": 202, "../core/renderer/render-engine": 203, "../core/renderer/webgl/quad-buffer": 230, "../core/renderer/webgl/vertex-format": 233, "./CCParticleSystem": 265 } ], 270: [ (function(require, module, exports) { "use strict"; var codec = require("../compression/ZipUtils"); var zlib = require("../compression/zlib.min"); var js = require("../core/platform/js"); require("../core/platform/CCSAXParser"); function uint8ArrayToUint32Array(uint8Arr) { if (uint8Arr.length % 4 !== 0) return null; var arrLen = uint8Arr.length / 4; var retArr = window.Uint32Array ? new Uint32Array(arrLen) : []; for (var i = 0; i < arrLen; i++) { var offset = 4 * i; retArr[i] = uint8Arr[offset] + 256 * uint8Arr[offset + 1] + 65536 * uint8Arr[offset + 2] + uint8Arr[offset + 3] * (1 << 24); } return retArr; } cc.TMXLayerInfo = function() { this.properties = {}; this.name = ""; this._layerSize = null; this._tiles = []; this.visible = true; this._opacity = 0; this.ownTiles = true; this._minGID = 1e5; this._maxGID = 0; this.offset = cc.v2(0, 0); }; cc.TMXLayerInfo.prototype = { constructor: cc.TMXLayerInfo, getProperties: function() { return this.properties; }, setProperties: function(value) { this.properties = value; } }; cc.TMXObjectGroupInfo = function() { this.properties = {}; this.name = ""; this._objects = []; this.visible = true; this._opacity = 0; this._color = new cc.Color(255, 255, 255, 255); this.offset = cc.v2(0, 0); this._draworder = "topdown"; }; cc.TMXObjectGroupInfo.prototype = { constructor: cc.TMXObjectGroupInfo, getProperties: function() { return this.properties; }, setProperties: function(value) { this.properties = value; } }; cc.TMXTilesetInfo = function() { this.name = ""; this.firstGid = 0; this.spacing = 0; this.margin = 0; this.sourceImage = null; this.imageSize = cc.size(0, 0); this.tileOffset = cc.v2(0, 0); this._tileSize = cc.size(0, 0); }; cc.TMXTilesetInfo.prototype = { constructor: cc.TMXTilesetInfo, rectForGID: function(gid, result) { var rect = result || cc.rect(0, 0, 0, 0); rect.width = this._tileSize.width; rect.height = this._tileSize.height; gid &= cc.TiledMap.TileFlag.FLIPPED_MASK; gid -= parseInt(this.firstGid, 10); var max_x = parseInt((this.imageSize.width - 2 * this.margin + this.spacing) / (this._tileSize.width + this.spacing), 10); rect.x = parseInt(gid % max_x * (this._tileSize.width + this.spacing) + this.margin, 10); rect.y = parseInt(parseInt(gid / max_x, 10) * (this._tileSize.height + this.spacing) + this.margin, 10); return rect; } }; function getPropertyList(node, map) { var res = []; var properties = node.getElementsByTagName("properties"); for (var i = 0; i < properties.length; ++i) { var property = properties[i].getElementsByTagName("property"); for (var j = 0; j < property.length; ++j) res.push(property[j]); } map = map || {}; for (var _i = 0; _i < res.length; _i++) { var element = res[_i]; var name = element.getAttribute("name"); var type = element.getAttribute("type") || "string"; var value = element.getAttribute("value"); if ("int" === type) value = parseInt(value); else if ("float" === type) value = parseFloat(value); else if ("bool" === type) value = "true" === value; else if ("color" === type) { value = 0 === value.indexOf("#") ? value.substring(1) : value; var a = parseInt(value.substr(0, 2), 16) || 255; var r = parseInt(value.substr(2, 2), 16) || 0; var g = parseInt(value.substr(4, 2), 16) || 0; var b = parseInt(value.substr(6, 2), 16) || 0; value = cc.color(r, g, b, a); } map[name] = value; } return map; } cc.TMXMapInfo = function(tmxFile, tsxMap, textures) { this.properties = []; this.orientation = null; this.parentElement = null; this.parentGID = null; this.layerAttrs = 0; this.storingCharacters = false; this.currentString = null; this._parser = new cc.SAXParser(); this._objectGroups = []; this._allChildren = []; this._mapSize = cc.size(0, 0); this._tileSize = cc.size(0, 0); this._layers = []; this._tilesets = []; this._tileProperties = {}; this._tsxMap = null; this._textures = null; this._staggerAxis = null; this._staggerIndex = null; this._hexSideLength = 0; this.initWithXML(tmxFile, tsxMap, textures); }; cc.TMXMapInfo.prototype = { constructor: cc.TMXMapInfo, getOrientation: function() { return this.orientation; }, setOrientation: function(value) { this.orientation = value; }, getStaggerAxis: function() { return this._staggerAxis; }, setStaggerAxis: function(value) { this._staggerAxis = value; }, getStaggerIndex: function() { return this._staggerIndex; }, setStaggerIndex: function(value) { this._staggerIndex = value; }, getHexSideLength: function() { return this._hexSideLength; }, setHexSideLength: function(value) { this._hexSideLength = value; }, getMapSize: function() { return cc.size(this._mapSize.width, this._mapSize.height); }, setMapSize: function(value) { this._mapSize.width = value.width; this._mapSize.height = value.height; }, _getMapWidth: function() { return this._mapSize.width; }, _setMapWidth: function(width) { this._mapSize.width = width; }, _getMapHeight: function() { return this._mapSize.height; }, _setMapHeight: function(height) { this._mapSize.height = height; }, getTileSize: function() { return cc.size(this._tileSize.width, this._tileSize.height); }, setTileSize: function(value) { this._tileSize.width = value.width; this._tileSize.height = value.height; }, _getTileWidth: function() { return this._tileSize.width; }, _setTileWidth: function(width) { this._tileSize.width = width; }, _getTileHeight: function() { return this._tileSize.height; }, _setTileHeight: function(height) { this._tileSize.height = height; }, getLayers: function() { return this._layers; }, setLayers: function(value) { this._allChildren.push(value); this._layers.push(value); }, getTilesets: function() { return this._tilesets; }, setTilesets: function(value) { this._tilesets.push(value); }, getObjectGroups: function() { return this._objectGroups; }, setObjectGroups: function(value) { this._allChildren.push(value); this._objectGroups.push(value); }, getAllChildren: function() { return this._allChildren; }, getParentElement: function() { return this.parentElement; }, setParentElement: function(value) { this.parentElement = value; }, getParentGID: function() { return this.parentGID; }, setParentGID: function(value) { this.parentGID = value; }, getLayerAttribs: function() { return this.layerAttrs; }, setLayerAttribs: function(value) { this.layerAttrs = value; }, getStoringCharacters: function() { return this.storingCharacters; }, setStoringCharacters: function(value) { this.storingCharacters = value; }, getProperties: function() { return this.properties; }, setProperties: function(value) { this.properties = value; }, initWithXML: function(tmxString, tsxMap, textures) { this._tilesets.length = 0; this._layers.length = 0; this._tsxMap = tsxMap; this._textures = textures; this._objectGroups.length = 0; this._allChildren.length = 0; this.properties.length = 0; this._tileProperties.length = 0; this.currentString = ""; this.storingCharacters = false; this.layerAttrs = cc.TMXLayerInfo.ATTRIB_NONE; this.parentElement = cc.TiledMap.NONE; return this.parseXMLString(tmxString); }, parseXMLString: function(xmlStr, tilesetFirstGid) { var mapXML = this._parser._parseXML(xmlStr); var i = void 0, j = void 0; var map = mapXML.documentElement; var version = map.getAttribute("version"); var orientationStr = map.getAttribute("orientation"); var staggerAxisStr = map.getAttribute("staggeraxis"); var staggerIndexStr = map.getAttribute("staggerindex"); var hexSideLengthStr = map.getAttribute("hexsidelength"); if ("map" === map.nodeName) { "1.0" !== version && null !== version && cc.logID(7216, version); "orthogonal" === orientationStr ? this.orientation = cc.TiledMap.Orientation.ORTHO : "isometric" === orientationStr ? this.orientation = cc.TiledMap.Orientation.ISO : "hexagonal" === orientationStr ? this.orientation = cc.TiledMap.Orientation.HEX : null !== orientationStr && cc.logID(7217, orientationStr); "x" === staggerAxisStr ? this.setStaggerAxis(cc.TiledMap.StaggerAxis.STAGGERAXIS_X) : "y" === staggerAxisStr && this.setStaggerAxis(cc.TiledMap.StaggerAxis.STAGGERAXIS_Y); "odd" === staggerIndexStr ? this.setStaggerIndex(cc.TiledMap.StaggerIndex.STAGGERINDEX_ODD) : "even" === staggerIndexStr && this.setStaggerIndex(cc.TiledMap.StaggerIndex.STAGGERINDEX_EVEN); hexSideLengthStr && this.setHexSideLength(parseFloat(hexSideLengthStr)); var mapSize = cc.size(0, 0); mapSize.width = parseFloat(map.getAttribute("width")); mapSize.height = parseFloat(map.getAttribute("height")); this.setMapSize(mapSize); mapSize = cc.size(0, 0); mapSize.width = parseFloat(map.getAttribute("tilewidth")); mapSize.height = parseFloat(map.getAttribute("tileheight")); this.setTileSize(mapSize); this.properties = getPropertyList(map); } var tilesets = map.getElementsByTagName("tileset"); if ("map" !== map.nodeName) { tilesets = []; tilesets.push(map); } for (i = 0; i < tilesets.length; i++) { var selTileset = tilesets[i]; var tsxName = selTileset.getAttribute("source"); if (tsxName) { var currentFirstGID = parseInt(selTileset.getAttribute("firstgid")); var tsxXmlString = this._tsxMap[tsxName]; tsxXmlString && this.parseXMLString(tsxXmlString, currentFirstGID); } else { var tileset = new cc.TMXTilesetInfo(); tileset.name = selTileset.getAttribute("name") || ""; tileset.firstGid = tilesetFirstGid || (parseInt(selTileset.getAttribute("firstgid")) || 0); tileset.spacing = parseInt(selTileset.getAttribute("spacing")) || 0; tileset.margin = parseInt(selTileset.getAttribute("margin")) || 0; var tilesetSize = cc.size(0, 0); tilesetSize.width = parseFloat(selTileset.getAttribute("tilewidth")); tilesetSize.height = parseFloat(selTileset.getAttribute("tileheight")); tileset._tileSize = tilesetSize; var image = selTileset.getElementsByTagName("image")[0]; var imagename = image.getAttribute("source"); imagename.replace(/\\/g, "/"); tileset.sourceImage = this._textures[imagename]; tileset.sourceImage || cc.errorID(7221, imagename); this.setTilesets(tileset); var offset = selTileset.getElementsByTagName("tileoffset")[0]; if (offset) { var offsetX = parseFloat(offset.getAttribute("x")); var offsetY = parseFloat(offset.getAttribute("y")); tileset.tileOffset = cc.v2(offsetX, offsetY); } var tiles = selTileset.getElementsByTagName("tile"); if (tiles) for (var tIdx = 0; tIdx < tiles.length; tIdx++) { var t = tiles[tIdx]; this.parentGID = parseInt(tileset.firstGid) + parseInt(t.getAttribute("id") || 0); this._tileProperties[this.parentGID] = getPropertyList(t); } } } var childNodes = map.childNodes; for (i = 0; i < childNodes.length; i++) { var childNode = childNodes[i]; if (this._shouldIgnoreNode(childNode)) continue; if ("layer" === childNode.nodeName) { var layer = this._parseLayer(childNode); this.setLayers(layer); } if ("objectgroup" === childNode.nodeName) { var objectGroup = this._parseObjectGroup(childNode); this.setObjectGroups(objectGroup); } } return map; }, _shouldIgnoreNode: function(node) { return 3 === node.nodeType || 8 === node.nodeType || 4 === node.nodeType; }, _parseLayer: function(selLayer) { var data = selLayer.getElementsByTagName("data")[0]; var layer = new cc.TMXLayerInfo(); layer.name = selLayer.getAttribute("name"); var layerSize = cc.size(0, 0); layerSize.width = parseFloat(selLayer.getAttribute("width")); layerSize.height = parseFloat(selLayer.getAttribute("height")); layer._layerSize = layerSize; var visible = selLayer.getAttribute("visible"); layer.visible = !("0" === visible); var opacity = selLayer.getAttribute("opacity") || 1; layer._opacity = opacity ? parseInt(255 * parseFloat(opacity)) : 255; layer.offset = cc.v2(parseFloat(selLayer.getAttribute("x")) || 0, parseFloat(selLayer.getAttribute("y")) || 0); var nodeValue = ""; for (var j = 0; j < data.childNodes.length; j++) nodeValue += data.childNodes[j].nodeValue; nodeValue = nodeValue.trim(); var compression = data.getAttribute("compression"); var encoding = data.getAttribute("encoding"); if (compression && "gzip" !== compression && "zlib" !== compression) { cc.logID(7218); return null; } var tiles = void 0; switch (compression) { case "gzip": tiles = codec.unzipBase64AsArray(nodeValue, 4); break; case "zlib": var inflator = new zlib.Inflate(codec.Base64.decodeAsArray(nodeValue, 1)); tiles = uint8ArrayToUint32Array(inflator.decompress()); break; case null: case "": if ("base64" === encoding) tiles = codec.Base64.decodeAsArray(nodeValue, 4); else if ("csv" === encoding) { tiles = []; var csvTiles = nodeValue.split(","); for (var csvIdx = 0; csvIdx < csvTiles.length; csvIdx++) tiles.push(parseInt(csvTiles[csvIdx])); } else { var selDataTiles = data.getElementsByTagName("tile"); tiles = []; for (var xmlIdx = 0; xmlIdx < selDataTiles.length; xmlIdx++) tiles.push(parseInt(selDataTiles[xmlIdx].getAttribute("gid"))); } break; default: this.layerAttrs === cc.TMXLayerInfo.ATTRIB_NONE && cc.logID(7219); } tiles && (layer._tiles = new Uint32Array(tiles)); layer.properties = getPropertyList(selLayer); return layer; }, _parseObjectGroup: function(selGroup) { var objectGroup = new cc.TMXObjectGroupInfo(); objectGroup.name = selGroup.getAttribute("name") || ""; objectGroup.offset = cc.v2(parseFloat(selGroup.getAttribute("offsetx")), parseFloat(selGroup.getAttribute("offsety"))); var opacity = selGroup.getAttribute("opacity") || 1; objectGroup._opacity = opacity ? parseInt(255 * parseFloat(opacity)) : 255; var visible = selGroup.getAttribute("visible"); visible && 0 === parseInt(visible) && (objectGroup.visible = false); var color = selGroup.getAttribute("color"); color && objectGroup._color.fromHEX(color); var draworder = selGroup.getAttribute("draworder"); draworder && (objectGroup._draworder = draworder); objectGroup.setProperties(getPropertyList(selGroup)); var objects = selGroup.getElementsByTagName("object"); if (objects) for (var j = 0; j < objects.length; j++) { var selObj = objects[j]; var objectProp = {}; objectProp["id"] = selObj.getAttribute("id") || 0; objectProp["name"] = selObj.getAttribute("name") || ""; objectProp["width"] = parseFloat(selObj.getAttribute("width")) || 0; objectProp["height"] = parseFloat(selObj.getAttribute("height")) || 0; objectProp["x"] = parseFloat(selObj.getAttribute("x")) || 0; objectProp["y"] = parseFloat(selObj.getAttribute("y")) || 0; objectProp["rotation"] = parseFloat(selObj.getAttribute("rotation")) || 0; getPropertyList(selObj, objectProp); var visibleAttr = selObj.getAttribute("visible"); objectProp["visible"] = !(visibleAttr && 0 === parseInt(visibleAttr)); var gid = selObj.getAttribute("gid"); if (gid) { objectProp["gid"] = parseInt(gid); objectProp["type"] = cc.TiledMap.TMXObjectType.IMAGE; } var ellipse = selObj.getElementsByTagName("ellipse"); ellipse && ellipse.length > 0 && (objectProp["type"] = cc.TiledMap.TMXObjectType.ELLIPSE); var polygonProps = selObj.getElementsByTagName("polygon"); if (polygonProps && polygonProps.length > 0) { objectProp["type"] = cc.TiledMap.TMXObjectType.POLYGON; var selPgPointStr = polygonProps[0].getAttribute("points"); selPgPointStr && (objectProp["points"] = this._parsePointsString(selPgPointStr)); } var polylineProps = selObj.getElementsByTagName("polyline"); if (polylineProps && polylineProps.length > 0) { objectProp["type"] = cc.TiledMap.TMXObjectType.POLYLINE; var selPlPointStr = polylineProps[0].getAttribute("points"); selPlPointStr && (objectProp["polylinePoints"] = this._parsePointsString(selPlPointStr)); } objectProp["type"] || (objectProp["type"] = cc.TiledMap.TMXObjectType.RECT); objectGroup._objects.push(objectProp); } return objectGroup; }, _parsePointsString: function(pointsString) { if (!pointsString) return null; var points = []; var pointsStr = pointsString.split(" "); for (var i = 0; i < pointsStr.length; i++) { var selPointStr = pointsStr[i].split(","); points.push({ x: parseFloat(selPointStr[0]), y: parseFloat(selPointStr[1]) }); } return points; }, getTileProperties: function() { return this._tileProperties; }, setTileProperties: function(tileProperties) { this._tileProperties.push(tileProperties); }, getCurrentString: function() { return this.currentString; }, setCurrentString: function(currentString) { this.currentString = currentString; } }; var _p = cc.TMXMapInfo.prototype; js.getset(_p, "mapWidth", _p._getMapWidth, _p._setMapWidth); js.getset(_p, "mapHeight", _p._getMapHeight, _p._setMapHeight); js.getset(_p, "tileWidth", _p._getTileWidth, _p._setTileWidth); js.getset(_p, "tileHeight", _p._getTileHeight, _p._setTileHeight); cc.TMXLayerInfo.ATTRIB_NONE = 1; cc.TMXLayerInfo.ATTRIB_BASE64 = 2; cc.TMXLayerInfo.ATTRIB_GZIP = 4; cc.TMXLayerInfo.ATTRIB_ZLIB = 8; }), { "../compression/ZipUtils": 23, "../compression/zlib.min": 26, "../core/platform/CCSAXParser": 168, "../core/platform/js": 181 } ], 271: [ (function(require, module, exports) { var RenderComponent = require("../core/components/CCRenderComponent"); var renderEngine = require("../core/renderer/render-engine"); var SpriteMaterial = renderEngine.SpriteMaterial; var TiledLayer = cc.Class({ name: "cc.TiledLayer", extends: RenderComponent, ctor: function() { this._tiles = []; this._texGrids = []; this._textures = []; this._spriteTiles = {}; this._tiledTiles = []; this._layerName = ""; this._layerOrientation = null; }, getLayerName: function() { return this._layerName; }, setLayerName: function(layerName) { this._layerName = layerName; }, getProperty: function(propertyName) { return this._properties[propertyName]; }, getPositionAt: function(pos, y) { var x = void 0; if (void 0 !== y) { x = Math.floor(pos); y = Math.floor(y); } else { x = Math.floor(pos.x); y = Math.floor(pos.y); } var ret = void 0; switch (this._layerOrientation) { case cc.TiledMap.Orientation.ORTHO: ret = this._positionForOrthoAt(x, y); break; case cc.TiledMap.Orientation.ISO: ret = this._positionForIsoAt(x, y); break; case cc.TiledMap.Orientation.HEX: ret = this._positionForHexAt(x, y); } return ret; }, _isInvalidPosition: function(x, y) { if (x && "object" === (__typeofVal = typeof x, "object" === __typeofVal ? __realTypeOfObj(x) : __typeofVal)) { var pos = x; y = pos.y; x = pos.x; } return x >= this._layerSize.width || y >= this._layerSize.height || x < 0 || y < 0; }, _positionForIsoAt: function(x, y) { return cc.v2(this._mapTileSize.width / 2 * (this._layerSize.width + x - y - 1), this._mapTileSize.height / 2 * (2 * this._layerSize.height - x - y - 2)); }, _positionForOrthoAt: function(x, y) { return cc.v2(x * this._mapTileSize.width, (this._layerSize.height - y - 1) * this._mapTileSize.height); }, _positionForHexAt: function(row, col) { var tileWidth = this._mapTileSize.width; var tileHeight = this._mapTileSize.height; var cols = this._layerSize.height; var offset = this._tileset.tileOffset; var centerWidth = this.node.width / 2; var centerHeight = this.node.height / 2; var odd_even = this._staggerIndex === cc.TiledMap.StaggerIndex.STAGGERINDEX_ODD ? 1 : -1; var x = 0, y = 0; switch (this._staggerAxis) { case cc.TiledMap.StaggerAxis.STAGGERAXIS_Y: var diffX = 0; var diffX1 = this._staggerIndex === cc.TiledMap.StaggerIndex.STAGGERINDEX_ODD ? 0 : tileWidth / 2; col % 2 === 1 && (diffX = tileWidth / 2 * odd_even); x = row * tileWidth + diffX + diffX1 + offset.x - centerWidth; y = (cols - col - 1) * (tileHeight - (tileHeight - this._hexSideLength) / 2) - offset.y - centerHeight; break; case cc.TiledMap.StaggerAxis.STAGGERAXIS_X: var diffY = 0; var diffY1 = this._staggerIndex === cc.TiledMap.StaggerIndex.STAGGERINDEX_ODD ? tileHeight / 2 : 0; row % 2 === 1 && (diffY = tileHeight / 2 * -odd_even); x = row * (tileWidth - (tileWidth - this._hexSideLength) / 2) + offset.x - centerWidth; y = (cols - col - 1) * tileHeight + diffY + diffY1 - offset.y - centerHeight; } return cc.v2(x, y); }, setTileGIDAt: function(gid, posOrX, flagsOrY, flags) { if (void 0 === posOrX) throw new Error("cc.TiledLayer.setTileGIDAt(): pos should be non-null"); var pos = void 0; if (void 0 === flags && posOrX instanceof cc.Vec2) { pos = posOrX; flags = flagsOrY; } else pos = cc.v2(posOrX, flagsOrY); pos.x = Math.floor(pos.x); pos.y = Math.floor(pos.y); if (this._isInvalidPosition(pos)) throw new Error("cc.TiledLayer.setTileGIDAt(): invalid position"); if (!this._tiles) { cc.logID(7238); return; } if (0 !== gid && gid < this._tileset.firstGid) { cc.logID(7239, gid); return; } flags = flags || 0; var currentFlags = this.getTileFlagsAt(pos); var currentGID = this.getTileGIDAt(pos); if (currentGID === gid && currentFlags === flags) return; var gidAndFlags = (gid | flags) >>> 0; this._updateTileForGID(gidAndFlags, pos); }, _updateTileForGID: function(gid, pos) { if (0 !== gid && !this._texGrids[gid]) return; var idx = 0 | pos.x + pos.y * this._layerSize.width; idx < this._tiles.length && (this._tiles[idx] = gid); }, getTileGIDAt: function(pos, y) { if (void 0 === pos) throw new Error("cc.TiledLayer.getTileGIDAt(): pos should be non-null"); var x = pos; if (void 0 === y) { x = pos.x; y = pos.y; } if (this._isInvalidPosition(x, y)) throw new Error("cc.TiledLayer.getTileGIDAt(): invalid position"); if (!this._tiles) { cc.logID(7237); return null; } var index = Math.floor(x) + Math.floor(y) * this._layerSize.width; var tile = this._tiles[index]; return (tile & cc.TiledMap.TileFlag.FLIPPED_MASK) >>> 0; }, getTileFlagsAt: function(pos, y) { if (!pos) throw new Error("TiledLayer.getTileFlagsAt: pos should be non-null"); void 0 !== y && (pos = cc.v2(pos, y)); if (this._isInvalidPosition(pos)) throw new Error("TiledLayer.getTileFlagsAt: invalid position"); if (!this._tiles) { cc.logID(7240); return null; } var idx = Math.floor(pos.x) + Math.floor(pos.y) * this._layerSize.width; var tile = this._tiles[idx]; return (tile & cc.TiledMap.TileFlag.FLIPPED_ALL) >>> 0; }, getTiledTileAt: function(x, y, forceCreate) { if (this._isInvalidPosition(x, y)) throw new Error("TiledLayer.getTiledTileAt: invalid position"); if (!this._tiles) { cc.logID(7236); return null; } var index = Math.floor(x) + Math.floor(y) * this._layerSize.width; var tile = this._tiledTiles[index]; if (!tile && forceCreate) { var node = new cc.Node(); tile = node.addComponent(cc.TiledTile); tile._x = x; tile._y = y; tile._layer = this; tile._updateInfo(); node.parent = this.node; return tile; } return tile; }, setTiledTileAt: function(x, y, tiledTile) { if (this._isInvalidPosition(x, y)) throw new Error("TiledLayer.setTiledTileAt: invalid position"); if (!this._tiles) { cc.logID(7236); return null; } var index = Math.floor(x) + Math.floor(y) * this._layerSize.width; return this._tiledTiles[index] = tiledTile; }, getTexture: function() { return this._texture; }, setTexture: function(texture) { this._texture = texture; this._activateMaterial(); }, getLayerSize: function() { return this._layerSize; }, getMapTileSize: function() { return this._mapTileSize; }, getTileSet: function() { return this._tileset; }, setTileSet: function(tileset) { this._tileset = tileset; }, getLayerOrientation: function() { return this._layerOrientation; }, getProperties: function() { return this._properties; }, _init: function(tileset, layerInfo, mapInfo) { var size = layerInfo._layerSize; this._layerName = layerInfo.name; this._tiles = layerInfo._tiles; this._properties = layerInfo.properties; this._layerSize = size; this._minGID = layerInfo._minGID; this._maxGID = layerInfo._maxGID; this._opacity = layerInfo._opacity; this._staggerAxis = mapInfo.getStaggerAxis(); this._staggerIndex = mapInfo.getStaggerIndex(); this._hexSideLength = mapInfo.getHexSideLength(); this._tileset = tileset; this._layerOrientation = mapInfo.orientation; this._mapTileSize = mapInfo.getTileSize(); var tilesets = mapInfo._tilesets; if (tilesets) { this._textures.length = tilesets.length; this._texGrids.length = 0; for (var i = 0, l = tilesets.length; i < l; ++i) { var tilesetInfo = tilesets[i]; var tex = tilesetInfo.sourceImage; this._textures[i] = tex; this._fillTextureGrids(tilesetInfo, i); tileset === tilesetInfo && (this._texture = tex); } } this._offset = this._calculateLayerOffset(layerInfo.offset); if (this._layerOrientation === cc.TiledMap.Orientation.HEX) { var width = 0, height = 0; if (this._staggerAxis === cc.TiledMap.StaggerAxis.STAGGERAXIS_X) { height = mapInfo._tileSize.height * (this._layerSize.height + .5); width = (mapInfo._tileSize.width + this._hexSideLength) * Math.floor(this._layerSize.width / 2) + mapInfo._tileSize.width * (this._layerSize.width % 2); } else { width = mapInfo._tileSize.width * (this._layerSize.width + .5); height = (mapInfo._tileSize.height + this._hexSideLength) * Math.floor(this._layerSize.height / 2) + mapInfo._tileSize.height * (this._layerSize.height % 2); } this.node.setContentSize(width, height); } else this.node.setContentSize(this._layerSize.width * this._mapTileSize.width, this._layerSize.height * this._mapTileSize.height); this._useAutomaticVertexZ = false; this._vertexZvalue = 0; this._activateMaterial(); }, _calculateLayerOffset: function(pos) { var ret = cc.v2(0, 0); switch (this._layerOrientation) { case cc.TiledMap.Orientation.ORTHO: ret = cc.v2(pos.x * this._mapTileSize.width, -pos.y * this._mapTileSize.height); break; case cc.TiledMap.Orientation.ISO: ret = cc.v2(this._mapTileSize.width / 2 * (pos.x - pos.y), this._mapTileSize.height / 2 * (-pos.x - pos.y)); break; case cc.TiledMap.Orientation.HEX: if (this._staggerAxis === cc.TiledMap.StaggerAxis.STAGGERAXIS_Y) { var diffX = this._staggerIndex === cc.TiledMap.StaggerIndex.STAGGERINDEX_EVEN ? this._mapTileSize.width / 2 : 0; ret = cc.v2(pos.x * this._mapTileSize.width + diffX, -pos.y * (this._mapTileSize.height - (this._mapTileSize.width - this._hexSideLength) / 2)); } else if (this._staggerAxis === cc.TiledMap.StaggerAxis.STAGGERAXIS_X) { var diffY = this._staggerIndex === cc.TiledMap.StaggerIndex.STAGGERINDEX_ODD ? this._mapTileSize.height / 2 : 0; ret = cc.v2(pos.x * (this._mapTileSize.width - (this._mapTileSize.width - this._hexSideLength) / 2), -pos.y * this._mapTileSize.height + diffY); } } return ret; }, _fillTextureGrids: function(tileset, texId) { var tex = this._textures[texId]; if (!tex) return; if (!tex.loaded) { tex.once("load", (function() { this._fillTextureGrids(tileset, texId); }), this); return; } if (!tileset.imageSize.width || !tileset.imageSize.height) { tileset.imageSize.width = tex.width; tileset.imageSize.height = tex.height; } var tw = tileset._tileSize.width, th = tileset._tileSize.height, imageW = tex.width, imageH = tex.height, spacing = tileset.spacing, margin = tileset.margin, cols = Math.floor((imageW - 2 * margin + spacing) / (tw + spacing)), rows = Math.floor((imageH - 2 * margin + spacing) / (th + spacing)), count = rows * cols, gid = tileset.firstGid, maxGid = tileset.firstGid + count, grids = this._texGrids, grid = null, override = !!grids[gid], texelCorrect = cc.macro.FIX_ARTIFACTS_BY_STRECHING_TEXEL_TMX ? .5 : 0; for (;gid < maxGid; ++gid) { override && !grids[gid] && (override = false); if (!override && grids[gid]) break; grid = { texId: texId, x: 0, y: 0, width: tw, height: th, t: 0, l: 0, r: 0, b: 0 }; tileset.rectForGID(gid, grid); grid.x += texelCorrect; grid.y += texelCorrect; grid.width -= 2 * texelCorrect; grid.height -= 2 * texelCorrect; grid.t = grid.y / imageH; grid.l = grid.x / imageW; grid.r = (grid.x + grid.width) / imageW; grid.b = (grid.y + grid.height) / imageH; grids[gid] = grid; } }, _activateMaterial: function() { var material = this._material; if (!material) { material = this._material = new SpriteMaterial(); material.useColor = false; } if (this._texture) { material.texture = this._texture; this.markForUpdateRenderData(true); this.markForRender(true); } else this.disableRender(); this._updateMaterial(material); } }); cc.TiledLayer = module.exports = TiledLayer; }), { "../core/components/CCRenderComponent": 78, "../core/renderer/render-engine": 203 } ], 272: [ (function(require, module, exports) { require("./CCTMXXMLParser"); require("./CCTiledMapAsset"); require("./CCTiledLayer"); require("./CCTiledTile"); require("./CCTiledObjectGroup"); var Orientation = cc.Enum({ ORTHO: 0, HEX: 1, ISO: 2 }); var Property = cc.Enum({ NONE: 0, MAP: 1, LAYER: 2, OBJECTGROUP: 3, OBJECT: 4, TILE: 5 }); var TileFlag = cc.Enum({ HORIZONTAL: 2147483648, VERTICAL: 1073741824, DIAGONAL: 536870912, FLIPPED_ALL: 3758096384, FLIPPED_MASK: 536870911 }); var StaggerAxis = cc.Enum({ STAGGERAXIS_X: 0, STAGGERAXIS_Y: 1 }); var StaggerIndex = cc.Enum({ STAGGERINDEX_ODD: 0, STAGGERINDEX_EVEN: 1 }); var TMXObjectType = cc.Enum({ RECT: 0, ELLIPSE: 1, POLYGON: 2, POLYLINE: 3, IMAGE: 4 }); var TiledMap = cc.Class({ name: "cc.TiledMap", extends: cc.Component, editor: false, ctor: function() { this._layers = []; this._groups = []; this._properties = []; this._tileProperties = []; this._mapSize = cc.size(0, 0); this._tileSize = cc.size(0, 0); }, statics: { Orientation: Orientation, Property: Property, TileFlag: TileFlag, StaggerAxis: StaggerAxis, StaggerIndex: StaggerIndex, TMXObjectType: TMXObjectType }, properties: { _tmxFile: { default: null, type: cc.TiledMapAsset }, tmxAsset: { get: function() { return this._tmxFile; }, set: function(value, force) { if (this._tmxFile !== value || false) { this._tmxFile = value; this._applyFile(); } }, type: cc.TiledMapAsset } }, getMapSize: function() { return this._mapSize; }, getTileSize: function() { return this._tileSize; }, getMapOrientation: function() { return this._mapOrientation; }, getObjectGroups: function() { return this._groups; }, getObjectGroup: function(groupName) { var groups = this._groups; for (var i = 0, l = groups.length; i < l; i++) { var group = groups[i]; if (group && group.getGroupName() === groupName) return group; } return null; }, getProperties: function() { return this._properties; }, getLayers: function() { return this._layers; }, getLayer: function(layerName) { var layers = this._layers; for (var i = 0, l = layers.length; i < l; i++) { var layer = layers[i]; if (layer && layer.getLayerName() === layerName) return layer; } return null; }, getProperty: function(propertyName) { return this._properties[propertyName.toString()]; }, getPropertiesForGID: function(GID) { return this._tileProperties[GID]; }, __preload: function() { this._tmxFile && this._applyFile(); }, onEnable: function() { this.node.on(cc.Node.EventType.ANCHOR_CHANGED, this._syncAnchorPoint, this); }, onDisable: function() { this.node.off(cc.Node.EventType.ANCHOR_CHANGED, this._syncAnchorPoint, this); }, _applyFile: function() { var file = this._tmxFile; if (file) { var texValues = file.textures; var texKeys = file.textureNames; var textures = {}; for (var i = 0; i < texValues.length; ++i) textures[texKeys[i]] = texValues[i]; var tsxFileNames = file.tsxFileNames; var tsxFiles = file.tsxFiles; var tsxMap = {}; for (var _i = 0; _i < tsxFileNames.length; ++_i) tsxFileNames[_i].length > 0 && (tsxMap[tsxFileNames[_i]] = tsxFiles[_i].text); var mapInfo = new cc.TMXMapInfo(file.tmxXmlStr, tsxMap, textures); var tilesets = mapInfo.getTilesets(); tilesets && 0 !== tilesets.length || cc.logID(7241); this._buildWithMapInfo(mapInfo); } else this._relseasMapInfo(); }, _relseasMapInfo: function() { var layers = this._layers; for (var i = 0, l = layers.length; i < l; i++) layers[i].node.removeFromParent(); layers.length = 0; var groups = this._groups; for (var _i2 = 0, _l = groups.length; _i2 < _l; _i2++) groups[_i2].node.removeFromParent(); groups.length = 0; }, _syncAnchorPoint: function() { var anchor = this.node.getAnchorPoint(); for (var i = 0, l = this._layers.length; i < l; i++) this._layers[i].node.setAnchorPoint(anchor); }, _buildWithMapInfo: function(mapInfo) { this._mapSize = mapInfo.getMapSize(); this._tileSize = mapInfo.getTileSize(); this._mapOrientation = mapInfo.orientation; this._properties = mapInfo.properties; this._tileProperties = mapInfo.getTileProperties(); this._relseasMapInfo(); var layers = this._layers; var groups = this._groups; var node = this.node; var layerInfos = mapInfo.getAllChildren(); if (layerInfos && layerInfos.length > 0) for (var i = 0, len = layerInfos.length; i < len; i++) { var layerInfo = layerInfos[i]; var name = layerInfo.name; var child = this.node.getChildByName(name); if (!child) { child = new cc.Node(); child.name = name; node.addChild(child); } if (layerInfo instanceof cc.TMXLayerInfo && layerInfo.visible) { var layer = child.getComponent(cc.TiledLayer); layer || (layer = child.addComponent(cc.TiledLayer)); var tileset = this._tilesetForLayer(layerInfo, mapInfo); layer._init(tileset, layerInfo, mapInfo); layerInfo.ownTiles = false; this.node.width = Math.max(this.node.width, child.width); this.node.height = Math.max(this.node.height, child.height); layers.push(layer); } else if (layerInfo instanceof cc.TMXObjectGroupInfo) { var group = child.getComponent(cc.TiledObjectGroup); group || (group = child.addComponent(cc.TiledObjectGroup)); group._init(layerInfo, mapInfo); groups.push(group); } } this._syncAnchorPoint(); }, _tilesetForLayer: function(layerInfo, mapInfo) { var size = layerInfo._layerSize; var tilesets = mapInfo.getTilesets(); if (tilesets) for (var i = tilesets.length - 1; i >= 0; i--) { var tileset = tilesets[i]; if (tileset) for (var y = 0; y < size.height; y++) for (var x = 0; x < size.width; x++) { var pos = x + size.width * y; var gid = layerInfo._tiles[pos]; if (0 !== gid && (gid & cc.TiledMap.TileFlag.FLIPPED_MASK) >>> 0 >= tileset.firstGid) return tileset; } } cc.logID(7215, layerInfo.name); return null; } }); cc.TiledMap = module.exports = TiledMap; cc.js.obsolete(cc.TiledMap.prototype, "cc.TiledMap.tmxFile", "tmxAsset", true); cc.js.get(cc.TiledMap.prototype, "mapLoaded", (function() { cc.errorID(7203); return []; }), false); }), { "./CCTMXXMLParser": 270, "./CCTiledLayer": 271, "./CCTiledMapAsset": 273, "./CCTiledObjectGroup": 274, "./CCTiledTile": 275 } ], 273: [ (function(require, module, exports) { var TiledMapAsset = cc.Class({ name: "cc.TiledMapAsset", extends: cc.Asset, properties: { tmxXmlStr: "", textures: { default: [], type: [ cc.Texture2D ] }, textureNames: [ cc.String ], tsxFiles: [ cc.TextAsset ], tsxFileNames: [ cc.String ] }, statics: { preventDeferredLoadDependents: true }, createNode: false }); cc.TiledMapAsset = TiledMapAsset; module.exports = TiledMapAsset; }), {} ], 274: [ (function(require, module, exports) { var TiledObjectGroup = cc.Class({ name: "cc.TiledObjectGroup", extends: cc.Component, getPositionOffset: function() { return this._positionOffset; }, getProperties: function() { this._properties; }, getGroupName: function() { return this._groupName; }, getProperty: function(propertyName) { return this._properties[propertyName.toString()]; }, getObject: function(objectName) { for (var i = 0, len = this._objects.length; i < len; i++) { var obj = this._objects[i]; if (obj && obj.name === objectName) return obj; } return null; }, getObjects: function() { return this._objects; }, _init: function(groupInfo, mapInfo) { this._groupName = groupInfo.name; this._positionOffset = groupInfo.offset; this._mapInfo = mapInfo; this._properties = groupInfo.getProperties(); var mapSize = mapInfo._mapSize; var tileSize = mapInfo._tileSize; var width = 0, height = 0; if (mapInfo.orientation === cc.TiledMap.Orientation.HEX) if (mapInfo.getStaggerAxis() === cc.TiledMap.StaggerAxis.STAGGERAXIS_X) { height = tileSize.height * (mapSize.height + .5); width = (tileSize.width + mapInfo.getHexSideLength()) * Math.floor(mapSize.width / 2) + tileSize.width * (mapSize.width % 2); } else { width = tileSize.width * (mapSize.width + .5); height = (tileSize.height + mapInfo.getHexSideLength()) * Math.floor(mapSize.height / 2) + tileSize.height * (mapSize.height % 2); } else { width = mapSize.width * tileSize.width; height = mapSize.height * tileSize.height; } this.node.setContentSize(width, height); var objects = groupInfo._objects; for (var i = 0, l = objects.length; i < l; i++) { var object = objects[i]; object.offset = cc.v2(object.x, object.y); if (cc.TiledMap.Orientation.ISO !== this._mapOrientation) object.y = height - object.y; else { var posIdxX = object.offset.x / tileSize.width * 2; var posIdxY = object.offset.y / tileSize.height; object.x = tileSize.width / 2 * (mapSize.width + posIdxX - posIdxY); object.y = tileSize.height / 2 * (2 * mapSize.height - posIdxX - posIdxY); } } this._objects = objects; } }); cc.TiledObjectGroup = module.exports = TiledObjectGroup; }), {} ], 275: [ (function(require, module, exports) { var TiledTile = cc.Class({ name: "cc.TiledTile", extends: cc.Component, editor: false, ctor: function() { this._layer = null; }, properties: { _x: 0, _y: 0, x: { get: function() { return this._x; }, set: function(value) { if (value === this._x) return; if (this._layer && this._layer._isInvalidPosition(value, this._y)) { cc.warn("Invalid x, the valid value is between [%s] ~ [%s]", 0, this._layer._layerSize.width); return; } this._resetTile(); this._x = value; this._updateInfo(); }, type: cc.Integer }, y: { get: function() { return this._y; }, set: function(value) { if (value === this._y) return; if (this._layer && this._layer._isInvalidPosition(this._x, value)) { cc.warn("Invalid y, the valid value is between [%s] ~ [%s]", 0, this._layer._layerSize.height); return; } this._resetTile(); this._y = value; this._updateInfo(); }, type: cc.Integer }, gid: { get: function() { if (this._layer) return this._layer.getTileGIDAt(this._x, this._y); return 0; }, set: function(value) { this._layer && this._layer.setTileGIDAt(value, this._x, this._y); }, type: cc.Integer } }, onEnable: function() { var parent = this.node.parent; this._layer = parent.getComponent(cc.TiledLayer); this._resetTile(); this._updateInfo(); }, onDisable: function() { this._resetTile(); }, _resetTile: function() { this._layer && this._layer.getTiledTileAt(this._x, this._y) === this && this._layer.setTiledTileAt(this._x, this._y, null); }, _updateInfo: function() { if (!this._layer) return; var x = this._x, y = this._y; if (this._layer.getTiledTileAt(x, y)) { cc.warn("There is already a TiledTile at [%s, %s]", x, y); return; } this.node.setPosition(this._layer.getPositionAt(x, y)); this._layer.setTiledTileAt(x, y, this); } }); cc.TiledTile = module.exports = TiledTile; }), {} ], 276: [ (function(require, module, exports) { require("./CCTiledMap"); require("./tmx-layer-assembler"); }), { "./CCTiledMap": 272, "./tmx-layer-assembler": 277 } ], 277: [ (function(require, module, exports) { var TiledLayer = require("./CCTiledLayer"); var TiledMap = require("./CCTiledMap"); var renderEngine = require("../core/renderer/render-engine"); var RenderFlow = require("../core/renderer/render-flow"); var Orientation = TiledMap.Orientation; var TileFlag = TiledMap.TileFlag; var FLIPPED_MASK = TileFlag.FLIPPED_MASK; var StaggerAxis = TiledMap.StaggerAxis; var StaggerIndex = TiledMap.StaggerIndex; var math = renderEngine.math; var mat4 = math.mat4; var vec3 = math.vec3; var _mat4_temp = mat4.create(); var _mat4_temp2 = mat4.create(); var _vec3_temp = vec3.create(); var tmxAssembler = { updateRenderData: function(comp) { var renderData = comp._renderData; renderData || (renderData = comp._renderData = comp.requestRenderData()); var size = comp.node._contentSize; var anchor = comp.node._anchorPoint; renderData.updateSizeNPivot(size.width, size.height, anchor.x, anchor.y); renderData.material = comp.getMaterial(); this.updateVertices(comp); }, fillBuffers: function(comp, renderer) { var renderData = comp._renderData; var data = renderData._data; var buffer = renderer._meshBuffer, vertexCount = renderData.vertexCount; var offsetInfo = buffer.request(vertexCount, renderData.indiceCount); var indiceOffset = offsetInfo.indiceOffset, vertexOffset = offsetInfo.byteOffset >> 2, vertexId = offsetInfo.vertexOffset, vbuf = buffer._vData, ibuf = buffer._iData, uintbuf = buffer._uintVData; for (var i = 0, l = renderData.vertexCount; i < l; i++) { var vert = data[i]; vbuf[vertexOffset++] = vert.x; vbuf[vertexOffset++] = vert.y; vbuf[vertexOffset++] = vert.u; vbuf[vertexOffset++] = vert.v; uintbuf[vertexOffset++] = vert.color; } for (var _i = 0, _l = renderData.indiceCount; _i < _l; _i += 6) { ibuf[indiceOffset++] = vertexId; ibuf[indiceOffset++] = vertexId + 1; ibuf[indiceOffset++] = vertexId + 2; ibuf[indiceOffset++] = vertexId + 1; ibuf[indiceOffset++] = vertexId + 3; ibuf[indiceOffset++] = vertexId + 2; vertexId += 4; } comp.node._renderFlag |= RenderFlow.FLAG_UPDATE_RENDER_DATA; }, updateVertices: function(comp) { var node = comp.node; var renderData = comp._renderData; var data = renderData._data; var color = node._color._val; var opacity = node._color.a; renderData.dataLength = renderData.vertexCount = renderData.indiceCount = 0; var layerOrientation = comp._layerOrientation, tiles = comp._tiles; if (!tiles || !comp._tileset) return; var appx = node._anchorPoint.x * node._contentSize.width, appy = node._anchorPoint.y * node._contentSize.height; mat4.copy(_mat4_temp, node._worldMatrix); vec3.set(_vec3_temp, -appx, -appy, 0); mat4.translate(_mat4_temp, _mat4_temp, _vec3_temp); var a = _mat4_temp.m00, b = _mat4_temp.m01, c = _mat4_temp.m04, d = _mat4_temp.m05, tx = _mat4_temp.m12, ty = _mat4_temp.m13; var maptw = comp._mapTileSize.width, mapth = comp._mapTileSize.height, tilew = comp._tileset._tileSize.width, tileh = comp._tileset._tileSize.height, extw = tilew - maptw, exth = tileh - mapth, winw = cc.winSize.width, winh = cc.winSize.height, rows = comp._layerSize.height, cols = comp._layerSize.width, grids = comp._texGrids, tiledTiles = comp._tiledTiles, ox = comp._offset.x, oy = comp._offset.y, w = tilew * a, h = tileh * d; tx += ox * a + oy * c; ty += ox * b + oy * d; var startCol = 0, startRow = 0, maxCol = cols, maxRow = rows; var cullingA = a, cullingD = d, cullingMapx = tx, cullingMapy = ty, cullingW = w, cullingH = h; var enabledCulling = cc.macro.ENABLE_TILEDMAP_CULLING; if (enabledCulling) { var camera = cc.Camera.findCamera(comp.node); if (camera) { camera.getWorldToCameraMatrix(_mat4_temp2); mat4.mul(_mat4_temp, _mat4_temp2, _mat4_temp); cullingA = _mat4_temp.m00; cullingD = _mat4_temp.m05; cullingMapx = ox * cullingA + oy * _mat4_temp.m04 + _mat4_temp.m12; cullingMapy = ox * _mat4_temp.m01 + oy * cullingD + _mat4_temp.m13; cullingW = tilew * cullingA; cullingH = tileh * cullingD; } if (layerOrientation === Orientation.ORTHO) { mat4.invert(_mat4_temp, _mat4_temp); var rect = cc.visibleRect; var _a = _mat4_temp.m00, _b = _mat4_temp.m01, _c = _mat4_temp.m04, _d = _mat4_temp.m05, _tx = _mat4_temp.m12, _ty = _mat4_temp.m13; var v0x = rect.topLeft.x * _a + rect.topLeft.y * _c + _tx; var v0y = rect.topLeft.x * _b + rect.topLeft.y * _d + _ty; var v1x = rect.bottomLeft.x * _a + rect.bottomLeft.y * _c + _tx; var v1y = rect.bottomLeft.x * _b + rect.bottomLeft.y * _d + _ty; var v2x = rect.topRight.x * _a + rect.topRight.y * _c + _tx; var v2y = rect.topRight.x * _b + rect.topRight.y * _d + _ty; var v3x = rect.bottomRight.x * _a + rect.bottomRight.y * _c + _tx; var v3y = rect.bottomRight.x * _b + rect.bottomRight.y * _d + _ty; var minx = Math.min(v0x, v1x, v2x, v3x), maxx = Math.max(v0x, v1x, v2x, v3x), miny = Math.min(v0y, v1y, v2y, v3y), maxy = Math.max(v0y, v1y, v2y, v3y); startCol = Math.floor(minx / maptw); startRow = rows - Math.ceil(maxy / mapth); maxCol = Math.ceil((maxx + extw) / maptw); maxRow = rows - Math.floor((miny - exth) / mapth); startCol < 0 && (startCol = 0); startRow < 0 && (startRow = 0); maxCol > cols && (maxCol = cols); maxRow > rows && (maxRow = rows); } } var colOffset = startRow * cols, gid = void 0, grid = void 0, top = void 0, left = void 0, bottom = void 0, right = void 0, gt = void 0, gl = void 0, gb = void 0, gr = void 0, axis = void 0, tileOffset = void 0, diffX1 = void 0, diffY1 = void 0, odd_even = void 0; if (layerOrientation === Orientation.HEX) { var hexSideLength = comp._hexSideLength; axis = comp._staggerAxis; tileOffset = comp._tileset.tileOffset; odd_even = comp._staggerIndex === StaggerIndex.STAGGERINDEX_ODD ? 1 : -1; diffX1 = axis === StaggerAxis.STAGGERAXIS_X ? (maptw - hexSideLength) / 2 : 0; diffY1 = axis === StaggerAxis.STAGGERAXIS_Y ? (mapth - hexSideLength) / 2 : 0; } var dataOffset = 0; var a2 = void 0, b2 = void 0, c2 = void 0, d2 = void 0, tx2 = void 0, ty2 = void 0, color2 = void 0; for (var row = startRow; row < maxRow; ++row) { for (var col = startCol; col < maxCol; ++col) { var index = colOffset + col; var flippedX = false, flippedY = false; var tiledTile = tiledTiles[index]; gid = tiledTile ? tiledTile.gid : comp._tiles[index]; grid = grids[(gid & FLIPPED_MASK) >>> 0]; if (!grid) continue; switch (layerOrientation) { case Orientation.ORTHO: left = col * maptw; bottom = (rows - row - 1) * mapth; break; case Orientation.ISO: left = maptw / 2 * (cols + col - row - 1); bottom = mapth / 2 * (2 * rows - col - row - 2); break; case Orientation.HEX: var diffX2 = axis === StaggerAxis.STAGGERAXIS_Y && row % 2 === 1 ? maptw / 2 * odd_even : 0; left = col * (maptw - diffX1) + diffX2 + tileOffset.x; var diffY2 = axis === StaggerAxis.STAGGERAXIS_X && col % 2 === 1 ? mapth / 2 * -odd_even : 0; bottom = (rows - row - 1) * (mapth - diffY1) + diffY2 - tileOffset.y; } if (tiledTile) { var tiledNode = tiledTile.node; color2 = color; var newOpacity = tiledNode.opacity * opacity / 255; color = tiledNode.color.setA(newOpacity)._val; a2 = a; b2 = b; c2 = c; d2 = d; tx2 = tx; ty2 = ty; tiledNode._updateLocalMatrix(); mat4.copy(_mat4_temp, tiledNode._matrix); vec3.set(_vec3_temp, -left, -bottom, 0); mat4.translate(_mat4_temp, _mat4_temp, _vec3_temp); mat4.multiply(_mat4_temp, node._worldMatrix, _mat4_temp); a = _mat4_temp.m00; b = _mat4_temp.m01; c = _mat4_temp.m04; d = _mat4_temp.m05; tx = _mat4_temp.m12; ty = _mat4_temp.m13; } right = left + tilew; top = bottom + tileh; if (enabledCulling && layerOrientation === Orientation.ISO) { gb = cullingMapy + bottom * cullingD; if (gb > winh + cullingH) { col += Math.floor(2 * (gb - winh) / cullingH) - 1; continue; } gr = cullingMapx + right * cullingA; if (gr < -cullingW) { col += Math.floor(2 * -gr / cullingW) - 1; continue; } gl = cullingMapx + left * cullingA; gt = cullingMapy + top * cullingD; if (gl > winw || gt < 0) { col = maxCol; continue; } } if (gid > TileFlag.DIAGONAL) { flippedX = (gid & TileFlag.HORIZONTAL) >>> 0; flippedY = (gid & TileFlag.VERTICAL) >>> 0; } renderData.vertexCount += 4; renderData.indiceCount += 6; renderData.dataLength = renderData.vertexCount; data[dataOffset].x = left * a + top * c + tx; data[dataOffset].y = left * b + top * d + ty; data[dataOffset].u = flippedX ? grid.r : grid.l; data[dataOffset].v = flippedY ? grid.b : grid.t; data[dataOffset].color = color; dataOffset++; data[dataOffset].x = left * a + bottom * c + tx; data[dataOffset].y = left * b + bottom * d + ty; data[dataOffset].u = flippedX ? grid.r : grid.l; data[dataOffset].v = flippedY ? grid.t : grid.b; data[dataOffset].color = color; dataOffset++; data[dataOffset].x = right * a + top * c + tx; data[dataOffset].y = right * b + top * d + ty; data[dataOffset].u = flippedX ? grid.l : grid.r; data[dataOffset].v = flippedY ? grid.b : grid.t; data[dataOffset].color = color; dataOffset++; data[dataOffset].x = right * a + bottom * c + tx; data[dataOffset].y = right * b + bottom * d + ty; data[dataOffset].u = flippedX ? grid.l : grid.r; data[dataOffset].v = flippedY ? grid.t : grid.b; data[dataOffset].color = color; dataOffset++; if (tiledTile) { color = color2; a = a2; b = b2; c = c2; d = d2; tx = tx2; ty = ty2; } } colOffset += cols; } } }; module.exports = TiledLayer._assembler = tmxAssembler; }), { "../core/renderer/render-engine": 203, "../core/renderer/render-flow": 204, "./CCTiledLayer": 271, "./CCTiledMap": 272 } ], 278: [ (function(require, module, exports) { var VideoPlayerImpl = require("./video-player-impl"); var EventType = VideoPlayerImpl.EventType; var ResourceType = cc.Enum({ REMOTE: 0, LOCAL: 1 }); var VideoPlayer = cc.Class({ name: "cc.VideoPlayer", extends: cc.Component, editor: false, properties: { _resourceType: ResourceType.REMOTE, resourceType: { tooltip: false, type: ResourceType, set: function(value) { this._resourceType = value; this._updateVideoSource(); }, get: function() { return this._resourceType; } }, _remoteURL: "", remoteURL: { tooltip: false, type: cc.String, set: function(url) { this._remoteURL = url; this._updateVideoSource(); }, get: function() { return this._remoteURL; } }, _clip: { default: null, type: cc.Asset }, clip: { tooltip: false, get: function() { return this._clip; }, set: function(value) { this._clip = value; this._updateVideoSource(); }, type: cc.Asset }, currentTime: { tooltip: false, type: cc.Float, set: function(time) { this._impl && this._impl.seekTo(time); }, get: function() { if (this._impl) return this._impl.currentTime(); return -1; } }, _volume: 1, volume: { get: function() { return this._volume; }, set: function(value) { this._volume = value; this.isPlaying() && !this._mute && this._syncVolume(); }, range: [ 0, 1 ], type: cc.Float, tooltip: false }, _mute: false, mute: { get: function() { return this._mute; }, set: function(value) { this._mute = value; this._syncVolume(); }, tooltip: false }, keepAspectRatio: { tooltip: false, default: true, type: cc.Boolean, notify: function() { this._impl.setKeepAspectRatioEnabled(this.keepAspectRatio); } }, isFullscreen: { tooltip: false, default: false, type: cc.Boolean, notify: function() { this._impl.setFullScreenEnabled(this.isFullscreen); } }, videoPlayerEvent: { default: [], type: cc.Component.EventHandler } }, statics: { EventType: EventType, ResourceType: ResourceType, Impl: VideoPlayerImpl }, ctor: function() { this._impl = new VideoPlayerImpl(); }, _syncVolume: function() { var impl = this._impl; if (impl) { var volume = this._mute ? 0 : this._volume; impl.setVolume(volume); } }, _updateVideoSource: function() { var url = ""; this.resourceType === ResourceType.REMOTE ? url = this.remoteURL : this._clip && (url = this._clip.nativeUrl || ""); url && cc.loader.md5Pipe && (url = cc.loader.md5Pipe.transformURL(url)); this._impl.setURL(url); }, onLoad: function() { var impl = this._impl; if (impl) { impl.createDomElementIfNeeded(); this._updateVideoSource(); impl.seekTo(this.currentTime); impl.setKeepAspectRatioEnabled(this.keepAspectRatio); impl.setFullScreenEnabled(this.isFullscreen); this.pause(); true; impl.setEventListener(EventType.PLAYING, this.onPlaying.bind(this)); impl.setEventListener(EventType.PAUSED, this.onPasued.bind(this)); impl.setEventListener(EventType.STOPPED, this.onStopped.bind(this)); impl.setEventListener(EventType.COMPLETED, this.onCompleted.bind(this)); impl.setEventListener(EventType.META_LOADED, this.onMetaLoaded.bind(this)); impl.setEventListener(EventType.CLICKED, this.onClicked.bind(this)); impl.setEventListener(EventType.READY_TO_PLAY, this.onReadyToPlay.bind(this)); } }, onRestore: function() { this._impl || (this._impl = new VideoPlayerImpl()); }, onEnable: function() { this._impl && this._impl.enable(); }, onDisable: function() { this._impl && this._impl.disable(); }, onDestroy: function() { if (this._impl) { this._impl.destroy(); this._impl = null; } }, update: function(dt) { this._impl && this._impl.updateMatrix(this.node); }, onReadyToPlay: function() { cc.Component.EventHandler.emitEvents(this.videoPlayerEvent, this, EventType.READY_TO_PLAY); this.node.emit("ready-to-play", this); }, onMetaLoaded: function() { cc.Component.EventHandler.emitEvents(this.videoPlayerEvent, this, EventType.META_LOADED); this.node.emit("meta-loaded", this); }, onClicked: function() { cc.Component.EventHandler.emitEvents(this.videoPlayerEvent, this, EventType.CLICKED); this.node.emit("clicked", this); }, onPlaying: function() { cc.Component.EventHandler.emitEvents(this.videoPlayerEvent, this, EventType.PLAYING); this.node.emit("playing", this); }, onPasued: function() { cc.Component.EventHandler.emitEvents(this.videoPlayerEvent, this, EventType.PAUSED); this.node.emit("paused", this); }, onStopped: function() { cc.Component.EventHandler.emitEvents(this.videoPlayerEvent, this, EventType.STOPPED); this.node.emit("stopped", this); }, onCompleted: function() { cc.Component.EventHandler.emitEvents(this.videoPlayerEvent, this, EventType.COMPLETED); this.node.emit("completed", this); }, play: function() { if (this._impl) { this._syncVolume(); this._impl.play(); } }, resume: function() { if (this._impl) { this._syncVolume(); this._impl.resume(); } }, pause: function() { this._impl && this._impl.pause(); }, stop: function() { this._impl && this._impl.stop(); }, getDuration: function() { if (this._impl) return this._impl.duration(); return -1; }, isPlaying: function() { if (this._impl) return this._impl.isPlaying(); return false; } }); cc.VideoPlayer = module.exports = VideoPlayer; }), { "./video-player-impl": 279 } ], 279: [ (function(require, module, exports) { var utils = require("../core/platform/utils"); var sys = require("../core/platform/CCSys"); var renderEngine = require("../core/renderer/render-engine"); var math = renderEngine.math; var READY_STATE = { HAVE_NOTHING: 0, HAVE_METADATA: 1, HAVE_CURRENT_DATA: 2, HAVE_FUTURE_DATA: 3, HAVE_ENOUGH_DATA: 4 }; var _mat4_temp = math.mat4.create(); var VideoPlayerImpl = cc.Class({ name: "VideoPlayerImpl", ctor: function() { this._EventList = {}; this._video = null; this._url = ""; this._fullScreenEnabled = false; this._loadedmeta = false; this._loaded = false; this._visible = false; this._playing = false; this._ignorePause = false; this._forceUpdate = true; this._m00 = 0; this._m01 = 0; this._m04 = 0; this._m05 = 0; this._m12 = 0; this._m13 = 0; this._w = 0; this._h = 0; this.__eventListeners = {}; }, _bindEvent: function() { var video = this._video, self = this; var cbs = this.__eventListeners; cbs.loadedmetadata = function() { self._loadedmeta = true; self._fullScreenEnabled ? cc.screen.requestFullScreen(video) : cc.screen.fullScreen() && cc.screen.exitFullScreen(video); self._dispatchEvent(VideoPlayerImpl.EventType.META_LOADED); }; cbs.ended = function() { if (self._video !== video) return; self._playing = false; self._dispatchEvent(VideoPlayerImpl.EventType.COMPLETED); }; cbs.play = function() { if (self._video !== video) return; self._playing = true; self._updateVisibility(); self._dispatchEvent(VideoPlayerImpl.EventType.PLAYING); }; cbs.pause = function() { if (self._video !== video) return; self._playing = false; if (self._ignorePause) return; self._dispatchEvent(VideoPlayerImpl.EventType.PAUSED); }; cbs.click = function() { self._dispatchEvent(VideoPlayerImpl.EventType.CLICKED); }; video.addEventListener("loadedmetadata", cbs.loadedmetadata); video.addEventListener("ended", cbs.ended); video.addEventListener("play", cbs.play); video.addEventListener("pause", cbs.pause); video.addEventListener("click", cbs.click); function onCanPlay() { if (self._loaded || self._loadedmeta || self._playing) return; var video = self._video; if (video.readyState === READY_STATE.HAVE_ENOUGH_DATA) { video.currentTime = 0; self._loaded = true; self._dispatchEvent(VideoPlayerImpl.EventType.READY_TO_PLAY); self._updateVisibility(); } } cbs.onCanPlay = onCanPlay; video.addEventListener("canplay", cbs.onCanPlay); video.addEventListener("canplaythrough", cbs.onCanPlay); video.addEventListener("suspend", cbs.onCanPlay); }, _updateVisibility: function() { var video = this._video; if (!video) return; if (this._visible) { video.style.visibility = "visible"; this._forceUpdate = true; } else { video.style.visibility = "hidden"; video.pause(); this._playing = false; this._forceUpdate = false; } }, _updateSize: function(width, height) { var video = this._video; if (!video) return; video.style.width = width + "px"; video.style.height = height + "px"; }, _createDom: function() { var video = document.createElement("video"); video.style.position = "absolute"; video.style.bottom = "0px"; video.style.left = "0px"; video.className = "cocosVideo"; video.setAttribute("preload", "auto"); video.setAttribute("webkit-playsinline", ""); video.setAttribute("x5-playsinline", ""); video.setAttribute("playsinline", ""); this._video = video; cc.game.container.appendChild(video); }, createDomElementIfNeeded: function() { this._video || this._createDom(); }, removeDom: function() { var video = this._video; if (video) { var hasChild = utils.contains(cc.game.container, video); hasChild && cc.game.container.removeChild(video); var cbs = this.__eventListeners; video.removeEventListener("loadedmetadata", cbs.loadedmetadata); video.removeEventListener("ended", cbs.ended); video.removeEventListener("play", cbs.play); video.removeEventListener("pause", cbs.pause); video.removeEventListener("click", cbs.click); video.removeEventListener("canplay", cbs.onCanPlay); video.removeEventListener("canplaythrough", cbs.onCanPlay); video.removeEventListener("suspend", cbs.onCanPlay); cbs.loadedmetadata = null; cbs.ended = null; cbs.play = null; cbs.pause = null; cbs.click = null; cbs.onCanPlay = null; } this._video = null; this._url = ""; }, setURL: function(path) { var source = void 0, extname = void 0; if (this._url === path) return; this._url = path; this.removeDom(); this.createDomElementIfNeeded(); this._bindEvent(); var video = this._video; video.style["visibility"] = "hidden"; this._loaded = false; this._playing = false; this._loadedmeta = false; source = document.createElement("source"); source.src = path; video.appendChild(source); extname = cc.path.extname(path); var polyfill = VideoPlayerImpl._polyfill; for (var i = 0; i < polyfill.canPlayType.length; i++) if (extname !== polyfill.canPlayType[i]) { source = document.createElement("source"); source.src = path.replace(extname, polyfill.canPlayType[i]); video.appendChild(source); } }, getURL: function() { return this._url; }, play: function() { var video = this._video; if (!video || !this._visible || this._playing) return; if (VideoPlayerImpl._polyfill.autoplayAfterOperation) { var self = this; setTimeout((function() { video.play(); }), 20); } else video.play(); }, pause: function() { var video = this._video; if (!this._playing || !video) return; video.pause(); }, resume: function() { this.play(); }, stop: function() { var video = this._video; if (!video || !this._visible) return; this._ignorePause = true; video.currentTime = 0; video.pause(); setTimeout(function() { this._dispatchEvent(VideoPlayerImpl.EventType.STOPPED); this._ignorePause = false; }.bind(this), 0); }, setVolume: function(volume) { var video = this._video; video && (video.volume = volume); }, seekTo: function(time) { var video = this._video; if (!video) return; this._loaded ? video.currentTime = time : (function() { var cb = function() { video.currentTime = time; video.removeEventListener(VideoPlayerImpl._polyfill.event, cb); }; video.addEventListener(VideoPlayerImpl._polyfill.event, cb); })(); VideoPlayerImpl._polyfill.autoplayAfterOperation && this.isPlaying() && setTimeout((function() { video.play(); }), 20); }, isPlaying: function() { var video = this._video; VideoPlayerImpl._polyfill.autoplayAfterOperation && this._playing && setTimeout((function() { video.play(); }), 20); return this._playing; }, duration: function() { var video = this._video; var duration = -1; if (!video) return duration; duration = video.duration; duration <= 0 && cc.logID(7702); return duration; }, currentTime: function() { var video = this._video; if (!video) return -1; return video.currentTime; }, setKeepAspectRatioEnabled: function() { false; cc.logID(7700); }, isKeepAspectRatioEnabled: function() { return true; }, setFullScreenEnabled: function(enable) { var video = this._video; if (!video) return; this._fullScreenEnabled = enable; enable ? cc.screen.requestFullScreen(video) : cc.screen.fullScreen() && cc.screen.exitFullScreen(video); }, isFullScreenEnabled: function() { return this._fullScreenEnabled; }, setEventListener: function(event, callback) { this._EventList[event] = callback; }, removeEventListener: function(event) { this._EventList[event] = null; }, _dispatchEvent: function(event) { var callback = this._EventList[event]; callback && callback.call(this, this, this._video.src); }, onPlayEvent: function() { var callback = this._EventList[VideoPlayerImpl.EventType.PLAYING]; callback.call(this, this, this._video.src); }, enable: function() { var list = VideoPlayerImpl.elements; -1 === list.indexOf(this) && list.push(this); this.setVisible(true); }, disable: function() { var list = VideoPlayerImpl.elements; var index = list.indexOf(this); -1 !== index && list.splice(index, 1); this.setVisible(false); }, destroy: function() { this.disable(); this.removeDom(); }, setVisible: function(visible) { if (this._visible !== visible) { this._visible = !!visible; this._updateVisibility(); } }, updateMatrix: function(node) { if (!this._video || !this._visible) return; node.getWorldMatrix(_mat4_temp); if (!this._forceUpdate && this._m00 === _mat4_temp.m00 && this._m01 === _mat4_temp.m01 && this._m04 === _mat4_temp.m04 && this._m05 === _mat4_temp.m05 && this._m12 === _mat4_temp.m12 && this._m13 === _mat4_temp.m13 && this._w === node._contentSize.width && this._h === node._contentSize.height) return; this._m00 = _mat4_temp.m00; this._m01 = _mat4_temp.m01; this._m04 = _mat4_temp.m04; this._m05 = _mat4_temp.m05; this._m12 = _mat4_temp.m12; this._m13 = _mat4_temp.m13; this._w = node._contentSize.width; this._h = node._contentSize.height; var scaleX = cc.view._scaleX, scaleY = cc.view._scaleY; var dpr = cc.view._devicePixelRatio; scaleX /= dpr; scaleY /= dpr; var container = cc.game.container; var a = _mat4_temp.m00 * scaleX, b = _mat4_temp.m01, c = _mat4_temp.m04, d = _mat4_temp.m05 * scaleY; var offsetX = container && container.style.paddingLeft ? parseInt(container.style.paddingLeft) : 0; var offsetY = container && container.style.paddingBottom ? parseInt(container.style.paddingBottom) : 0; var w = void 0, h = void 0; if (VideoPlayerImpl._polyfill.zoomInvalid) { this._updateSize(this._w * a, this._h * d); a = 1; d = 1; w = this._w * scaleX; h = this._h * scaleY; } else { w = this._w * scaleX; h = this._h * scaleY; this._updateSize(this._w, this._h); } var appx = w * _mat4_temp.m00 * node._anchorPoint.x; var appy = h * _mat4_temp.m05 * node._anchorPoint.y; var viewport = cc.view._viewportRect; offsetX += viewport.x / dpr; offsetY += viewport.y / dpr; var tx = _mat4_temp.m12 * scaleX - appx + offsetX, ty = _mat4_temp.m13 * scaleY - appy + offsetY; var matrix = "matrix(" + a + "," + -b + "," + -c + "," + d + "," + tx + "," + -ty + ")"; this._video.style["transform"] = matrix; this._video.style["-webkit-transform"] = matrix; this._video.style["transform-origin"] = "0px 100% 0px"; this._video.style["-webkit-transform-origin"] = "0px 100% 0px"; } }); VideoPlayerImpl.EventType = { PLAYING: 0, PAUSED: 1, STOPPED: 2, COMPLETED: 3, META_LOADED: 4, CLICKED: 5, READY_TO_PLAY: 6 }; VideoPlayerImpl.elements = []; VideoPlayerImpl.pauseElements = []; cc.game.on(cc.game.EVENT_HIDE, (function() { var list = VideoPlayerImpl.elements; for (var element, i = 0; i < list.length; i++) { element = list[i]; if (element.isPlaying()) { element.pause(); VideoPlayerImpl.pauseElements.push(element); } } })); cc.game.on(cc.game.EVENT_SHOW, (function() { var list = VideoPlayerImpl.pauseElements; var element = list.pop(); while (element) { element.play(); element = list.pop(); } })); VideoPlayerImpl._polyfill = { devicePixelRatio: false, event: "canplay", canPlayType: [] }; var isBaiduGame = cc.sys.platform === cc.sys.BAIDU_GAME; var dom = document.createElement("video"); if (true, !isBaiduGame) { if (dom.canPlayType("video/ogg")) { VideoPlayerImpl._polyfill.canPlayType.push(".ogg"); VideoPlayerImpl._polyfill.canPlayType.push(".ogv"); } dom.canPlayType("video/mp4") && VideoPlayerImpl._polyfill.canPlayType.push(".mp4"); dom.canPlayType("video/webm") && VideoPlayerImpl._polyfill.canPlayType.push(".webm"); } sys.browserType === sys.BROWSER_TYPE_FIREFOX && (VideoPlayerImpl._polyfill.autoplayAfterOperation = true); sys.OS_ANDROID !== sys.os || sys.browserType !== sys.BROWSER_TYPE_SOUGOU && sys.browserType !== sys.BROWSER_TYPE_360 || (VideoPlayerImpl._polyfill.zoomInvalid = true); var style = document.createElement("style"); style.innerHTML = ".cocosVideo:-moz-full-screen{transform:matrix(1,0,0,1,0,0) !important;}.cocosVideo:full-screen{transform:matrix(1,0,0,1,0,0) !important;}.cocosVideo:-webkit-full-screen{transform:matrix(1,0,0,1,0,0) !important;}"; document.head.appendChild(style); module.exports = VideoPlayerImpl; }), { "../core/platform/CCSys": 170, "../core/platform/utils": 185, "../core/renderer/render-engine": 203 } ], 280: [ (function(require, module, exports) { var WebViewImpl = require("./webview-impl"); var EventType = WebViewImpl.EventType; function emptyCallback() {} var WebView = cc.Class({ name: "cc.WebView", extends: cc.Component, editor: false, properties: { _useOriginalSize: true, _url: "", url: { type: String, tooltip: false, get: function() { return this._url; }, set: function(url) { this._url = url; var impl = this._impl; impl && impl.loadURL(url); } }, webviewEvents: { default: [], type: cc.Component.EventHandler } }, statics: { EventType: EventType, Impl: WebViewImpl }, ctor: function() { this._impl = new WebView.Impl(); }, onRestore: function() { this._impl || (this._impl = new WebView.Impl()); }, onEnable: function() { var impl = this._impl; impl.createDomElementIfNeeded(this.node.width, this.node.height); true; impl.setEventListener(EventType.LOADED, this._onWebViewLoaded.bind(this)); impl.setEventListener(EventType.LOADING, this._onWebViewLoading.bind(this)); impl.setEventListener(EventType.ERROR, this._onWebViewLoadError.bind(this)); impl.loadURL(this._url); impl.setVisible(true); }, onDisable: function() { var impl = this._impl; impl.setVisible(false); true; impl.setEventListener(EventType.LOADED, emptyCallback); impl.setEventListener(EventType.LOADING, emptyCallback); impl.setEventListener(EventType.ERROR, emptyCallback); }, onDestroy: function() { if (this._impl) { this._impl.destroy(); this._impl = null; } }, update: function(dt) { this._impl && this._impl.updateMatrix(this.node); }, _onWebViewLoaded: function() { cc.Component.EventHandler.emitEvents(this.webviewEvents, this, EventType.LOADED); this.node.emit("loaded", this); }, _onWebViewLoading: function() { cc.Component.EventHandler.emitEvents(this.webviewEvents, this, EventType.LOADING); this.node.emit("loading", this); return true; }, _onWebViewLoadError: function() { cc.Component.EventHandler.emitEvents(this.webviewEvents, this, EventType.ERROR); this.node.emit("error", this); }, setJavascriptInterfaceScheme: function(scheme) { this._impl && this._impl.setJavascriptInterfaceScheme(scheme); }, setOnJSCallback: function(callback) { this._impl && this._impl.setOnJSCallback(callback); }, evaluateJS: function(str) { this._impl && this._impl.evaluateJS(str); } }); cc.WebView = module.exports = WebView; }), { "./webview-impl": 281 } ], 281: [ (function(require, module, exports) { var utils = require("../core/platform/utils"); var sys = require("../core/platform/CCSys"); var renderEngine = require("../core/renderer/render-engine"); var math = renderEngine.math; var _mat4_temp = math.mat4.create(); var WebViewImpl = cc.Class({ name: "WebViewImpl", ctor: function() { this._EventList = {}; this._visible = false; this._parent = null; this._div = null; this._iframe = null; this._listener = null; this._forceUpdate = true; this._m00 = 0; this._m01 = 0; this._m04 = 0; this._m05 = 0; this._m12 = 0; this._m13 = 0; this._w = 0; this._h = 0; this.__eventListeners = {}; }, _updateVisibility: function() { if (!this._div) return; var div = this._div; this._visible ? div.style.visibility = "visible" : div.style.visibility = "hidden"; this._forceUpdate = true; }, _updateSize: function(w, h) { var div = this._div; if (div) { div.style.width = w + "px"; div.style.height = h + "px"; } }, _initEvent: function() { var _this = this; var iframe = this._iframe; iframe && (function() { var cbs = _this.__eventListeners, self = _this; cbs.load = function() { self._dispatchEvent(WebViewImpl.EventType.LOADED); }; cbs.error = function() { self._dispatchEvent(WebViewImpl.EventType.ERROR); }; iframe.addEventListener("load", cbs.load); iframe.addEventListener("error", cbs.error); })(); }, _initStyle: function() { if (!this._div) return; var div = this._div; div.style.position = "absolute"; div.style.bottom = "0px"; div.style.left = "0px"; }, _setOpacity: function(opacity) { var iframe = this._iframe; iframe && iframe.style && (iframe.style.opacity = opacity / 255); }, _createDom: function(w, h) { if (WebViewImpl._polyfill.enableDiv) { this._div = document.createElement("div"); this._div.style["-webkit-overflow"] = "auto"; this._div.style["-webkit-overflow-scrolling"] = "touch"; this._iframe = document.createElement("iframe"); this._div.appendChild(this._iframe); this._iframe.style.width = "100%"; this._iframe.style.height = "100%"; } else this._div = this._iframe = document.createElement("iframe"); WebViewImpl._polyfill.enableBG && (this._div.style["background"] = "#FFF"); this._div.style["background"] = "#FFF"; this._div.style.height = h + "px"; this._div.style.width = w + "px"; this._div.style.overflow = "scroll"; this._iframe.style.border = "none"; cc.game.container.appendChild(this._div); this._updateVisibility(); }, _createNativeControl: function(w, h) { this._createDom(w, h); this._initStyle(); this._initEvent(); }, createDomElementIfNeeded: function(w, h) { this._div ? this._updateSize(w, h) : this._createNativeControl(w, h); }, removeDom: function() { var div = this._div; if (div) { var hasChild = utils.contains(cc.game.container, div); hasChild && cc.game.container.removeChild(div); this._div = null; } var iframe = this._iframe; if (iframe) { var cbs = this.__eventListeners; iframe.removeEventListener("load", cbs.load); iframe.removeEventListener("error", cbs.error); cbs.load = null; cbs.error = null; this._iframe = null; } }, setOnJSCallback: function(callback) {}, setJavascriptInterfaceScheme: function(scheme) {}, loadData: function(data, MIMEType, encoding, baseURL) {}, loadHTMLString: function(string, baseURL) {}, loadURL: function(url) { var _this2 = this; var iframe = this._iframe; iframe && (function() { iframe.src = url; var self = _this2; var cb = function() { self._loaded = true; self._updateVisibility(); iframe.removeEventListener("load", cb); }; iframe.addEventListener("load", cb); _this2._dispatchEvent(WebViewImpl.EventType.LOADING); })(); }, stopLoading: function() { cc.logID(7800); }, reload: function() { var iframe = this._iframe; if (iframe) { var win = iframe.contentWindow; win && win.location && win.location.reload(); } }, canGoBack: function() { cc.logID(7801); return true; }, canGoForward: function() { cc.logID(7802); return true; }, goBack: function() { try { if (WebViewImpl._polyfill.closeHistory) return cc.logID(7803); var iframe = this._iframe; if (iframe) { var win = iframe.contentWindow; win && win.location && win.history.back.call(win); } } catch (err) { cc.log(err); } }, goForward: function() { try { if (WebViewImpl._polyfill.closeHistory) return cc.logID(7804); var iframe = this._iframe; if (iframe) { var win = iframe.contentWindow; win && win.location && win.history.forward.call(win); } } catch (err) { cc.log(err); } }, evaluateJS: function(str) { var iframe = this._iframe; if (iframe) { var win = iframe.contentWindow; try { win.eval(str); this._dispatchEvent(WebViewImpl.EventType.JS_EVALUATED); } catch (err) { console.error(err); } } }, setScalesPageToFit: function() { cc.logID(7805); }, setEventListener: function(event, callback) { this._EventList[event] = callback; }, removeEventListener: function(event) { this._EventList[event] = null; }, _dispatchEvent: function(event) { var callback = this._EventList[event]; callback && callback.call(this, this, this._iframe.src); }, _createRenderCmd: function() { return new WebViewImpl.RenderCmd(this); }, destroy: function() { this.removeDom(); }, setVisible: function(visible) { if (this._visible !== visible) { this._visible = !!visible; this._updateVisibility(); } }, updateMatrix: function(node) { if (!this._div || !this._visible) return; node.getWorldMatrix(_mat4_temp); if (!this._forceUpdate && this._m00 === _mat4_temp.m00 && this._m01 === _mat4_temp.m01 && this._m04 === _mat4_temp.m04 && this._m05 === _mat4_temp.m05 && this._m12 === _mat4_temp.m12 && this._m13 === _mat4_temp.m13 && this._w === node._contentSize.width && this._h === node._contentSize.height) return; this._m00 = _mat4_temp.m00; this._m01 = _mat4_temp.m01; this._m04 = _mat4_temp.m04; this._m05 = _mat4_temp.m05; this._m12 = _mat4_temp.m12; this._m13 = _mat4_temp.m13; this._w = node._contentSize.width; this._h = node._contentSize.height; var scaleX = cc.view._scaleX, scaleY = cc.view._scaleY; var dpr = cc.view._devicePixelRatio; scaleX /= dpr; scaleY /= dpr; var container = cc.game.container; var a = _mat4_temp.m00 * scaleX, b = _mat4_temp.m01, c = _mat4_temp.m04, d = _mat4_temp.m05 * scaleY; var offsetX = container && container.style.paddingLeft ? parseInt(container.style.paddingLeft) : 0; var offsetY = container && container.style.paddingBottom ? parseInt(container.style.paddingBottom) : 0; this._updateSize(this._w, this._h); var w = this._div.clientWidth * scaleX; var h = this._div.clientHeight * scaleY; var appx = w * _mat4_temp.m00 * node._anchorPoint.x; var appy = h * _mat4_temp.m05 * node._anchorPoint.y; var viewport = cc.view._viewportRect; offsetX += viewport.x / dpr; offsetY += viewport.y / dpr; var tx = _mat4_temp.m12 * scaleX - appx + offsetX, ty = _mat4_temp.m13 * scaleY - appy + offsetY; var matrix = "matrix(" + a + "," + -b + "," + -c + "," + d + "," + tx + "," + -ty + ")"; this._div.style["transform"] = matrix; this._div.style["-webkit-transform"] = matrix; this._div.style["transform-origin"] = "0px 100% 0px"; this._div.style["-webkit-transform-origin"] = "0px 100% 0px"; this._setOpacity(node.opacity); } }); WebViewImpl.EventType = { LOADING: 0, LOADED: 1, ERROR: 2, JS_EVALUATED: 3 }; var polyfill = WebViewImpl._polyfill = { devicePixelRatio: false, enableDiv: false }; sys.os === sys.OS_IOS && (polyfill.enableDiv = true); sys.isMobile ? sys.browserType === sys.BROWSER_TYPE_FIREFOX && (polyfill.enableBG = true) : sys.browserType === sys.BROWSER_TYPE_IE && (polyfill.closeHistory = true); module.exports = WebViewImpl; }), { "../core/platform/CCSys": 170, "../core/platform/utils": 185, "../core/renderer/render-engine": 203 } ], 282: [ (function(require, module, exports) { 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": 111, "./cocos2d/core/components/CCStudioComponent": 84, "./cocos2d/deprecated": 261, "./cocos2d/particle": 267, "./cocos2d/particle/CCParticleAsset": 264, "./cocos2d/tilemap": 276, "./cocos2d/tilemap/CCTiledMapAsset": 273, "./cocos2d/videoplayer/CCVideoPlayer": 278, "./cocos2d/webview/CCWebView": 280, "./extensions/ccpool/CCNodePool": 283, "./extensions/dragonbones": 287, "./extensions/spine": 290 } ], 283: [ (function(require, module, exports) { cc.NodePool = function(poolHandlerComp) { this.poolHandlerComp = poolHandlerComp; this._pool = []; }; cc.NodePool.prototype = { constructor: cc.NodePool, size: function() { return this._pool.length; }, clear: function() { var count = this._pool.length; for (var i = 0; i < count; ++i) this._pool[i].destroy(); this._pool.length = 0; }, put: function(obj) { if (obj && -1 === this._pool.indexOf(obj)) { obj.removeFromParent(false); var handler = this.poolHandlerComp ? obj.getComponent(this.poolHandlerComp) : null; handler && handler.unuse && handler.unuse(); this._pool.push(obj); } }, get: function() { var last = this._pool.length - 1; if (last < 0) return null; var obj = this._pool[last]; this._pool.length = last; var handler = this.poolHandlerComp ? obj.getComponent(this.poolHandlerComp) : null; handler && handler.reuse && handler.reuse.apply(handler, arguments); return obj; } }; module.exports = cc.NodePool; }), {} ], 284: [ (function(require, module, exports) { var RenderComponent = require("../../cocos2d/core/components/CCRenderComponent"); var SpriteMaterial = require("../../cocos2d/core/renderer/render-engine").SpriteMaterial; var EventTarget = require("../../cocos2d/core/event/event-target"); var Node = require("../../cocos2d/core/CCNode"); var Graphics = require("../../cocos2d/core/graphics/graphics"); var ArmatureCache = require("./ArmatureCache"); var DefaultArmaturesEnum = cc.Enum({ default: -1 }); var DefaultAnimsEnum = cc.Enum({ "": 0 }); var DefaultCacheMode = cc.Enum({ REALTIME: 0 }); var AnimationCacheMode = cc.Enum({ REALTIME: 0, SHARED_CACHE: 1, PRIVATE_CACHE: 2 }); function setEnumAttr(obj, propName, enumDef) { cc.Class.attr(obj, propName, { type: "Enum", enumList: cc.Enum.getList(enumDef) }); } var ArmatureDisplay = cc.Class({ name: "dragonBones.ArmatureDisplay", extends: RenderComponent, editor: false, statics: { AnimationCacheMode: AnimationCacheMode }, properties: { _factory: { default: null, type: dragonBones.CCFactory, serializable: false }, dragonAsset: { default: null, type: dragonBones.DragonBonesAsset, notify: function() { this._refresh(); false; }, tooltip: false }, dragonAtlasAsset: { default: null, type: dragonBones.DragonBonesAtlasAsset, notify: function() { this._parseDragonAtlasAsset(); this._buildArmature(); }, tooltip: false }, _armatureName: "", armatureName: { get: function() { return this._armatureName; }, set: function(value) { this._armatureName = value; var animNames = this.getAnimationNames(this._armatureName); if (!this.animationName || animNames.indexOf(this.animationName) < 0) { false; this.animationName = ""; } this._armature && !this.isAnimationCached() && this._factory._dragonBones.clock.remove(this._armature); this._refresh(); this._armature && !this.isAnimationCached() && this._factory._dragonBones.clock.add(this._armature); }, visible: false }, _animationName: "", animationName: { get: function() { return this._animationName; }, set: function(value) { this._animationName = value; }, visible: false }, _defaultArmatureIndex: { default: 0, notify: function() { var armatureName = ""; if (this.dragonAsset) { var armaturesEnum = void 0; this.dragonAsset && (armaturesEnum = this.dragonAsset.getArmatureEnum()); if (!armaturesEnum) return cc.errorID(7400, this.name); armatureName = armaturesEnum[this._defaultArmatureIndex]; } void 0 !== armatureName ? this.armatureName = armatureName : cc.errorID(7401, this.name); }, type: DefaultArmaturesEnum, visible: true, editorOnly: true, animatable: false, displayName: "Armature", tooltip: false }, _animationIndex: { default: 0, notify: function() { if (0 === this._animationIndex) { this.animationName = ""; return; } var animsEnum = void 0; this.dragonAsset && (animsEnum = this.dragonAsset.getAnimsEnum(this.armatureName)); if (!animsEnum) return; var animName = animsEnum[this._animationIndex]; void 0 !== animName ? this.playAnimation(animName, this.playTimes) : cc.errorID(7402, this.name); }, type: DefaultAnimsEnum, visible: true, editorOnly: true, displayName: "Animation", tooltip: false }, _preCacheMode: -1, _cacheMode: AnimationCacheMode.REALTIME, _defaultCacheMode: { default: 0, type: AnimationCacheMode, notify: function() { this.setAnimationCacheMode(this._defaultCacheMode); }, editorOnly: true, visible: true, animatable: false, displayName: "Animation Cache Mode", tooltip: false }, timeScale: { default: 1, notify: function() { this._armature && (this._armature.animation.timeScale = this.timeScale); }, tooltip: false }, playTimes: { default: -1, tooltip: false }, premultipliedAlpha: { default: false, tooltip: false }, debugBones: { default: false, notify: function() { this._updateDebugDraw(); }, tooltip: false }, enableBatch: { default: false, notify: function() { this._updateBatch(); }, tooltip: false }, _armatureKey: "", _accTime: 0, _playCount: 0, _frameCache: null, _curFrame: null, _playing: false, _armatureCache: null }, ctor: function() { this._material = new SpriteMaterial(); this._eventTarget = null; this._materialCache = {}; this._inited = false; this._factory = dragonBones.CCFactory.getInstance(); }, onLoad: function() { var children = this.node.children; for (var i = 0, n = children.length; i < n; i++) { var child = children[i]; var pos = child._name && child._name.search("CHILD_ARMATURE-"); 0 === pos && child.destroy(); } }, _updateBatch: function() { var cache = this._materialCache; for (var mKey in cache) { var material = cache[mKey]; material && (material.useModel = !this.enableBatch); } }, _updateMaterial: function(material) { this._super(material); this._materialCache = {}; }, __preload: function() { this._init(); }, _init: function() { if (this._inited) return; this._inited = true; true; this._cacheMode = AnimationCacheMode.REALTIME; this._parseDragonAtlasAsset(); this._refresh(); 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._updateDebugDraw(); }, setAnimationCacheMode: function(cacheMode) { true; return; }, isAnimationCached: function() { false; return this._cacheMode !== AnimationCacheMode.REALTIME; }, onEnable: function() { this._super(); this._armature && !this.isAnimationCached() && this._factory._dragonBones.clock.add(this._armature); }, onDisable: function() { this._super(); this._armature && !this.isAnimationCached() && this._factory._dragonBones.clock.remove(this._armature); }, update: function(dt) { if (!this.isAnimationCached()) return; if (!this._playing) return; var frames = this._frameCache.frames; var totalTime = this._frameCache.totalTime; var frameCount = frames.length; 0 == this._accTime && 0 == this._playCount && this._eventTarget && this._eventTarget.emit(dragonBones.EventObject.START); this._accTime += dt * this.timeScale; var frameIdx = Math.floor(this._accTime / totalTime * frameCount); if (frameIdx >= frameCount) { this._eventTarget && this._eventTarget.emit(dragonBones.EventObject.LOOP_COMPLETE); this._eventTarget && this._eventTarget.emit(dragonBones.EventObject.COMPLETE); this._playCount++; if (-1 === this.playTimes || this.playTimes > 0 && this._playCount >= this.playTimes) { this._accTime = 0; this._playing = false; this._playCount = 0; return; } this._accTime = 0; frameIdx = 0; } this._curFrame = frames[frameIdx]; }, onDestroy: function() { this._super(); this._inited = false; true; if (this._cacheMode === AnimationCacheMode.PRIVATE_CACHE) { this._armatureCache.dispose(); this._armatureCache = null; this._armature = null; } else if (this._cacheMode === AnimationCacheMode.SHARED_CACHE) { this._armatureCache = null; this._armature = null; } else if (this._armature) { this._armature.dispose(); this._armature = null; } }, _updateDebugDraw: function() { if (this.debugBones) { if (!this._debugDraw) { 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._debugDraw = debugDraw; } this._debugDraw.node.parent = this.node; } else this._debugDraw && (this._debugDraw.node.parent = null); }, _buildArmature: function() { if (!this.dragonAsset || !this.dragonAtlasAsset || !this.armatureName) return; if (this._armature) { true; this._preCacheMode === AnimationCacheMode.PRIVATE_CACHE ? this._armatureCache.dispose() : this._preCacheMode === AnimationCacheMode.REALTIME && this._armature.dispose(); this._armatureCache = null; this._armature = null; this._displayProxy = null; this._frameCache = null; this._curFrame = null; this._playing = false; this._preCacheMode = null; this._eventTarget = null; } true; if (this._cacheMode === AnimationCacheMode.SHARED_CACHE) { this._armatureCache = ArmatureCache.sharedCache; this._eventTarget = new EventTarget(); } else if (this._cacheMode === AnimationCacheMode.PRIVATE_CACHE) { this._armatureCache = new ArmatureCache(); this._eventTarget = new EventTarget(); } var atlasUUID = this.dragonAtlasAsset._uuid; this._armatureKey = this.dragonAsset.init(this._factory, atlasUUID); if (this.isAnimationCached()) { this._armature = this._armatureCache.getArmatureCache(this.armatureName, this._armatureKey, atlasUUID); this._armature || (this._cacheMode = AnimationCacheMode.REALTIME); } this._preCacheMode = this._cacheMode; if (false, this._cacheMode === AnimationCacheMode.REALTIME) { this._displayProxy = this._factory.buildArmatureDisplay(this.armatureName, this._armatureKey, "", atlasUUID); if (!this._displayProxy) return; this._displayProxy._ccNode = this.node; this._armature = this._displayProxy._armature; this._armature.animation.timeScale = this.timeScale; } this._cacheMode !== AnimationCacheMode.REALTIME && this.debugBones && cc.warn("Debug bones is invalid in cached mode"); this._updateBatch(); this.animationName && this.playAnimation(this.animationName, this.playTimes); }, _parseDragonAtlasAsset: function() { this.dragonAtlasAsset && this.dragonAtlasAsset.init(this._factory); }, _refresh: function() { this._buildArmature(); false; }, _updateCacheModeEnum: false, _updateAnimEnum: false, _updateArmatureEnum: false, playAnimation: function(animName, playTimes) { this.playTimes = void 0 === playTimes ? -1 : playTimes; this.animationName = animName; if (this.isAnimationCached()) { var cache = this._armatureCache.getAnimationCache(this._armatureKey, animName); cache || (cache = this._armatureCache.updateAnimationCache(this._armatureKey, animName)); if (cache) { this._accTime = 0; this._playCount = 0; this._frameCache = cache; this._playing = true; this._curFrame = this._frameCache.frames[0]; } } else if (this._armature) return this._armature.animation.play(animName, this.playTimes); }, updateAnimationCache: function(animName) { if (!this.isAnimationCached()) return; var cache = this._armatureCache.updateAnimationCache(this._armatureKey, animName); this._frameCache = cache || this._frameCache; }, getArmatureNames: function() { var dragonBonesData = this._factory.getDragonBonesData(this._armatureKey); return dragonBonesData && dragonBonesData.armatureNames || []; }, getAnimationNames: function(armatureName) { var ret = []; var dragonBonesData = this._factory.getDragonBonesData(this._armatureKey); if (dragonBonesData) { var armatureData = dragonBonesData.getArmature(armatureName); if (armatureData) for (var animName in armatureData.animations) armatureData.animations.hasOwnProperty(animName) && ret.push(animName); } return ret; }, on: function(eventType, listener, target) { this.addEventListener(eventType, listener, target); }, off: function(eventType, listener, target) { this.removeEventListener(eventType, listener, target); }, once: function(eventType, listener, target) { this._displayProxy ? this._displayProxy.once(eventType, listener, target) : this._eventTarget && this._eventTarget.once(eventType, listener, target); }, addEventListener: function(eventType, listener, target) { this._displayProxy ? this._displayProxy.on(eventType, listener, target) : this._eventTarget && this._eventTarget.on(eventType, listener, target); }, removeEventListener: function(eventType, listener, target) { this._displayProxy ? this._displayProxy.off(eventType, listener, target) : this._eventTarget && this._eventTarget.off(eventType, listener, target); }, buildArmature: function(armatureName, node) { return this._factory.createArmatureNode(this, armatureName, node); }, armature: function() { return this._armature; } }); module.exports = dragonBones.ArmatureDisplay = ArmatureDisplay; }), { "../../cocos2d/core/CCNode": 30, "../../cocos2d/core/components/CCRenderComponent": 78, "../../cocos2d/core/event/event-target": 103, "../../cocos2d/core/graphics/graphics": 107, "../../cocos2d/core/renderer/render-engine": 203, "./ArmatureCache": void 0 } ], 285: [ (function(require, module, exports) { var ArmatureCache = false; var DragonBonesAsset = cc.Class({ name: "dragonBones.DragonBonesAsset", extends: cc.Asset, ctor: function() { this.reset(); }, properties: { _dragonBonesJson: "", dragonBonesJson: { get: function() { return this._dragonBonesJson; }, set: function(value) { this._dragonBonesJson = value; this.reset(); } }, _nativeAsset: { get: function() { return this._buffer; }, set: function(bin) { this._buffer = bin.buffer || bin; this.reset(); }, override: true } }, statics: { preventDeferredLoadDependents: true }, createNode: false, reset: function() { this._clear(); false; }, init: function(factory, atlasUUID) { false; this._factory = factory; var armatureKey = this._uuid + "#" + atlasUUID; var dragonBonesData = this._factory.getDragonBonesData(armatureKey); if (dragonBonesData) return armatureKey; var rawData = null; rawData = this.dragonBonesJson ? JSON.parse(this.dragonBonesJson) : this._nativeAsset; this._factory.parseDragonBonesData(rawData, armatureKey); return armatureKey; }, getArmatureEnum: false, getAnimsEnum: false, _clear: function() { true; return; }, destroy: function() { this._clear(); this._super(); } }); dragonBones.DragonBonesAsset = module.exports = DragonBonesAsset; }), { "./ArmatureCache": void 0 } ], 286: [ (function(require, module, exports) { var ArmatureCache = false; var DragonBonesAtlasAsset = cc.Class({ name: "dragonBones.DragonBonesAtlasAsset", extends: cc.Asset, ctor: function() { this._clear(); }, properties: { _atlasJson: "", atlasJson: { get: function() { return this._atlasJson; }, set: function(value) { this._atlasJson = value; this._clear(); } }, _texture: { default: null, type: cc.Texture2D, formerlySerializedAs: "texture" }, texture: { get: function() { return this._texture; }, set: function(value) { this._texture = value; this._clear(); } }, _textureAtlasData: null }, statics: { preventDeferredLoadDependents: true }, createNode: false, init: function(factory) { this._factory = factory; this._textureAtlasData ? factory.addTextureAtlasData(this._textureAtlasData, this._uuid) : this._textureAtlasData = factory.parseTextureAtlasData(this.atlasJson, this.texture, this._uuid); }, _clear: function() { true; return; }, destroy: function() { this._clear(); this._super(); } }); dragonBones.DragonBonesAtlasAsset = module.exports = DragonBonesAtlasAsset; }), { "./ArmatureCache": void 0 } ], 287: [ (function(require, module, exports) { var _global = "undefined" === (__typeofVal = typeof window, "object" === __typeofVal ? __realTypeOfObj(window) : __typeofVal) ? global : window; false; if (void 0 !== _global.dragonBones) { dragonBones.DisplayType = { Image: 0, Armature: 1, Mesh: 2 }; dragonBones.ArmatureType = { Armature: 0, MovieClip: 1, Stage: 2 }; dragonBones.ExtensionType = { FFD: 0, AdjustColor: 10, BevelFilter: 11, BlurFilter: 12, DropShadowFilter: 13, GlowFilter: 14, GradientBevelFilter: 15, GradientGlowFilter: 16 }; dragonBones.EventType = { Frame: 0, Sound: 1 }; dragonBones.ActionType = { Play: 0, Stop: 1, GotoAndPlay: 2, GotoAndStop: 3, FadeIn: 4, FadeOut: 5 }; dragonBones.AnimationFadeOutMode = { None: 0, SameLayer: 1, SameGroup: 2, SameLayerAndGroup: 3, All: 4 }; dragonBones.BinaryOffset = { WeigthBoneCount: 0, WeigthFloatOffset: 1, WeigthBoneIndices: 2, MeshVertexCount: 0, MeshTriangleCount: 1, MeshFloatOffset: 2, MeshWeightOffset: 3, MeshVertexIndices: 4, TimelineScale: 0, TimelineOffset: 1, TimelineKeyFrameCount: 2, TimelineFrameValueCount: 3, TimelineFrameValueOffset: 4, TimelineFrameOffset: 5, FramePosition: 0, FrameTweenType: 1, FrameTweenEasingOrCurveSampleCount: 2, FrameCurveSamples: 3, DeformMeshOffset: 0, DeformCount: 1, DeformValueCount: 2, DeformValueOffset: 3, DeformFloatOffset: 4 }; dragonBones.BoneType = { Bone: 0, Surface: 1 }; true; false; require("./DragonBonesAsset"); require("./DragonBonesAtlasAsset"); require("./ArmatureDisplay"); require("./webgl-assembler"); } }), { "./ArmatureCache": void 0, "./ArmatureDisplay": 284, "./CCArmatureDisplay": void 0, "./CCFactory": void 0, "./CCSlot": void 0, "./CCTextureData": void 0, "./DragonBonesAsset": 285, "./DragonBonesAtlasAsset": 286, "./lib/dragonBones": void 0, "./webgl-assembler": 288 } ], 288: [ (function(require, module, exports) { var Armature = require("./ArmatureDisplay"); var renderEngine = require("../../cocos2d/core/renderer/render-engine"); var RenderFlow = require("../../cocos2d/core/renderer/render-flow"); var gfx = renderEngine.gfx; var math = require("../../cocos2d/core/renderer/render-engine").math; var NEED_NONE = 0; var NEED_COLOR = 1; var NEED_BATCH = 16; var NEED_COLOR_BATCH = 17; var _boneColor = cc.color(255, 0, 0, 255); var _slotColor = cc.color(0, 0, 255, 255); var _nodeR = void 0, _nodeG = void 0, _nodeB = void 0, _nodeA = void 0, _premultipliedAlpha = void 0, _mustFlush = void 0, _buffer = void 0, _node = void 0, _renderer = void 0, _comp = void 0, _vfOffset = void 0, _indexOffset = void 0, _vertexOffset = void 0, _vertexCount = void 0, _indexCount = void 0, _x = void 0, _y = void 0, _c = void 0, _r = void 0, _g = void 0, _b = void 0, _a = void 0, _handleVal = void 0, _m00 = void 0, _m04 = void 0, _m12 = void 0, _m01 = void 0, _m05 = void 0, _m13 = void 0; function _getSlotMaterial(tex, blendMode) { if (!tex) return null; var src = void 0, dst = void 0; switch (blendMode) { case 1: src = _premultipliedAlpha ? cc.macro.ONE : cc.macro.SRC_ALPHA; dst = cc.macro.ONE; break; case 10: src = cc.macro.DST_COLOR; dst = cc.macro.ONE_MINUS_SRC_ALPHA; break; case 12: src = cc.macro.ONE; dst = cc.macro.ONE_MINUS_SRC_COLOR; break; case 0: default: src = _premultipliedAlpha ? cc.macro.ONE : cc.macro.SRC_ALPHA; dst = cc.macro.ONE_MINUS_SRC_ALPHA; } var useModel = !_comp.enableBatch; var key = tex.url + src + dst + useModel; var baseMaterial = _comp._material; if (!baseMaterial) return null; var materialCache = _comp._materialCache; var material = materialCache[key]; if (material) { if (material.texture !== tex) { material.texture = tex; material.updateHash(key); } } else { var baseKey = baseMaterial._hash; material = materialCache[baseKey] ? baseMaterial.clone() : baseMaterial; material.useModel = useModel; material.texture = tex; material.useColor = false; var pass = material._mainTech.passes[0]; pass.setBlend(gfx.BLEND_FUNC_ADD, src, dst, gfx.BLEND_FUNC_ADD, src, dst); materialCache[key] = material; material.updateHash(key); } return material; } function _handleColor(color) { _r = color.r * _nodeR; _g = color.g * _nodeG; _b = color.b * _nodeB; _a = color.a * _nodeA; _c = (_a << 24 >>> 0) + (_b << 16) + (_g << 8) + _r; } var armatureAssembler = { updateRenderData: function(comp, batchData) {}, realTimeTraverse: function(armature, parentMat) { var slots = armature._slots; var vbuf = void 0, ibuf = void 0, uintbuf = void 0; var material = void 0; var vertices = void 0, indices = void 0; var slotColor = void 0; var slot = void 0; var slotMat = void 0; var offsetInfo = void 0; for (var i = 0, l = slots.length; i < l; i++) { slot = slots[i]; if (!slot._visible || !slot._displayData) continue; parentMat ? slot._mulMat(slot._worldMatrix, parentMat, slot._matrix) : math.mat4.copy(slot._worldMatrix, slot._matrix); if (slot.childArmature) { this.realTimeTraverse(slot.childArmature, slot._worldMatrix); continue; } material = _getSlotMaterial(slot.getTexture(), slot._blendMode); if (!material) continue; if (_mustFlush || material._hash !== _renderer.material._hash) { _mustFlush = false; _renderer._flush(); _renderer.node = _node; _renderer.material = material; } slotColor = slot._color; _handleColor(slotColor); slotMat = slot._worldMatrix; vertices = slot._localVertices; _vertexCount = vertices.length >> 2; indices = slot._indices; _indexCount = indices.length; offsetInfo = _buffer.request(_vertexCount, _indexCount); _indexOffset = offsetInfo.indiceOffset; _vfOffset = offsetInfo.byteOffset >> 2; _vertexOffset = offsetInfo.vertexOffset; vbuf = _buffer._vData; ibuf = _buffer._iData; uintbuf = _buffer._uintVData; _m00 = slotMat.m00; _m04 = slotMat.m04; _m12 = slotMat.m12; _m01 = slotMat.m01; _m05 = slotMat.m05; _m13 = slotMat.m13; for (var vi = 0, vl = vertices.length; vi < vl; ) { _x = vertices[vi++]; _y = vertices[vi++]; vbuf[_vfOffset++] = _x * _m00 + _y * _m04 + _m12; vbuf[_vfOffset++] = _x * _m01 + _y * _m05 + _m13; vbuf[_vfOffset++] = vertices[vi++]; vbuf[_vfOffset++] = vertices[vi++]; uintbuf[_vfOffset++] = _c; } for (var ii = 0, il = indices.length; ii < il; ii++) ibuf[_indexOffset++] = _vertexOffset + indices[ii]; } }, cacheTraverse: function(frame, parentMat) { if (!frame) return; var segments = frame.segments; if (0 == segments.length) return; var vbuf = void 0, ibuf = void 0, uintbuf = void 0; var material = void 0; var offsetInfo = void 0; var vertices = frame.vertices; var indices = frame.indices; var uintVert = frame.uintVert; var frameVFOffset = 0, frameIndexOffset = 0, segVFCount = 0; if (parentMat) { _m00 = parentMat.m00; _m04 = parentMat.m04; _m12 = parentMat.m12; _m01 = parentMat.m01; _m05 = parentMat.m05; _m13 = parentMat.m13; } var colorOffset = 0; var colors = frame.colors; var nowColor = colors[colorOffset++]; var maxVFOffset = 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 (_mustFlush || material._hash !== _renderer.material._hash) { _mustFlush = false; _renderer._flush(); _renderer.node = _node; _renderer.material = material; } _vertexCount = segInfo.vertexCount; _indexCount = segInfo.indexCount; offsetInfo = _buffer.request(_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 = segInfo.vfCount; switch (_handleVal) { case NEED_COLOR: case NEED_NONE: vbuf.set(vertices.subarray(frameVFOffset, frameVFOffset + segVFCount), _vfOffset); frameVFOffset += segVFCount; break; case NEED_BATCH: case NEED_COLOR_BATCH: for (var _ii = _vfOffset, _il = _vfOffset + segVFCount; _ii < _il; ) { _x = vertices[frameVFOffset++]; _y = vertices[frameVFOffset++]; vbuf[_ii++] = _x * _m00 + _y * _m04 + _m12; vbuf[_ii++] = _x * _m01 + _y * _m05 + _m13; vbuf[_ii++] = vertices[frameVFOffset++]; vbuf[_ii++] = vertices[frameVFOffset++]; uintbuf[_ii++] = uintVert[frameVFOffset++]; } } if (!(_handleVal & NEED_COLOR)) continue; var frameColorOffset = frameVFOffset - segVFCount; for (var _ii2 = _vfOffset + 4, _il2 = _vfOffset + 4 + segVFCount; _ii2 < _il2; _ii2 += 5, frameColorOffset += 5) { if (frameColorOffset >= maxVFOffset) { nowColor = colors[colorOffset++]; _handleColor(nowColor); maxVFOffset = nowColor.vfOffset; } uintbuf[_ii2] = _c; } } }, fillBuffers: function(comp, renderer) { comp.node._renderFlag |= RenderFlow.FLAG_UPDATE_RENDER_DATA; _mustFlush = true; _premultipliedAlpha = comp.premultipliedAlpha; _node = comp.node; _buffer = renderer._meshBuffer; _renderer = renderer; _comp = comp; _handleVal = 0; var nodeColor = _node._color; _nodeR = nodeColor.r / 255; _nodeG = nodeColor.g / 255; _nodeB = nodeColor.b / 255; _nodeA = nodeColor.a / 255; 4294967295 !== nodeColor._val && (_handleVal |= NEED_COLOR); var worldMat = void 0; if (_comp.enableBatch) { worldMat = _node._worldMatrix; _mustFlush = false; _handleVal |= NEED_BATCH; } if (comp.isAnimationCached()) this.cacheTraverse(comp._curFrame, worldMat); else { var armature = comp._armature; if (!armature) return; this.realTimeTraverse(armature, worldMat); var graphics = comp._debugDraw; if (comp.debugBones && graphics) { graphics.clear(); graphics.lineWidth = 5; graphics.strokeColor = _boneColor; graphics.fillColor = _slotColor; var bones = armature.getBones(); for (var i = 0, l = bones.length; i < l; i++) { var bone = bones[i]; var boneLength = Math.max(bone.boneData.length, 5); var startX = bone.globalTransformMatrix.tx; var startY = -bone.globalTransformMatrix.ty; var endX = startX + bone.globalTransformMatrix.a * boneLength; var endY = startY - bone.globalTransformMatrix.b * boneLength; graphics.moveTo(startX, startY); graphics.lineTo(endX, endY); graphics.stroke(); } } } _node = void 0; _buffer = void 0; _renderer = void 0; _comp = void 0; } }; module.exports = Armature._assembler = armatureAssembler; }), { "../../cocos2d/core/renderer/render-engine": 203, "../../cocos2d/core/renderer/render-flow": 204, "./ArmatureDisplay": 284 } ], 289: [ (function(require, module, exports) { var TrackEntryListeners = require("./track-entry-listeners"); var RenderComponent = require("../../cocos2d/core/components/CCRenderComponent"); var spine = require("./lib/spine"); var SpineMaterial = require("../../cocos2d/core/renderer/render-engine").SpineMaterial; var Graphics = require("../../cocos2d/core/graphics/graphics"); var SkeletonCache = require("./skeleton-cache"); 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(obj, propName, { type: "Enum", 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() { this.defaultSkin = ""; this.defaultAnimation = ""; false; this._updateSkeletonData(); }, tooltip: false }, defaultSkin: { default: "", visible: false }, defaultAnimation: { default: "", visible: false }, animation: { get: function() { if (this.isAnimationCached()) return this._animationName; var entry = this.getCurrent(0); return entry && entry.animation.name || ""; }, set: function(value) { this.defaultAnimation = value; if (value) this.setAnimation(0, value, this.loop); else { this.clearTrack(0); this.setToSetupPose(); } }, visible: false }, _defaultSkinIndex: { get: function() { if (this.skeletonData && this.defaultSkin) { var skinsEnum = this.skeletonData.getSkinsEnum(); if (skinsEnum) { var skinIndex = skinsEnum[this.defaultSkin]; if (void 0 !== skinIndex) return skinIndex; } } return 0; }, set: function(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; false; } else cc.errorID(7501, this.name); }, type: DefaultSkinsEnum, visible: true, displayName: "Default Skin", tooltip: false }, _animationIndex: { get: function() { 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(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, displayName: "Animation", tooltip: false }, _preCacheMode: -1, _cacheMode: AnimationCacheMode.REALTIME, _defaultCacheMode: { default: 0, type: AnimationCacheMode, notify: function() { 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() { this._updateDebugDraw(); } }, debugBones: { default: false, editorOnly: true, tooltip: false, notify: function() { this._updateDebugDraw(); } }, useTint: { default: false, tooltip: false, notify: function() { this._updateUseTint(); } }, enableBatch: { default: false, notify: function() { this._updateBatch(); }, tooltip: false }, _accTime: 0, _playCount: 0, _frameCache: null, _curFrame: null, _skeletonCache: null, _animationName: null, _animationQueue: [], _headAniInfo: null, _playTimes: 0, _isAniComplete: true }, ctor: function() { this._skeleton = null; this._rootBone = null; this._listener = null; this._boundingBox = cc.rect(); this._material = new SpineMaterial(); this._materialCache = {}; this._debugRenderer = null; this._startSlotIndex = -1; this._endSlotIndex = -1; this._startEntry = { animation: { name: "" }, trackIndex: 0 }; this._endEntry = { animation: { name: "" }, trackIndex: 0 }; }, _updateMaterial: function(material) { this._super(material); this._materialCache = {}; }, _updateUseTint: function() { var cache = this._materialCache; for (var mKey in cache) { var material = cache[mKey]; material && (material.useTint = this.useTint); } }, _updateBatch: function() { var cache = this._materialCache; for (var mKey in cache) { var material = cache[mKey]; material && (material.useModel = !this.enableBatch); } }, setSkeletonData: function(skeletonData) { null != skeletonData.width && null != skeletonData.height && this.node.setContentSize(skeletonData.width, skeletonData.height); if (this.isAnimationCached()) { 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(); } }, setSlotsRange: function(startSlotIndex, endSlotIndex) { if (this.isAnimationCached()) console.warn("Slots visible range can not be modified in cached mode."); else { this._startSlotIndex = startSlotIndex; this._endSlotIndex = endSlotIndex; } }, setAnimationStateData: function(stateData) { if (this.isAnimationCached()) console.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() { 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(); } true; this._cacheMode = AnimationCacheMode.REALTIME; this._updateSkeletonData(); this._updateDebugDraw(); this._updateUseTint(); this._updateBatch(); }, setAnimationCacheMode: function(cacheMode) { true; return; }, isAnimationCached: function() { false; return this._cacheMode !== AnimationCacheMode.REALTIME; }, update: function(dt) { false; if (this.paused) return; if (this.isAnimationCached()) { if (this._isAniComplete) { if (0 === this._animationQueue.length && !this._headAniInfo) 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); }, _updateCache: function(dt) { var frames = this._frameCache.frames; var totalTime = this._frameCache.totalTime; var frameCount = frames.length; 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 * this.timeScale; var frameIdx = Math.floor(this._accTime / totalTime * frameCount); if (frameIdx >= frameCount) { this._endEntry.animation.name = this._animationName; this._listener && this._listener.complete && this._listener.complete(this._endEntry); this._listener && this._listener.end && this._listener.end(this._endEntry); this._playCount++; if (this._playTimes > 0 && this._playCount >= this._playTimes) { this._accTime = 0; this._playCount = 0; this._isAniComplete = true; return; } this._accTime = 0; frameIdx = 0; } this._curFrame = frames[frameIdx]; }, _updateRealtime: function(dt) { var skeleton = this._skeleton; var state = this._state; if (skeleton) { skeleton.update(dt); if (state) { dt *= this.timeScale; state.update(dt); state.apply(skeleton); } } }, onRestore: function() { if (!this._material) { this._boundingBox = cc.rect(); this._material = new SpineMaterial(); this._materialCache = {}; } }, updateWorldTransform: function() { if (!this.isAnimationCached()) return; this._skeleton && this._skeleton.updateWorldTransform(); }, setToSetupPose: function() { this.isAnimationCached() ? cc.warn("'SetToSetupPose' interface can not be invoked in cached mode.") : this._skeleton && this._skeleton.setToSetupPose(); }, setBonesToSetupPose: function() { this.isAnimationCached() ? cc.warn("'setBonesToSetupPose' interface can not be invoked in cached mode.") : this._skeleton && this._skeleton.setBonesToSetupPose(); }, setSlotsToSetupPose: function() { this.isAnimationCached() ? cc.warn("'setSlotsToSetupPose' interface can not be invoked in cached mode.") : this._skeleton && this._skeleton.setSlotsToSetupPose(); }, updateAnimationCache: function(animName) { if (!this.isAnimationCached()) return; var cache = this._skeletonCache.updateAnimationCache(this.skeletonData._uuid, animName); this._frameCache = cache || this._frameCache; }, findBone: function(boneName) { if (this._skeleton) return this._skeleton.findBone(boneName); return null; }, findSlot: function(slotName) { if (this._skeleton) return this._skeleton.findSlot(slotName); return null; }, setSkin: function(skinName) { if (this.isAnimationCached()) { this._skeletonCache.resetSkeleton(); this._animationName && (this.animation = this._animationName); } else if (this._skeleton) return this._skeleton.setSkinByName(skinName); return null; }, getAttachment: function(slotName, attachmentName) { if (this._skeleton) return this._skeleton.getAttachmentByName(slotName, attachmentName); return null; }, setAttachment: function(slotName, attachmentName) { this._skeleton && this._skeleton.setAttachment(slotName, attachmentName); }, getTextureAtlas: function(regionAttachment) { return regionAttachment.region; }, setMix: function(fromAnimation, toAnimation, duration) { this._state && this._state.data.setMix(fromAnimation, toAnimation, duration); }, setAnimation: function(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."); var cache = this._skeletonCache.getAnimationCache(this.skeletonData._uuid, name); cache || (cache = this._skeletonCache.updateAnimationCache(this.skeletonData._uuid, name)); if (cache) { this._isAniComplete = false; this._accTime = 0; this._playCount = 0; this._frameCache = cache; 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(trackIndex, name, loop, delay) { 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) { delay = delay || 0; 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(name) { if (this._skeleton) return this._skeleton.data.findAnimation(name); return null; }, getCurrent: function(trackIndex) { if (this.isAnimationCached()) console.warn("'getCurrent' interface can not be invoked in cached mode."); else if (this._state) return this._state.getCurrent(trackIndex); return null; }, clearTracks: function() { this.isAnimationCached() ? console.warn("'clearTracks' interface can not be invoked in cached mode.") : this._state && this._state.clearTracks(); }, clearTrack: function(trackIndex) { if (this.isAnimationCached()) console.warn("'clearTrack' interface can not be invoked in cached mode."); else if (this._state) { this._state.clearTrack(trackIndex); false; } }, setStartListener: function(listener) { this._ensureListener(); this._listener.start = listener; }, setInterruptListener: function(listener) { this._ensureListener(); this._listener.interrupt = listener; }, setEndListener: function(listener) { this._ensureListener(); this._listener.end = listener; }, setDisposeListener: function(listener) { this._ensureListener(); this._listener.dispose = listener; }, setCompleteListener: function(listener) { this._ensureListener(); this._listener.complete = listener; }, setEventListener: function(listener) { this._ensureListener(); this._listener.event = listener; }, setTrackStartListener: function(entry, listener) { TrackEntryListeners.getListeners(entry).start = listener; }, setTrackInterruptListener: function(entry, listener) { TrackEntryListeners.getListeners(entry).interrupt = listener; }, setTrackEndListener: function(entry, listener) { TrackEntryListeners.getListeners(entry).end = listener; }, setTrackDisposeListener: function(entry, listener) { TrackEntryListeners.getListeners(entry).dispose = listener; }, setTrackCompleteListener: function(entry, listener) { TrackEntryListeners.getListeners(entry).complete = function(trackEntry) { var loopCount = Math.floor(trackEntry.trackTime / trackEntry.animationEnd); listener(trackEntry, loopCount); }; }, setTrackEventListener: function(entry, listener) { TrackEntryListeners.getListeners(entry).event = listener; }, getState: function() { return this._state; }, _updateAnimEnum: false, _updateSkinEnum: false, _ensureListener: function() { if (!this._listener) { this._listener = new TrackEntryListeners(); this._state && this._state.addListener(this._listener); } }, _updateSkeletonData: function() { if (!this.skeletonData) return; var data = this.skeletonData.getRuntimeData(); if (!data) return; true; this._cacheMode === AnimationCacheMode.SHARED_CACHE ? this._skeletonCache = SkeletonCache.sharedCache : this._cacheMode === AnimationCacheMode.PRIVATE_CACHE && (this._skeletonCache = new SkeletonCache()); this.isAnimationCached() && (this.debugBones || this.debugSlots) && cc.warn("Debug bones or slots is invalid in cached mode"); 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._preCacheMode = this._cacheMode; this.animation = this.defaultAnimation; }, _refreshInspector: function() { this._updateAnimEnum(); this._updateSkinEnum(); Editor.Utils.refreshSelectedInspector("node", this.node.uuid); }, _updateDebugDraw: function() { 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": 78, "../../cocos2d/core/graphics/graphics": 107, "../../cocos2d/core/renderer/render-engine": 203, "./lib/spine": void 0, "./skeleton-cache": void 0, "./track-entry-listeners": 294 } ], 290: [ (function(require, module, exports) { var _global = "undefined" === (__typeofVal = typeof window, "object" === __typeofVal ? __realTypeOfObj(window) : __typeofVal) ? global : window; var _isUseSpine = true; (true, void 0 === _global.spine) && (_isUseSpine = false); if (_isUseSpine) { _global.sp = {}; 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; true; sp.spine = _global.spine; require("./skeleton-texture"); require("./skeleton-data"); require("./Skeleton"); require("./spine-assembler"); } }), { "./Skeleton": 289, "./lib/spine": void 0, "./skeleton-data": 291, "./skeleton-texture": 292, "./spine-assembler": 293 } ], 291: [ (function(require, module, exports) { var SkeletonCache = false; var SkeletonData = cc.Class({ name: "sp.SkeletonData", extends: cc.Asset, ctor: function() { this.reset(); }, properties: { _skeletonJson: null, skeletonJson: { get: function() { return this._skeletonJson; }, set: function(value) { this._skeletonJson = value; this.reset(); } }, _atlasText: "", atlasText: { get: function() { return this._atlasText; }, set: function(value) { this._atlasText = value; this.reset(); } }, textures: { default: [], type: [ cc.Texture2D ] }, textureNames: { default: [], type: [ cc.String ] }, scale: 1 }, statics: { preventDeferredLoadDependents: true, preventPreloadNativeObject: true }, createNode: false, reset: function() { this._skeletonCache = null; this._atlasCache = null; false; }, getRuntimeData: function(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 jsonReader = new sp.spine.SkeletonJson(attachmentLoader); jsonReader.scale = this.scale; var json = this.skeletonJson; this._skeletonCache = jsonReader.readSkeletonData(json); atlas.dispose(jsonReader); return this._skeletonCache; }, getSkinsEnum: false, getAnimsEnum: false, _getTexture: function(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(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)); }, destroy: function() { false; this._super(); } }); sp.SkeletonData = module.exports = SkeletonData; }), { "./skeleton-cache": void 0 } ], 292: [ (function(require, module, exports) { sp.SkeletonTexture = cc.Class({ name: "sp.SkeletonTexture", extends: sp.spine.Texture, _texture: null, _material: null, setRealTexture: function(tex) { this._texture = tex; }, getRealTexture: function() { return this._texture; }, setFilters: function(minFilter, magFilter) { this._texture && this._texture.setFilters(minFilter, magFilter); }, setWraps: function(uWrap, vWrap) { this._texture && this._texture.setWrapMode(uWrap, vWrap); }, dispose: function() {} }); }), {} ], 293: [ (function(require, module, exports) { var Skeleton = require("./Skeleton"); var spine = require("./lib/spine"); var renderer = require("../../cocos2d/core/renderer"); var RenderFlow = require("../../cocos2d/core/renderer/render-flow"); var renderEngine = renderer.renderEngine; var gfx = renderEngine.gfx; var VertexFormat = require("../../cocos2d/core/renderer/webgl/vertex-format"); var VFOneColor = VertexFormat.vfmtPosUvColor; var VFTwoColor = VertexFormat.vfmtPosUvTwoColor; var FLAG_BATCH = 16; var FLAG_TWO_COLOR = 1; var NOT_BATCH_ONE_COLOR = 0; var NOT_BATCH_TWO_COLOR = 1; var BATCH_ONE_COLOR = 16; var BATCH_TWO_COLOR = 17; 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 _finalColor = void 0; var _darkColor = void 0; false; var _premultipliedAlpha = void 0; var _multiplier = void 0; var _slotRangeStart = void 0; var _slotRangeEnd = void 0; var _useTint = void 0; var _debugSlots = void 0; var _debugBones = void 0; var _nodeR = void 0, _nodeG = void 0, _nodeB = void 0, _nodeA = void 0; var _finalColor32 = void 0, _darkColor32 = void 0; var _vertexFormat = void 0; var _perVertexSize = void 0; var _perClipVertexSize = void 0; var _vertexFloatCount = 0, _vertexCount = 0, _vertexFloatOffset = 0, _vertexOffset = 0, _indexCount = 0, _indexOffset = 0, _vfOffset = 0; var _tempr = void 0, _tempg = void 0, _tempb = void 0, _tempa = void 0; var _inRange = void 0; var _mustFlush = void 0; var _x = void 0, _y = void 0, _m00 = void 0, _m04 = void 0, _m12 = void 0, _m01 = void 0, _m05 = void 0, _m13 = void 0; var _r = void 0, _g = void 0, _b = void 0, _fr = void 0, _fg = void 0, _fb = void 0, _fa = void 0, _dr = void 0, _dg = void 0, _db = void 0, _da = void 0; var _comp = void 0, _buffer = void 0, _renderer = void 0, _node = void 0, _needColor = void 0; function _getSlotMaterial(tex, blendMode) { var src = void 0, dst = void 0; 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 key = tex.url + src + dst + _useTint + useModel; var baseMaterial = _comp._material; if (!baseMaterial) return null; var materialCache = _comp._materialCache; var material = materialCache[key]; if (material) { if (material.texture !== tex) { material.texture = tex; material.updateHash(key); } } else { var baseKey = baseMaterial._hash; material = materialCache[baseKey] ? baseMaterial.clone() : baseMaterial; material.useModel = useModel; material.texture = tex; material.useTint = _useTint; var pass = material._mainTech.passes[0]; pass.setBlend(gfx.BLEND_FUNC_ADD, src, dst, gfx.BLEND_FUNC_ADD, src, dst); material.updateHash(key); materialCache[key] = material; } return material; } function _handleColor(color) { _multiplier = _premultipliedAlpha ? color.fa / 255 : 1; _r = _nodeR * _multiplier; _g = _nodeG * _multiplier; _b = _nodeB * _multiplier; _fr = color.fr * _r; _fg = color.fg * _g; _fb = color.fb * _b; _fa = color.fa * _nodeA; _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; } var spineAssembler = { updateRenderData: function(comp, batchData) { var skeleton = comp._skeleton; skeleton && skeleton.updateWorldTransform(); }, fillVertices: function(skeletonColor, attachmentColor, slotColor, clipper, slot) { var vbuf = _buffer._vData, ibuf = _buffer._iData, uintVData = _buffer._uintVData; var offsetInfo = void 0; _tempa = slotColor.a * attachmentColor.a * skeletonColor.a * 255; _multiplier = _premultipliedAlpha ? _tempa : 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; _finalColor.a = _tempa * _nodeA; 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.request(_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 (_useTint) for (var _v3 = 0, _n3 = clippedVertices.length, _offset = _vertexFloatOffset; _v3 < _n3; _v3 += 12, _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; _darkColor32 = (clippedVertices[_v3 + 11] << 24 >>> 0) + (clippedVertices[_v3 + 10] << 16) + (clippedVertices[_v3 + 9] << 8) + clippedVertices[_v3 + 8]; uintVData[_offset + 5] = _darkColor32; } else for (var _v2 = 0, _n2 = clippedVertices.length, offset = _vertexFloatOffset; _v2 < _n2; _v2 += 8, offset += _perVertexSize) { vbuf[offset] = clippedVertices[_v2]; vbuf[offset + 1] = clippedVertices[_v2 + 1]; vbuf[offset + 2] = clippedVertices[_v2 + 6]; vbuf[offset + 3] = clippedVertices[_v2 + 7]; _finalColor32 = (clippedVertices[_v2 + 5] << 24 >>> 0) + (clippedVertices[_v2 + 4] << 16) + (clippedVertices[_v2 + 3] << 8) + clippedVertices[_v2 + 2]; uintVData[offset + 4] = _finalColor32; } } else { _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 (_useTint) for (var _v = _vertexFloatOffset, _n = _vertexFloatOffset + _vertexFloatCount; _v < _n; _v += _perVertexSize) { uintVData[_v + 4] = _finalColor32; uintVData[_v + 5] = _darkColor32; } else for (var v = _vertexFloatOffset, n = _vertexFloatOffset + _vertexFloatCount; v < n; v += _perVertexSize) uintVData[v + 4] = _finalColor32; } }, realTimeTraverse: function(worldMat) { var vbuf = void 0; var ibuf = void 0; var locSkeleton = _comp._skeleton; var skeletonColor = locSkeleton.color; var graphics = _comp._debugRenderer; var clipper = _comp._clipper; var material = null; var attachment = void 0, attachmentColor = void 0, slotColor = void 0, uvs = void 0, triangles = void 0; var isRegion = void 0, isMesh = void 0, isClip = void 0; var offsetInfo = void 0; var slot = void 0; _slotRangeStart = _comp._startSlotIndex; _slotRangeEnd = _comp._endSlotIndex; _inRange = false; -1 == _slotRangeStart && (_inRange = true); _debugSlots = _comp.debugSlots; _debugBones = _comp.debugBones; if (graphics && (_debugBones || _debugSlots)) { graphics.clear(); graphics.strokeColor = _slotColor; graphics.lineWidth = 5; } _perClipVertexSize = _useTint ? 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]; _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) 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) continue; material = _getSlotMaterial(attachment.region.texture._texture, slot.data.blendMode); if (!material) continue; if (_mustFlush || material._hash !== _renderer.material._hash) { _mustFlush = false; _renderer._flush(); _renderer.node = _node; _renderer.material = material; } if (isRegion) { triangles = _quadTriangles; _vertexFloatCount = 4 * _perVertexSize; _indexCount = 6; offsetInfo = _buffer.request(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.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.request(_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 (0 == _vertexFloatCount || 0 == _indexCount) 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); if (_indexCount > 0) { for (var _ii = _indexOffset, _nn = _indexOffset + _indexCount; _ii < _nn; _ii++) ibuf[_ii] += _vertexOffset; if (worldMat) { _m00 = worldMat.m00; _m04 = worldMat.m04; _m12 = worldMat.m12; _m01 = worldMat.m01; _m05 = worldMat.m05; _m13 = worldMat.m13; for (var _ii2 = _vertexFloatOffset, _nn2 = _vertexFloatOffset + _vertexFloatCount; _ii2 < _nn2; _ii2 += _perVertexSize) { _x = vbuf[_ii2]; _y = vbuf[_ii2 + 1]; vbuf[_ii2] = _x * _m00 + _y * _m04 + _m12; vbuf[_ii2 + 1] = _x * _m01 + _y * _m05 + _m13; } } _buffer.adjust(_vertexFloatCount / _perVertexSize, _indexCount); } clipper.clipEndWithSlot(slot); } clipper.clipEnd(); if (graphics && _debugBones) { var bone = void 0; 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, 2 * Math.PI); graphics.fill(); 0 === i && (graphics.fillColor = _originColor); } } }, cacheTraverse: function(worldMat) { var frame = _comp._curFrame; if (!frame) return; var segments = frame.segments; if (0 == segments.length) return; var vbuf = void 0, ibuf = void 0, uintbuf = void 0; var material = void 0; var offsetInfo = void 0; var vertices = frame.vertices; var indices = frame.indices; var uintVert = frame.uintVert; var frameVFOffset = 0, frameIndexOffset = 0, segVFCount = 0; if (worldMat) { _m00 = worldMat.m00; _m04 = worldMat.m04; _m12 = worldMat.m12; _m01 = worldMat.m01; _m05 = worldMat.m05; _m13 = worldMat.m13; } var colorOffset = 0; var colors = frame.colors; var nowColor = colors[colorOffset++]; var maxVFOffset = 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._hash !== _renderer.material._hash) { _mustFlush = false; _renderer._flush(); _renderer.node = _node; _renderer.material = material; } _vertexCount = segInfo.vertexCount; _indexCount = segInfo.indexCount; _vertexFloatCount = _vertexCount * _perVertexSize; offsetInfo = _buffer.request(_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 = segInfo.vfCount; switch (_handleVal) { case NOT_BATCH_ONE_COLOR: for (var _ii3 = _vfOffset, _il = _vfOffset + _vertexFloatCount; _ii3 < _il; ) { vbuf[_ii3++] = vertices[frameVFOffset++]; vbuf[_ii3++] = vertices[frameVFOffset++]; vbuf[_ii3++] = vertices[frameVFOffset++]; vbuf[_ii3++] = vertices[frameVFOffset++]; uintbuf[_ii3++] = uintVert[frameVFOffset++]; frameVFOffset++; } break; case NOT_BATCH_TWO_COLOR: vbuf.set(vertices.subarray(frameVFOffset, frameVFOffset + _vertexFloatCount), _vfOffset); frameVFOffset += _vertexFloatCount; break; case BATCH_ONE_COLOR: for (var _ii4 = _vfOffset, _il2 = _vfOffset + _vertexFloatCount; _ii4 < _il2; ) { _x = vertices[frameVFOffset++]; _y = vertices[frameVFOffset++]; vbuf[_ii4++] = _x * _m00 + _y * _m04 + _m12; vbuf[_ii4++] = _x * _m01 + _y * _m05 + _m13; vbuf[_ii4++] = vertices[frameVFOffset++]; vbuf[_ii4++] = vertices[frameVFOffset++]; uintbuf[_ii4++] = uintVert[frameVFOffset++]; frameVFOffset++; } break; case BATCH_TWO_COLOR: for (var _ii5 = _vfOffset, _il3 = _vfOffset + _vertexFloatCount; _ii5 < _il3; ) { _x = vertices[frameVFOffset++]; _y = vertices[frameVFOffset++]; vbuf[_ii5++] = _x * _m00 + _y * _m04 + _m12; vbuf[_ii5++] = _x * _m01 + _y * _m05 + _m13; vbuf[_ii5++] = vertices[frameVFOffset++]; vbuf[_ii5++] = vertices[frameVFOffset++]; uintbuf[_ii5++] = uintVert[frameVFOffset++]; uintbuf[_ii5++] = uintVert[frameVFOffset++]; } } _buffer.adjust(_vertexCount, _indexCount); if (!_needColor) continue; var frameColorOffset = frameVFOffset - segVFCount; for (var _ii6 = _vfOffset + 4, _il4 = _vfOffset + 4 + _vertexFloatCount; _ii6 < _il4; _ii6 += _perVertexSize, frameColorOffset += 6) { if (frameColorOffset >= maxVFOffset) { nowColor = colors[colorOffset++]; _handleColor(nowColor); maxVFOffset = nowColor.vfOffset; } uintbuf[_ii6] = _finalColor32; _useTint && (uintbuf[_ii6 + 1] = _darkColor32); } } }, fillBuffers: function(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; _useTint = comp.useTint; _vertexFormat = _useTint ? VFTwoColor : VFOneColor; _perVertexSize = _useTint ? 6 : 5; _node = comp.node; _buffer = renderer.getBuffer("spine", _vertexFormat); _renderer = renderer; _comp = comp; _mustFlush = true; _premultipliedAlpha = comp.premultipliedAlpha; _multiplier = 1; _handleVal = 0; _needColor = false; (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; } comp.isAnimationCached() ? this.cacheTraverse(worldMat) : this.realTimeTraverse(worldMat); _node = void 0; _buffer = void 0; _renderer = void 0; _comp = void 0; } }; Skeleton._assembler = spineAssembler; module.exports = spineAssembler; }), { "../../cocos2d/core/renderer": 202, "../../cocos2d/core/renderer/render-flow": 204, "../../cocos2d/core/renderer/webgl/vertex-format": 233, "./Skeleton": 289, "./lib/spine": void 0 } ], 294: [ (function(require, module, exports) { var TrackEntryListeners = function() { 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; }), {} ], 295: [ (function(require, module, exports) { (function(global, factory) { "object" === (__typeofVal = typeof exports, "object" === __typeofVal ? __realTypeOfObj(exports) : __typeofVal) && "undefined" !== (__typeofVal = typeof module, "object" === __typeofVal ? __realTypeOfObj(module) : __typeofVal) ? factory(exports) : "function" === (__typeofVal = typeof define, "object" === __typeofVal ? __realTypeOfObj(define) : __typeofVal) && define.amd ? define([ "exports" ], factory) : factory(global.box2d = {}); })(this, (function(exports) { "use strict"; function b2Assert(condition) { var args = []; for (var _i = 1; _i < arguments.length; _i++) args[_i - 1] = arguments[_i]; if (!condition) throw new (Error.bind.apply(Error, [ void 0 ].concat(args)))(); } function b2Maybe(value, def) { return void 0 !== value ? value : def; } var b2_maxFloat = 1e37; var b2_epsilon = 1e-5; var b2_epsilon_sq = b2_epsilon * b2_epsilon; var b2_pi = 3.14159265359; var b2_maxManifoldPoints = 2; var b2_maxPolygonVertices = 8; var b2_aabbExtension = .1; var b2_aabbMultiplier = 2; var b2_linearSlop = .008; var b2_angularSlop = 2 / 180 * b2_pi; var b2_polygonRadius = 2 * b2_linearSlop; var b2_maxSubSteps = 8; var b2_maxTOIContacts = 32; var b2_velocityThreshold = 1; var b2_maxLinearCorrection = .2; var b2_maxAngularCorrection = 8 / 180 * b2_pi; var b2_maxTranslation = 2; var b2_maxTranslationSquared = b2_maxTranslation * b2_maxTranslation; var b2_maxRotation = .5 * b2_pi; var b2_maxRotationSquared = b2_maxRotation * b2_maxRotation; var b2_baumgarte = .2; var b2_toiBaumgarte = .75; var b2_invalidParticleIndex = -1; var b2_maxParticleIndex = 2147483647; var b2_particleStride = .75; var b2_minParticleWeight = 1; var b2_maxParticlePressure = .25; var b2_maxParticleForce = .5; var b2_maxTriadDistance = 2; var b2_maxTriadDistanceSquared = b2_maxTriadDistance * b2_maxTriadDistance; var b2_minParticleSystemBufferCapacity = 256; var b2_barrierCollisionTime = 2.5; var b2_timeToSleep = .5; var b2_linearSleepTolerance = .01; var b2_angularSleepTolerance = 2 / 180 * b2_pi; function b2Alloc(size) { return null; } function b2Free(mem) {} function b2Log(message) { var args = []; for (var _i = 1; _i < arguments.length; _i++) args[_i - 1] = arguments[_i]; } var b2Version = (function() { function b2Version(major, minor, revision) { void 0 === major && (major = 0); void 0 === minor && (minor = 0); void 0 === revision && (revision = 0); this.major = 0; this.minor = 0; this.revision = 0; this.major = major; this.minor = minor; this.revision = revision; } b2Version.prototype.toString = function() { return this.major + "." + this.minor + "." + this.revision; }; return b2Version; })(); var b2_version = new b2Version(2, 3, 2); var b2_branch = "master"; var b2_commit = "fbf51801d80fc389d43dc46524520e89043b6faf"; function b2ParseInt(v) { return parseInt(v, 10); } function b2ParseUInt(v) { return Math.abs(parseInt(v, 10)); } function b2MakeArray(length, init) { var a = []; for (var i = 0; i < length; ++i) a.push(init(i)); return a; } function b2MakeNullArray(length) { var a = []; for (var i = 0; i < length; ++i) a.push(null); return a; } function b2MakeNumberArray(length, init) { void 0 === init && (init = 0); var a = []; for (var i = 0; i < length; ++i) a.push(init); return a; } var b2_pi_over_180 = b2_pi / 180; var b2_180_over_pi = 180 / b2_pi; var b2_two_pi = 2 * b2_pi; var b2Abs = Math.abs; var b2Min = Math.min; var b2Max = Math.max; function b2Clamp(a, lo, hi) { return a < lo ? lo : a > hi ? hi : a; } function b2Swap(a, b) { var tmp = a[0]; a[0] = b[0]; b[0] = tmp; } var b2IsValid = isFinite; function b2Sq(n) { return n * n; } function b2InvSqrt(n) { return 1 / Math.sqrt(n); } var b2Sqrt = Math.sqrt; var b2Pow = Math.pow; function b2DegToRad(degrees) { return degrees * b2_pi_over_180; } function b2RadToDeg(radians) { return radians * b2_180_over_pi; } var b2Cos = Math.cos; var b2Sin = Math.sin; var b2Acos = Math.acos; var b2Asin = Math.asin; var b2Atan2 = Math.atan2; function b2NextPowerOfTwo(x) { x |= x >> 1 & 2147483647; x |= x >> 2 & 1073741823; x |= x >> 4 & 268435455; x |= x >> 8 & 16777215; x |= x >> 16 & 65535; return x + 1; } function b2IsPowerOfTwo(x) { return x > 0 && 0 === (x & x - 1); } function b2Random() { return 2 * Math.random() - 1; } function b2RandomRange(lo, hi) { return (hi - lo) * Math.random() + lo; } var b2Vec2 = (function() { function b2Vec2(x, y) { void 0 === x && (x = 0); void 0 === y && (y = 0); this.x = x; this.y = y; } b2Vec2.prototype.Clone = function() { return new b2Vec2(this.x, this.y); }; b2Vec2.prototype.SetZero = function() { this.x = 0; this.y = 0; return this; }; b2Vec2.prototype.Set = function(x, y) { this.x = x; this.y = y; return this; }; b2Vec2.prototype.Copy = function(other) { this.x = other.x; this.y = other.y; return this; }; b2Vec2.prototype.SelfAdd = function(v) { this.x += v.x; this.y += v.y; return this; }; b2Vec2.prototype.SelfAddXY = function(x, y) { this.x += x; this.y += y; return this; }; b2Vec2.prototype.SelfSub = function(v) { this.x -= v.x; this.y -= v.y; return this; }; b2Vec2.prototype.SelfSubXY = function(x, y) { this.x -= x; this.y -= y; return this; }; b2Vec2.prototype.SelfMul = function(s) { this.x *= s; this.y *= s; return this; }; b2Vec2.prototype.SelfMulAdd = function(s, v) { this.x += s * v.x; this.y += s * v.y; return this; }; b2Vec2.prototype.SelfMulSub = function(s, v) { this.x -= s * v.x; this.y -= s * v.y; return this; }; b2Vec2.prototype.Dot = function(v) { return this.x * v.x + this.y * v.y; }; b2Vec2.prototype.Cross = function(v) { return this.x * v.y - this.y * v.x; }; b2Vec2.prototype.Length = function() { var x = this.x, y = this.y; return Math.sqrt(x * x + y * y); }; b2Vec2.prototype.LengthSquared = function() { var x = this.x, y = this.y; return x * x + y * y; }; b2Vec2.prototype.Normalize = function() { var length = this.Length(); if (length >= b2_epsilon) { var inv_length = 1 / length; this.x *= inv_length; this.y *= inv_length; } return length; }; b2Vec2.prototype.SelfNormalize = function() { var length = this.Length(); if (length >= b2_epsilon) { var inv_length = 1 / length; this.x *= inv_length; this.y *= inv_length; } return this; }; b2Vec2.prototype.SelfRotate = function(radians) { var c = Math.cos(radians); var s = Math.sin(radians); var x = this.x; this.x = c * x - s * this.y; this.y = s * x + c * this.y; return this; }; b2Vec2.prototype.IsValid = function() { return isFinite(this.x) && isFinite(this.y); }; b2Vec2.prototype.SelfCrossVS = function(s) { var x = this.x; this.x = s * this.y; this.y = -s * x; return this; }; b2Vec2.prototype.SelfCrossSV = function(s) { var x = this.x; this.x = -s * this.y; this.y = s * x; return this; }; b2Vec2.prototype.SelfMinV = function(v) { this.x = b2Min(this.x, v.x); this.y = b2Min(this.y, v.y); return this; }; b2Vec2.prototype.SelfMaxV = function(v) { this.x = b2Max(this.x, v.x); this.y = b2Max(this.y, v.y); return this; }; b2Vec2.prototype.SelfAbs = function() { this.x = b2Abs(this.x); this.y = b2Abs(this.y); return this; }; b2Vec2.prototype.SelfNeg = function() { this.x = -this.x; this.y = -this.y; return this; }; b2Vec2.prototype.SelfSkew = function() { var x = this.x; this.x = -this.y; this.y = x; return this; }; b2Vec2.MakeArray = function(length) { return b2MakeArray(length, (function(i) { return new b2Vec2(); })); }; b2Vec2.AbsV = function(v, out) { out.x = b2Abs(v.x); out.y = b2Abs(v.y); return out; }; b2Vec2.MinV = function(a, b, out) { out.x = b2Min(a.x, b.x); out.y = b2Min(a.y, b.y); return out; }; b2Vec2.MaxV = function(a, b, out) { out.x = b2Max(a.x, b.x); out.y = b2Max(a.y, b.y); return out; }; b2Vec2.ClampV = function(v, lo, hi, out) { out.x = b2Clamp(v.x, lo.x, hi.x); out.y = b2Clamp(v.y, lo.y, hi.y); return out; }; b2Vec2.RotateV = function(v, radians, out) { var v_x = v.x, v_y = v.y; var c = Math.cos(radians); var s = Math.sin(radians); out.x = c * v_x - s * v_y; out.y = s * v_x + c * v_y; return out; }; b2Vec2.DotVV = function(a, b) { return a.x * b.x + a.y * b.y; }; b2Vec2.CrossVV = function(a, b) { return a.x * b.y - a.y * b.x; }; b2Vec2.CrossVS = function(v, s, out) { var v_x = v.x; out.x = s * v.y; out.y = -s * v_x; return out; }; b2Vec2.CrossVOne = function(v, out) { var v_x = v.x; out.x = v.y; out.y = -v_x; return out; }; b2Vec2.CrossSV = function(s, v, out) { var v_x = v.x; out.x = -s * v.y; out.y = s * v_x; return out; }; b2Vec2.CrossOneV = function(v, out) { var v_x = v.x; out.x = -v.y; out.y = v_x; return out; }; b2Vec2.AddVV = function(a, b, out) { out.x = a.x + b.x; out.y = a.y + b.y; return out; }; b2Vec2.SubVV = function(a, b, out) { out.x = a.x - b.x; out.y = a.y - b.y; return out; }; b2Vec2.MulSV = function(s, v, out) { out.x = v.x * s; out.y = v.y * s; return out; }; b2Vec2.MulVS = function(v, s, out) { out.x = v.x * s; out.y = v.y * s; return out; }; b2Vec2.AddVMulSV = function(a, s, b, out) { out.x = a.x + s * b.x; out.y = a.y + s * b.y; return out; }; b2Vec2.SubVMulSV = function(a, s, b, out) { out.x = a.x - s * b.x; out.y = a.y - s * b.y; return out; }; b2Vec2.AddVCrossSV = function(a, s, v, out) { var v_x = v.x; out.x = a.x - s * v.y; out.y = a.y + s * v_x; return out; }; b2Vec2.MidVV = function(a, b, out) { out.x = .5 * (a.x + b.x); out.y = .5 * (a.y + b.y); return out; }; b2Vec2.ExtVV = function(a, b, out) { out.x = .5 * (b.x - a.x); out.y = .5 * (b.y - a.y); return out; }; b2Vec2.IsEqualToV = function(a, b) { return a.x === b.x && a.y === b.y; }; b2Vec2.DistanceVV = function(a, b) { var c_x = a.x - b.x; var c_y = a.y - b.y; return Math.sqrt(c_x * c_x + c_y * c_y); }; b2Vec2.DistanceSquaredVV = function(a, b) { var c_x = a.x - b.x; var c_y = a.y - b.y; return c_x * c_x + c_y * c_y; }; b2Vec2.NegV = function(v, out) { out.x = -v.x; out.y = -v.y; return out; }; b2Vec2.ZERO = new b2Vec2(0, 0); b2Vec2.UNITX = new b2Vec2(1, 0); b2Vec2.UNITY = new b2Vec2(0, 1); b2Vec2.s_t0 = new b2Vec2(); b2Vec2.s_t1 = new b2Vec2(); b2Vec2.s_t2 = new b2Vec2(); b2Vec2.s_t3 = new b2Vec2(); return b2Vec2; })(); var b2Vec2_zero = new b2Vec2(0, 0); var b2Vec3 = (function() { function b2Vec3(x, y, z) { void 0 === x && (x = 0); void 0 === y && (y = 0); void 0 === z && (z = 0); this.x = x; this.y = y; this.z = z; } b2Vec3.prototype.Clone = function() { return new b2Vec3(this.x, this.y, this.z); }; b2Vec3.prototype.SetZero = function() { this.x = 0; this.y = 0; this.z = 0; return this; }; b2Vec3.prototype.SetXYZ = function(x, y, z) { this.x = x; this.y = y; this.z = z; return this; }; b2Vec3.prototype.Copy = function(other) { this.x = other.x; this.y = other.y; this.z = other.z; return this; }; b2Vec3.prototype.SelfNeg = function() { this.x = -this.x; this.y = -this.y; this.z = -this.z; return this; }; b2Vec3.prototype.SelfAdd = function(v) { this.x += v.x; this.y += v.y; this.z += v.z; return this; }; b2Vec3.prototype.SelfAddXYZ = function(x, y, z) { this.x += x; this.y += y; this.z += z; return this; }; b2Vec3.prototype.SelfSub = function(v) { this.x -= v.x; this.y -= v.y; this.z -= v.z; return this; }; b2Vec3.prototype.SelfSubXYZ = function(x, y, z) { this.x -= x; this.y -= y; this.z -= z; return this; }; b2Vec3.prototype.SelfMul = function(s) { this.x *= s; this.y *= s; this.z *= s; return this; }; b2Vec3.DotV3V3 = function(a, b) { return a.x * b.x + a.y * b.y + a.z * b.z; }; b2Vec3.CrossV3V3 = function(a, b, out) { var a_x = a.x, a_y = a.y, a_z = a.z; var b_x = b.x, b_y = b.y, b_z = b.z; out.x = a_y * b_z - a_z * b_y; out.y = a_z * b_x - a_x * b_z; out.z = a_x * b_y - a_y * b_x; return out; }; b2Vec3.ZERO = new b2Vec3(0, 0, 0); b2Vec3.s_t0 = new b2Vec3(); return b2Vec3; })(); var b2Mat22 = (function() { function b2Mat22() { this.ex = new b2Vec2(1, 0); this.ey = new b2Vec2(0, 1); } b2Mat22.prototype.Clone = function() { return new b2Mat22().Copy(this); }; b2Mat22.FromVV = function(c1, c2) { return new b2Mat22().SetVV(c1, c2); }; b2Mat22.FromSSSS = function(r1c1, r1c2, r2c1, r2c2) { return new b2Mat22().SetSSSS(r1c1, r1c2, r2c1, r2c2); }; b2Mat22.FromAngle = function(radians) { return new b2Mat22().SetAngle(radians); }; b2Mat22.prototype.SetSSSS = function(r1c1, r1c2, r2c1, r2c2) { this.ex.Set(r1c1, r2c1); this.ey.Set(r1c2, r2c2); return this; }; b2Mat22.prototype.SetVV = function(c1, c2) { this.ex.Copy(c1); this.ey.Copy(c2); return this; }; b2Mat22.prototype.SetAngle = function(radians) { var c = Math.cos(radians); var s = Math.sin(radians); this.ex.Set(c, s); this.ey.Set(-s, c); return this; }; b2Mat22.prototype.Copy = function(other) { this.ex.Copy(other.ex); this.ey.Copy(other.ey); return this; }; b2Mat22.prototype.SetIdentity = function() { this.ex.Set(1, 0); this.ey.Set(0, 1); return this; }; b2Mat22.prototype.SetZero = function() { this.ex.SetZero(); this.ey.SetZero(); return this; }; b2Mat22.prototype.GetAngle = function() { return Math.atan2(this.ex.y, this.ex.x); }; b2Mat22.prototype.GetInverse = function(out) { var a = this.ex.x; var b = this.ey.x; var c = this.ex.y; var d = this.ey.y; var det = a * d - b * c; 0 !== det && (det = 1 / det); out.ex.x = det * d; out.ey.x = -det * b; out.ex.y = -det * c; out.ey.y = det * a; return out; }; b2Mat22.prototype.Solve = function(b_x, b_y, out) { var a11 = this.ex.x, a12 = this.ey.x; var a21 = this.ex.y, a22 = this.ey.y; var det = a11 * a22 - a12 * a21; 0 !== det && (det = 1 / det); out.x = det * (a22 * b_x - a12 * b_y); out.y = det * (a11 * b_y - a21 * b_x); return out; }; b2Mat22.prototype.SelfAbs = function() { this.ex.SelfAbs(); this.ey.SelfAbs(); return this; }; b2Mat22.prototype.SelfInv = function() { this.GetInverse(this); return this; }; b2Mat22.prototype.SelfAddM = function(M) { this.ex.SelfAdd(M.ex); this.ey.SelfAdd(M.ey); return this; }; b2Mat22.prototype.SelfSubM = function(M) { this.ex.SelfSub(M.ex); this.ey.SelfSub(M.ey); return this; }; b2Mat22.AbsM = function(M, out) { var M_ex = M.ex, M_ey = M.ey; out.ex.x = b2Abs(M_ex.x); out.ex.y = b2Abs(M_ex.y); out.ey.x = b2Abs(M_ey.x); out.ey.y = b2Abs(M_ey.y); return out; }; b2Mat22.MulMV = function(M, v, out) { var M_ex = M.ex, M_ey = M.ey; var v_x = v.x, v_y = v.y; out.x = M_ex.x * v_x + M_ey.x * v_y; out.y = M_ex.y * v_x + M_ey.y * v_y; return out; }; b2Mat22.MulTMV = function(M, v, out) { var M_ex = M.ex, M_ey = M.ey; var v_x = v.x, v_y = v.y; out.x = M_ex.x * v_x + M_ex.y * v_y; out.y = M_ey.x * v_x + M_ey.y * v_y; return out; }; b2Mat22.AddMM = function(A, B, out) { var A_ex = A.ex, A_ey = A.ey; var B_ex = B.ex, B_ey = B.ey; out.ex.x = A_ex.x + B_ex.x; out.ex.y = A_ex.y + B_ex.y; out.ey.x = A_ey.x + B_ey.x; out.ey.y = A_ey.y + B_ey.y; return out; }; b2Mat22.MulMM = function(A, B, out) { var A_ex_x = A.ex.x, A_ex_y = A.ex.y; var A_ey_x = A.ey.x, A_ey_y = A.ey.y; var B_ex_x = B.ex.x, B_ex_y = B.ex.y; var B_ey_x = B.ey.x, B_ey_y = B.ey.y; out.ex.x = A_ex_x * B_ex_x + A_ey_x * B_ex_y; out.ex.y = A_ex_y * B_ex_x + A_ey_y * B_ex_y; out.ey.x = A_ex_x * B_ey_x + A_ey_x * B_ey_y; out.ey.y = A_ex_y * B_ey_x + A_ey_y * B_ey_y; return out; }; b2Mat22.MulTMM = function(A, B, out) { var A_ex_x = A.ex.x, A_ex_y = A.ex.y; var A_ey_x = A.ey.x, A_ey_y = A.ey.y; var B_ex_x = B.ex.x, B_ex_y = B.ex.y; var B_ey_x = B.ey.x, B_ey_y = B.ey.y; out.ex.x = A_ex_x * B_ex_x + A_ex_y * B_ex_y; out.ex.y = A_ey_x * B_ex_x + A_ey_y * B_ex_y; out.ey.x = A_ex_x * B_ey_x + A_ex_y * B_ey_y; out.ey.y = A_ey_x * B_ey_x + A_ey_y * B_ey_y; return out; }; b2Mat22.IDENTITY = new b2Mat22(); return b2Mat22; })(); var b2Mat33 = (function() { function b2Mat33() { this.ex = new b2Vec3(1, 0, 0); this.ey = new b2Vec3(0, 1, 0); this.ez = new b2Vec3(0, 0, 1); } b2Mat33.prototype.Clone = function() { return new b2Mat33().Copy(this); }; b2Mat33.prototype.SetVVV = function(c1, c2, c3) { this.ex.Copy(c1); this.ey.Copy(c2); this.ez.Copy(c3); return this; }; b2Mat33.prototype.Copy = function(other) { this.ex.Copy(other.ex); this.ey.Copy(other.ey); this.ez.Copy(other.ez); return this; }; b2Mat33.prototype.SetIdentity = function() { this.ex.SetXYZ(1, 0, 0); this.ey.SetXYZ(0, 1, 0); this.ez.SetXYZ(0, 0, 1); return this; }; b2Mat33.prototype.SetZero = function() { this.ex.SetZero(); this.ey.SetZero(); this.ez.SetZero(); return this; }; b2Mat33.prototype.SelfAddM = function(M) { this.ex.SelfAdd(M.ex); this.ey.SelfAdd(M.ey); this.ez.SelfAdd(M.ez); return this; }; b2Mat33.prototype.Solve33 = function(b_x, b_y, b_z, out) { var a11 = this.ex.x, a21 = this.ex.y, a31 = this.ex.z; var a12 = this.ey.x, a22 = this.ey.y, a32 = this.ey.z; var a13 = this.ez.x, a23 = this.ez.y, a33 = this.ez.z; var det = a11 * (a22 * a33 - a32 * a23) + a21 * (a32 * a13 - a12 * a33) + a31 * (a12 * a23 - a22 * a13); 0 !== det && (det = 1 / det); out.x = det * (b_x * (a22 * a33 - a32 * a23) + b_y * (a32 * a13 - a12 * a33) + b_z * (a12 * a23 - a22 * a13)); out.y = det * (a11 * (b_y * a33 - b_z * a23) + a21 * (b_z * a13 - b_x * a33) + a31 * (b_x * a23 - b_y * a13)); out.z = det * (a11 * (a22 * b_z - a32 * b_y) + a21 * (a32 * b_x - a12 * b_z) + a31 * (a12 * b_y - a22 * b_x)); return out; }; b2Mat33.prototype.Solve22 = function(b_x, b_y, out) { var a11 = this.ex.x, a12 = this.ey.x; var a21 = this.ex.y, a22 = this.ey.y; var det = a11 * a22 - a12 * a21; 0 !== det && (det = 1 / det); out.x = det * (a22 * b_x - a12 * b_y); out.y = det * (a11 * b_y - a21 * b_x); return out; }; b2Mat33.prototype.GetInverse22 = function(M) { var a = this.ex.x, b = this.ey.x, c = this.ex.y, d = this.ey.y; var det = a * d - b * c; 0 !== det && (det = 1 / det); M.ex.x = det * d; M.ey.x = -det * b; M.ex.z = 0; M.ex.y = -det * c; M.ey.y = det * a; M.ey.z = 0; M.ez.x = 0; M.ez.y = 0; M.ez.z = 0; }; b2Mat33.prototype.GetSymInverse33 = function(M) { var det = b2Vec3.DotV3V3(this.ex, b2Vec3.CrossV3V3(this.ey, this.ez, b2Vec3.s_t0)); 0 !== det && (det = 1 / det); var a11 = this.ex.x, a12 = this.ey.x, a13 = this.ez.x; var a22 = this.ey.y, a23 = this.ez.y; var a33 = this.ez.z; M.ex.x = det * (a22 * a33 - a23 * a23); M.ex.y = det * (a13 * a23 - a12 * a33); M.ex.z = det * (a12 * a23 - a13 * a22); M.ey.x = M.ex.y; M.ey.y = det * (a11 * a33 - a13 * a13); M.ey.z = det * (a13 * a12 - a11 * a23); M.ez.x = M.ex.z; M.ez.y = M.ey.z; M.ez.z = det * (a11 * a22 - a12 * a12); }; b2Mat33.MulM33V3 = function(A, v, out) { var v_x = v.x, v_y = v.y, v_z = v.z; out.x = A.ex.x * v_x + A.ey.x * v_y + A.ez.x * v_z; out.y = A.ex.y * v_x + A.ey.y * v_y + A.ez.y * v_z; out.z = A.ex.z * v_x + A.ey.z * v_y + A.ez.z * v_z; return out; }; b2Mat33.MulM33XYZ = function(A, x, y, z, out) { out.x = A.ex.x * x + A.ey.x * y + A.ez.x * z; out.y = A.ex.y * x + A.ey.y * y + A.ez.y * z; out.z = A.ex.z * x + A.ey.z * y + A.ez.z * z; return out; }; b2Mat33.MulM33V2 = function(A, v, out) { var v_x = v.x, v_y = v.y; out.x = A.ex.x * v_x + A.ey.x * v_y; out.y = A.ex.y * v_x + A.ey.y * v_y; return out; }; b2Mat33.MulM33XY = function(A, x, y, out) { out.x = A.ex.x * x + A.ey.x * y; out.y = A.ex.y * x + A.ey.y * y; return out; }; b2Mat33.IDENTITY = new b2Mat33(); return b2Mat33; })(); var b2Rot = (function() { function b2Rot(angle) { void 0 === angle && (angle = 0); this.s = 0; this.c = 1; if (angle) { this.s = Math.sin(angle); this.c = Math.cos(angle); } } b2Rot.prototype.Clone = function() { return new b2Rot().Copy(this); }; b2Rot.prototype.Copy = function(other) { this.s = other.s; this.c = other.c; return this; }; b2Rot.prototype.SetAngle = function(angle) { this.s = Math.sin(angle); this.c = Math.cos(angle); return this; }; b2Rot.prototype.SetIdentity = function() { this.s = 0; this.c = 1; return this; }; b2Rot.prototype.GetAngle = function() { return Math.atan2(this.s, this.c); }; b2Rot.prototype.GetXAxis = function(out) { out.x = this.c; out.y = this.s; return out; }; b2Rot.prototype.GetYAxis = function(out) { out.x = -this.s; out.y = this.c; return out; }; b2Rot.MulRR = function(q, r, out) { var q_c = q.c, q_s = q.s; var r_c = r.c, r_s = r.s; out.s = q_s * r_c + q_c * r_s; out.c = q_c * r_c - q_s * r_s; return out; }; b2Rot.MulTRR = function(q, r, out) { var q_c = q.c, q_s = q.s; var r_c = r.c, r_s = r.s; out.s = q_c * r_s - q_s * r_c; out.c = q_c * r_c + q_s * r_s; return out; }; b2Rot.MulRV = function(q, v, out) { var q_c = q.c, q_s = q.s; var v_x = v.x, v_y = v.y; out.x = q_c * v_x - q_s * v_y; out.y = q_s * v_x + q_c * v_y; return out; }; b2Rot.MulTRV = function(q, v, out) { var q_c = q.c, q_s = q.s; var v_x = v.x, v_y = v.y; out.x = q_c * v_x + q_s * v_y; out.y = -q_s * v_x + q_c * v_y; return out; }; b2Rot.IDENTITY = new b2Rot(); return b2Rot; })(); var b2Transform = (function() { function b2Transform() { this.p = new b2Vec2(); this.q = new b2Rot(); } b2Transform.prototype.Clone = function() { return new b2Transform().Copy(this); }; b2Transform.prototype.Copy = function(other) { this.p.Copy(other.p); this.q.Copy(other.q); return this; }; b2Transform.prototype.SetIdentity = function() { this.p.SetZero(); this.q.SetIdentity(); return this; }; b2Transform.prototype.SetPositionRotation = function(position, q) { this.p.Copy(position); this.q.Copy(q); return this; }; b2Transform.prototype.SetPositionAngle = function(pos, a) { this.p.Copy(pos); this.q.SetAngle(a); return this; }; b2Transform.prototype.SetPosition = function(position) { this.p.Copy(position); return this; }; b2Transform.prototype.SetPositionXY = function(x, y) { this.p.Set(x, y); return this; }; b2Transform.prototype.SetRotation = function(rotation) { this.q.Copy(rotation); return this; }; b2Transform.prototype.SetRotationAngle = function(radians) { this.q.SetAngle(radians); return this; }; b2Transform.prototype.GetPosition = function() { return this.p; }; b2Transform.prototype.GetRotation = function() { return this.q; }; b2Transform.prototype.GetRotationAngle = function() { return this.q.GetAngle(); }; b2Transform.prototype.GetAngle = function() { return this.q.GetAngle(); }; b2Transform.MulXV = function(T, v, out) { var T_q_c = T.q.c, T_q_s = T.q.s; var v_x = v.x, v_y = v.y; out.x = T_q_c * v_x - T_q_s * v_y + T.p.x; out.y = T_q_s * v_x + T_q_c * v_y + T.p.y; return out; }; b2Transform.MulTXV = function(T, v, out) { var T_q_c = T.q.c, T_q_s = T.q.s; var p_x = v.x - T.p.x; var p_y = v.y - T.p.y; out.x = T_q_c * p_x + T_q_s * p_y; out.y = -T_q_s * p_x + T_q_c * p_y; return out; }; b2Transform.MulXX = function(A, B, out) { b2Rot.MulRR(A.q, B.q, out.q); b2Vec2.AddVV(b2Rot.MulRV(A.q, B.p, out.p), A.p, out.p); return out; }; b2Transform.MulTXX = function(A, B, out) { b2Rot.MulTRR(A.q, B.q, out.q); b2Rot.MulTRV(A.q, b2Vec2.SubVV(B.p, A.p, out.p), out.p); return out; }; b2Transform.IDENTITY = new b2Transform(); return b2Transform; })(); var b2Sweep = (function() { function b2Sweep() { this.localCenter = new b2Vec2(); this.c0 = new b2Vec2(); this.c = new b2Vec2(); this.a0 = 0; this.a = 0; this.alpha0 = 0; } b2Sweep.prototype.Clone = function() { return new b2Sweep().Copy(this); }; b2Sweep.prototype.Copy = function(other) { this.localCenter.Copy(other.localCenter); this.c0.Copy(other.c0); this.c.Copy(other.c); this.a0 = other.a0; this.a = other.a; this.alpha0 = other.alpha0; return this; }; b2Sweep.prototype.GetTransform = function(xf, beta) { var one_minus_beta = 1 - beta; xf.p.x = one_minus_beta * this.c0.x + beta * this.c.x; xf.p.y = one_minus_beta * this.c0.y + beta * this.c.y; var angle = one_minus_beta * this.a0 + beta * this.a; xf.q.SetAngle(angle); xf.p.SelfSub(b2Rot.MulRV(xf.q, this.localCenter, b2Vec2.s_t0)); return xf; }; b2Sweep.prototype.Advance = function(alpha) { var beta = (alpha - this.alpha0) / (1 - this.alpha0); var one_minus_beta = 1 - beta; this.c0.x = one_minus_beta * this.c0.x + beta * this.c.x; this.c0.y = one_minus_beta * this.c0.y + beta * this.c.y; this.a0 = one_minus_beta * this.a0 + beta * this.a; this.alpha0 = alpha; }; b2Sweep.prototype.Normalize = function() { var d = b2_two_pi * Math.floor(this.a0 / b2_two_pi); this.a0 -= d; this.a -= d; }; return b2Sweep; })(); var b2Color = (function() { function b2Color(rr, gg, bb, aa) { void 0 === rr && (rr = .5); void 0 === gg && (gg = .5); void 0 === bb && (bb = .5); void 0 === aa && (aa = 1); this.r = rr; this.g = gg; this.b = bb; this.a = aa; } b2Color.prototype.Clone = function() { return new b2Color().Copy(this); }; b2Color.prototype.Copy = function(other) { this.r = other.r; this.g = other.g; this.b = other.b; this.a = other.a; return this; }; b2Color.prototype.IsEqual = function(color) { return this.r === color.r && this.g === color.g && this.b === color.b && this.a === color.a; }; b2Color.prototype.IsZero = function() { return 0 === this.r && 0 === this.g && 0 === this.b && 0 === this.a; }; b2Color.prototype.Set = function(r, g, b, a) { void 0 === a && (a = this.a); this.SetRGBA(r, g, b, a); }; b2Color.prototype.SetByteRGB = function(r, g, b) { this.r = r / 255; this.g = g / 255; this.b = b / 255; return this; }; b2Color.prototype.SetByteRGBA = function(r, g, b, a) { this.r = r / 255; this.g = g / 255; this.b = b / 255; this.a = a / 255; return this; }; b2Color.prototype.SetRGB = function(rr, gg, bb) { this.r = rr; this.g = gg; this.b = bb; return this; }; b2Color.prototype.SetRGBA = function(rr, gg, bb, aa) { this.r = rr; this.g = gg; this.b = bb; this.a = aa; return this; }; b2Color.prototype.SelfAdd = function(color) { this.r += color.r; this.g += color.g; this.b += color.b; this.a += color.a; return this; }; b2Color.prototype.Add = function(color, out) { out.r = this.r + color.r; out.g = this.g + color.g; out.b = this.b + color.b; out.a = this.a + color.a; return out; }; b2Color.prototype.SelfSub = function(color) { this.r -= color.r; this.g -= color.g; this.b -= color.b; this.a -= color.a; return this; }; b2Color.prototype.Sub = function(color, out) { out.r = this.r - color.r; out.g = this.g - color.g; out.b = this.b - color.b; out.a = this.a - color.a; return out; }; b2Color.prototype.SelfMul = function(s) { this.r *= s; this.g *= s; this.b *= s; this.a *= s; return this; }; b2Color.prototype.Mul = function(s, out) { out.r = this.r * s; out.g = this.g * s; out.b = this.b * s; out.a = this.a * s; return out; }; b2Color.prototype.Mix = function(mixColor, strength) { b2Color.MixColors(this, mixColor, strength); }; b2Color.MixColors = function(colorA, colorB, strength) { var dr = strength * (colorB.r - colorA.r); var dg = strength * (colorB.g - colorA.g); var db = strength * (colorB.b - colorA.b); var da = strength * (colorB.a - colorA.a); colorA.r += dr; colorA.g += dg; colorA.b += db; colorA.a += da; colorB.r -= dr; colorB.g -= dg; colorB.b -= db; colorB.a -= da; }; b2Color.prototype.MakeStyleString = function(alpha) { void 0 === alpha && (alpha = this.a); return b2Color.MakeStyleString(this.r, this.g, this.b, alpha); }; b2Color.MakeStyleString = function(r, g, b, a) { void 0 === a && (a = 1); r *= 255; g *= 255; b *= 255; return a < 1 ? "rgba(" + r + "," + g + "," + b + "," + a + ")" : "rgb(" + r + "," + g + "," + b + ")"; }; b2Color.ZERO = new b2Color(0, 0, 0, 0); b2Color.RED = new b2Color(1, 0, 0); b2Color.GREEN = new b2Color(0, 1, 0); b2Color.BLUE = new b2Color(0, 0, 1); return b2Color; })(); (function(b2DrawFlags) { b2DrawFlags[b2DrawFlags["e_none"] = 0] = "e_none"; b2DrawFlags[b2DrawFlags["e_shapeBit"] = 1] = "e_shapeBit"; b2DrawFlags[b2DrawFlags["e_jointBit"] = 2] = "e_jointBit"; b2DrawFlags[b2DrawFlags["e_aabbBit"] = 4] = "e_aabbBit"; b2DrawFlags[b2DrawFlags["e_pairBit"] = 8] = "e_pairBit"; b2DrawFlags[b2DrawFlags["e_centerOfMassBit"] = 16] = "e_centerOfMassBit"; b2DrawFlags[b2DrawFlags["e_particleBit"] = 32] = "e_particleBit"; b2DrawFlags[b2DrawFlags["e_controllerBit"] = 64] = "e_controllerBit"; b2DrawFlags[b2DrawFlags["e_all"] = 63] = "e_all"; })(exports.b2DrawFlags || (exports.b2DrawFlags = {})); var b2Draw = (function() { function b2Draw() { this.m_drawFlags = 0; } b2Draw.prototype.SetFlags = function(flags) { this.m_drawFlags = flags; }; b2Draw.prototype.GetFlags = function() { return this.m_drawFlags; }; b2Draw.prototype.AppendFlags = function(flags) { this.m_drawFlags |= flags; }; b2Draw.prototype.ClearFlags = function(flags) { this.m_drawFlags &= ~flags; }; return b2Draw; })(); var b2Timer = (function() { function b2Timer() { this.m_start = Date.now(); } b2Timer.prototype.Reset = function() { this.m_start = Date.now(); return this; }; b2Timer.prototype.GetMilliseconds = function() { return Date.now() - this.m_start; }; return b2Timer; })(); var b2Counter = (function() { function b2Counter() { this.m_count = 0; this.m_min_count = 0; this.m_max_count = 0; } b2Counter.prototype.GetCount = function() { return this.m_count; }; b2Counter.prototype.GetMinCount = function() { return this.m_min_count; }; b2Counter.prototype.GetMaxCount = function() { return this.m_max_count; }; b2Counter.prototype.ResetCount = function() { var count = this.m_count; this.m_count = 0; return count; }; b2Counter.prototype.ResetMinCount = function() { this.m_min_count = 0; }; b2Counter.prototype.ResetMaxCount = function() { this.m_max_count = 0; }; b2Counter.prototype.Increment = function() { this.m_count++; this.m_max_count < this.m_count && (this.m_max_count = this.m_count); }; b2Counter.prototype.Decrement = function() { this.m_count--; this.m_min_count > this.m_count && (this.m_min_count = this.m_count); }; return b2Counter; })(); var b2GrowableStack = (function() { function b2GrowableStack(N) { this.m_stack = []; this.m_count = 0; this.m_stack = b2MakeArray(N, (function(index) { return null; })); this.m_count = 0; } b2GrowableStack.prototype.Reset = function() { this.m_count = 0; return this; }; b2GrowableStack.prototype.Push = function(element) { this.m_stack[this.m_count] = element; this.m_count++; }; b2GrowableStack.prototype.Pop = function() { this.m_count--; var element = this.m_stack[this.m_count]; this.m_stack[this.m_count] = null; if (null === element) throw new Error(); return element; }; b2GrowableStack.prototype.GetCount = function() { return this.m_count; }; return b2GrowableStack; })(); var b2BlockAllocator = (function() { function b2BlockAllocator() {} return b2BlockAllocator; })(); var b2StackAllocator = (function() { function b2StackAllocator() {} return b2StackAllocator; })(); var b2DistanceProxy = (function() { function b2DistanceProxy() { this.m_buffer = b2Vec2.MakeArray(2); this.m_vertices = this.m_buffer; this.m_count = 0; this.m_radius = 0; } b2DistanceProxy.prototype.Copy = function(other) { if (other.m_vertices === other.m_buffer) { this.m_vertices = this.m_buffer; this.m_buffer[0].Copy(other.m_buffer[0]); this.m_buffer[1].Copy(other.m_buffer[1]); } else this.m_vertices = other.m_vertices; this.m_count = other.m_count; this.m_radius = other.m_radius; return this; }; b2DistanceProxy.prototype.Reset = function() { this.m_vertices = this.m_buffer; this.m_count = 0; this.m_radius = 0; return this; }; b2DistanceProxy.prototype.SetShape = function(shape, index) { shape.SetupDistanceProxy(this, index); }; b2DistanceProxy.prototype.SetVerticesRadius = function(vertices, count, radius) { this.m_vertices = vertices; this.m_count = count; this.m_radius = radius; }; b2DistanceProxy.prototype.GetSupport = function(d) { var bestIndex = 0; var bestValue = b2Vec2.DotVV(this.m_vertices[0], d); for (var i = 1; i < this.m_count; ++i) { var value = b2Vec2.DotVV(this.m_vertices[i], d); if (value > bestValue) { bestIndex = i; bestValue = value; } } return bestIndex; }; b2DistanceProxy.prototype.GetSupportVertex = function(d) { var bestIndex = 0; var bestValue = b2Vec2.DotVV(this.m_vertices[0], d); for (var i = 1; i < this.m_count; ++i) { var value = b2Vec2.DotVV(this.m_vertices[i], d); if (value > bestValue) { bestIndex = i; bestValue = value; } } return this.m_vertices[bestIndex]; }; b2DistanceProxy.prototype.GetVertexCount = function() { return this.m_count; }; b2DistanceProxy.prototype.GetVertex = function(index) { return this.m_vertices[index]; }; return b2DistanceProxy; })(); var b2SimplexCache = (function() { function b2SimplexCache() { this.metric = 0; this.count = 0; this.indexA = [ 0, 0, 0 ]; this.indexB = [ 0, 0, 0 ]; } b2SimplexCache.prototype.Reset = function() { this.metric = 0; this.count = 0; return this; }; return b2SimplexCache; })(); var b2DistanceInput = (function() { function b2DistanceInput() { this.proxyA = new b2DistanceProxy(); this.proxyB = new b2DistanceProxy(); this.transformA = new b2Transform(); this.transformB = new b2Transform(); this.useRadii = false; } b2DistanceInput.prototype.Reset = function() { this.proxyA.Reset(); this.proxyB.Reset(); this.transformA.SetIdentity(); this.transformB.SetIdentity(); this.useRadii = false; return this; }; return b2DistanceInput; })(); var b2DistanceOutput = (function() { function b2DistanceOutput() { this.pointA = new b2Vec2(); this.pointB = new b2Vec2(); this.distance = 0; this.iterations = 0; } b2DistanceOutput.prototype.Reset = function() { this.pointA.SetZero(); this.pointB.SetZero(); this.distance = 0; this.iterations = 0; return this; }; return b2DistanceOutput; })(); var b2ShapeCastInput = (function() { function b2ShapeCastInput() { this.proxyA = new b2DistanceProxy(); this.proxyB = new b2DistanceProxy(); this.transformA = new b2Transform(); this.transformB = new b2Transform(); this.translationB = new b2Vec2(); } return b2ShapeCastInput; })(); var b2ShapeCastOutput = (function() { function b2ShapeCastOutput() { this.point = new b2Vec2(); this.normal = new b2Vec2(); this.lambda = 0; this.iterations = 0; } return b2ShapeCastOutput; })(); exports.b2_gjkCalls = 0; exports.b2_gjkIters = 0; exports.b2_gjkMaxIters = 0; function b2_gjk_reset() { exports.b2_gjkCalls = 0; exports.b2_gjkIters = 0; exports.b2_gjkMaxIters = 0; } var b2SimplexVertex = (function() { function b2SimplexVertex() { this.wA = new b2Vec2(); this.wB = new b2Vec2(); this.w = new b2Vec2(); this.a = 0; this.indexA = 0; this.indexB = 0; } b2SimplexVertex.prototype.Copy = function(other) { this.wA.Copy(other.wA); this.wB.Copy(other.wB); this.w.Copy(other.w); this.a = other.a; this.indexA = other.indexA; this.indexB = other.indexB; return this; }; return b2SimplexVertex; })(); var b2Simplex = (function() { function b2Simplex() { this.m_v1 = new b2SimplexVertex(); this.m_v2 = new b2SimplexVertex(); this.m_v3 = new b2SimplexVertex(); this.m_vertices = []; this.m_count = 0; this.m_vertices[0] = this.m_v1; this.m_vertices[1] = this.m_v2; this.m_vertices[2] = this.m_v3; } b2Simplex.prototype.ReadCache = function(cache, proxyA, transformA, proxyB, transformB) { this.m_count = cache.count; var vertices = this.m_vertices; for (var i = 0; i < this.m_count; ++i) { var v = vertices[i]; v.indexA = cache.indexA[i]; v.indexB = cache.indexB[i]; var wALocal = proxyA.GetVertex(v.indexA); var wBLocal = proxyB.GetVertex(v.indexB); b2Transform.MulXV(transformA, wALocal, v.wA); b2Transform.MulXV(transformB, wBLocal, v.wB); b2Vec2.SubVV(v.wB, v.wA, v.w); v.a = 0; } if (this.m_count > 1) { var metric1 = cache.metric; var metric2 = this.GetMetric(); (metric2 < .5 * metric1 || 2 * metric1 < metric2 || metric2 < b2_epsilon) && (this.m_count = 0); } if (0 === this.m_count) { var v = vertices[0]; v.indexA = 0; v.indexB = 0; var wALocal = proxyA.GetVertex(0); var wBLocal = proxyB.GetVertex(0); b2Transform.MulXV(transformA, wALocal, v.wA); b2Transform.MulXV(transformB, wBLocal, v.wB); b2Vec2.SubVV(v.wB, v.wA, v.w); v.a = 1; this.m_count = 1; } }; b2Simplex.prototype.WriteCache = function(cache) { cache.metric = this.GetMetric(); cache.count = this.m_count; var vertices = this.m_vertices; for (var i = 0; i < this.m_count; ++i) { cache.indexA[i] = vertices[i].indexA; cache.indexB[i] = vertices[i].indexB; } }; b2Simplex.prototype.GetSearchDirection = function(out) { switch (this.m_count) { case 1: return b2Vec2.NegV(this.m_v1.w, out); case 2: var e12 = b2Vec2.SubVV(this.m_v2.w, this.m_v1.w, out); var sgn = b2Vec2.CrossVV(e12, b2Vec2.NegV(this.m_v1.w, b2Vec2.s_t0)); return sgn > 0 ? b2Vec2.CrossOneV(e12, out) : b2Vec2.CrossVOne(e12, out); default: return out.SetZero(); } }; b2Simplex.prototype.GetClosestPoint = function(out) { switch (this.m_count) { case 0: return out.SetZero(); case 1: return out.Copy(this.m_v1.w); case 2: return out.Set(this.m_v1.a * this.m_v1.w.x + this.m_v2.a * this.m_v2.w.x, this.m_v1.a * this.m_v1.w.y + this.m_v2.a * this.m_v2.w.y); case 3: default: return out.SetZero(); } }; b2Simplex.prototype.GetWitnessPoints = function(pA, pB) { switch (this.m_count) { case 0: break; case 1: pA.Copy(this.m_v1.wA); pB.Copy(this.m_v1.wB); break; case 2: pA.x = this.m_v1.a * this.m_v1.wA.x + this.m_v2.a * this.m_v2.wA.x; pA.y = this.m_v1.a * this.m_v1.wA.y + this.m_v2.a * this.m_v2.wA.y; pB.x = this.m_v1.a * this.m_v1.wB.x + this.m_v2.a * this.m_v2.wB.x; pB.y = this.m_v1.a * this.m_v1.wB.y + this.m_v2.a * this.m_v2.wB.y; break; case 3: pB.x = pA.x = this.m_v1.a * this.m_v1.wA.x + this.m_v2.a * this.m_v2.wA.x + this.m_v3.a * this.m_v3.wA.x; pB.y = pA.y = this.m_v1.a * this.m_v1.wA.y + this.m_v2.a * this.m_v2.wA.y + this.m_v3.a * this.m_v3.wA.y; } }; b2Simplex.prototype.GetMetric = function() { switch (this.m_count) { case 0: case 1: return 0; case 2: return b2Vec2.DistanceVV(this.m_v1.w, this.m_v2.w); case 3: return b2Vec2.CrossVV(b2Vec2.SubVV(this.m_v2.w, this.m_v1.w, b2Vec2.s_t0), b2Vec2.SubVV(this.m_v3.w, this.m_v1.w, b2Vec2.s_t1)); default: return 0; } }; b2Simplex.prototype.Solve2 = function() { var w1 = this.m_v1.w; var w2 = this.m_v2.w; var e12 = b2Vec2.SubVV(w2, w1, b2Simplex.s_e12); var d12_2 = -b2Vec2.DotVV(w1, e12); if (d12_2 <= 0) { this.m_v1.a = 1; this.m_count = 1; return; } var d12_1 = b2Vec2.DotVV(w2, e12); if (d12_1 <= 0) { this.m_v2.a = 1; this.m_count = 1; this.m_v1.Copy(this.m_v2); return; } var inv_d12 = 1 / (d12_1 + d12_2); this.m_v1.a = d12_1 * inv_d12; this.m_v2.a = d12_2 * inv_d12; this.m_count = 2; }; b2Simplex.prototype.Solve3 = function() { var w1 = this.m_v1.w; var w2 = this.m_v2.w; var w3 = this.m_v3.w; var e12 = b2Vec2.SubVV(w2, w1, b2Simplex.s_e12); var w1e12 = b2Vec2.DotVV(w1, e12); var w2e12 = b2Vec2.DotVV(w2, e12); var d12_1 = w2e12; var d12_2 = -w1e12; var e13 = b2Vec2.SubVV(w3, w1, b2Simplex.s_e13); var w1e13 = b2Vec2.DotVV(w1, e13); var w3e13 = b2Vec2.DotVV(w3, e13); var d13_1 = w3e13; var d13_2 = -w1e13; var e23 = b2Vec2.SubVV(w3, w2, b2Simplex.s_e23); var w2e23 = b2Vec2.DotVV(w2, e23); var w3e23 = b2Vec2.DotVV(w3, e23); var d23_1 = w3e23; var d23_2 = -w2e23; var n123 = b2Vec2.CrossVV(e12, e13); var d123_1 = n123 * b2Vec2.CrossVV(w2, w3); var d123_2 = n123 * b2Vec2.CrossVV(w3, w1); var d123_3 = n123 * b2Vec2.CrossVV(w1, w2); if (d12_2 <= 0 && d13_2 <= 0) { this.m_v1.a = 1; this.m_count = 1; return; } if (d12_1 > 0 && d12_2 > 0 && d123_3 <= 0) { var inv_d12 = 1 / (d12_1 + d12_2); this.m_v1.a = d12_1 * inv_d12; this.m_v2.a = d12_2 * inv_d12; this.m_count = 2; return; } if (d13_1 > 0 && d13_2 > 0 && d123_2 <= 0) { var inv_d13 = 1 / (d13_1 + d13_2); this.m_v1.a = d13_1 * inv_d13; this.m_v3.a = d13_2 * inv_d13; this.m_count = 2; this.m_v2.Copy(this.m_v3); return; } if (d12_1 <= 0 && d23_2 <= 0) { this.m_v2.a = 1; this.m_count = 1; this.m_v1.Copy(this.m_v2); return; } if (d13_1 <= 0 && d23_1 <= 0) { this.m_v3.a = 1; this.m_count = 1; this.m_v1.Copy(this.m_v3); return; } if (d23_1 > 0 && d23_2 > 0 && d123_1 <= 0) { var inv_d23 = 1 / (d23_1 + d23_2); this.m_v2.a = d23_1 * inv_d23; this.m_v3.a = d23_2 * inv_d23; this.m_count = 2; this.m_v1.Copy(this.m_v3); return; } var inv_d123 = 1 / (d123_1 + d123_2 + d123_3); this.m_v1.a = d123_1 * inv_d123; this.m_v2.a = d123_2 * inv_d123; this.m_v3.a = d123_3 * inv_d123; this.m_count = 3; }; b2Simplex.s_e12 = new b2Vec2(); b2Simplex.s_e13 = new b2Vec2(); b2Simplex.s_e23 = new b2Vec2(); return b2Simplex; })(); var b2Distance_s_simplex = new b2Simplex(); var b2Distance_s_saveA = [ 0, 0, 0 ]; var b2Distance_s_saveB = [ 0, 0, 0 ]; var b2Distance_s_p = new b2Vec2(); var b2Distance_s_d = new b2Vec2(); var b2Distance_s_normal = new b2Vec2(); var b2Distance_s_supportA = new b2Vec2(); var b2Distance_s_supportB = new b2Vec2(); function b2Distance(output, cache, input) { ++exports.b2_gjkCalls; var proxyA = input.proxyA; var proxyB = input.proxyB; var transformA = input.transformA; var transformB = input.transformB; var simplex = b2Distance_s_simplex; simplex.ReadCache(cache, proxyA, transformA, proxyB, transformB); var vertices = simplex.m_vertices; var k_maxIters = 20; var saveA = b2Distance_s_saveA; var saveB = b2Distance_s_saveB; var saveCount = 0; var iter = 0; while (iter < k_maxIters) { saveCount = simplex.m_count; for (var i = 0; i < saveCount; ++i) { saveA[i] = vertices[i].indexA; saveB[i] = vertices[i].indexB; } switch (simplex.m_count) { case 1: break; case 2: simplex.Solve2(); break; case 3: simplex.Solve3(); } if (3 === simplex.m_count) break; var d = simplex.GetSearchDirection(b2Distance_s_d); if (d.LengthSquared() < b2_epsilon_sq) break; var vertex = vertices[simplex.m_count]; vertex.indexA = proxyA.GetSupport(b2Rot.MulTRV(transformA.q, b2Vec2.NegV(d, b2Vec2.s_t0), b2Distance_s_supportA)); b2Transform.MulXV(transformA, proxyA.GetVertex(vertex.indexA), vertex.wA); vertex.indexB = proxyB.GetSupport(b2Rot.MulTRV(transformB.q, d, b2Distance_s_supportB)); b2Transform.MulXV(transformB, proxyB.GetVertex(vertex.indexB), vertex.wB); b2Vec2.SubVV(vertex.wB, vertex.wA, vertex.w); ++iter; ++exports.b2_gjkIters; var duplicate = false; for (var i = 0; i < saveCount; ++i) if (vertex.indexA === saveA[i] && vertex.indexB === saveB[i]) { duplicate = true; break; } if (duplicate) break; ++simplex.m_count; } exports.b2_gjkMaxIters = b2Max(exports.b2_gjkMaxIters, iter); simplex.GetWitnessPoints(output.pointA, output.pointB); output.distance = b2Vec2.DistanceVV(output.pointA, output.pointB); output.iterations = iter; simplex.WriteCache(cache); if (input.useRadii) { var rA = proxyA.m_radius; var rB = proxyB.m_radius; if (output.distance > rA + rB && output.distance > b2_epsilon) { output.distance -= rA + rB; var normal = b2Vec2.SubVV(output.pointB, output.pointA, b2Distance_s_normal); normal.Normalize(); output.pointA.SelfMulAdd(rA, normal); output.pointB.SelfMulSub(rB, normal); } else { var p = b2Vec2.MidVV(output.pointA, output.pointB, b2Distance_s_p); output.pointA.Copy(p); output.pointB.Copy(p); output.distance = 0; } } } var b2ShapeCast_s_n = new b2Vec2(); var b2ShapeCast_s_simplex = new b2Simplex(); var b2ShapeCast_s_wA = new b2Vec2(); var b2ShapeCast_s_wB = new b2Vec2(); var b2ShapeCast_s_v = new b2Vec2(); var b2ShapeCast_s_p = new b2Vec2(); var b2ShapeCast_s_pointA = new b2Vec2(); var b2ShapeCast_s_pointB = new b2Vec2(); function b2ShapeCast(output, input) { output.iterations = 0; output.lambda = 1; output.normal.SetZero(); output.point.SetZero(); var proxyA = input.proxyA; var proxyB = input.proxyB; var radiusA = b2Max(proxyA.m_radius, b2_polygonRadius); var radiusB = b2Max(proxyB.m_radius, b2_polygonRadius); var radius = radiusA + radiusB; var xfA = input.transformA; var xfB = input.transformB; var r = input.translationB; var n = b2ShapeCast_s_n.Set(0, 0); var lambda = 0; var simplex = b2ShapeCast_s_simplex; simplex.m_count = 0; var vertices = simplex.m_vertices; var indexA = proxyA.GetSupport(b2Rot.MulTRV(xfA.q, b2Vec2.NegV(r, b2Vec2.s_t1), b2Vec2.s_t0)); var wA = b2Transform.MulXV(xfA, proxyA.GetVertex(indexA), b2ShapeCast_s_wA); var indexB = proxyB.GetSupport(b2Rot.MulTRV(xfB.q, r, b2Vec2.s_t0)); var wB = b2Transform.MulXV(xfB, proxyB.GetVertex(indexB), b2ShapeCast_s_wB); var v = b2Vec2.SubVV(wA, wB, b2ShapeCast_s_v); var sigma = b2Max(b2_polygonRadius, radius - b2_polygonRadius); var tolerance = .5 * b2_linearSlop; var k_maxIters = 20; var iter = 0; while (iter < k_maxIters && b2Abs(v.Length() - sigma) > tolerance) { output.iterations += 1; indexA = proxyA.GetSupport(b2Rot.MulTRV(xfA.q, b2Vec2.NegV(v, b2Vec2.s_t1), b2Vec2.s_t0)); wA = b2Transform.MulXV(xfA, proxyA.GetVertex(indexA), b2ShapeCast_s_wA); indexB = proxyB.GetSupport(b2Rot.MulTRV(xfB.q, v, b2Vec2.s_t0)); wB = b2Transform.MulXV(xfB, proxyB.GetVertex(indexB), b2ShapeCast_s_wB); var p = b2Vec2.SubVV(wA, wB, b2ShapeCast_s_p); v.Normalize(); var vp = b2Vec2.DotVV(v, p); var vr = b2Vec2.DotVV(v, r); if (vp - sigma > lambda * vr) { if (vr <= 0) return false; lambda = (vp - sigma) / vr; if (lambda > 1) return false; n.Copy(v).SelfNeg(); simplex.m_count = 0; } var vertex = vertices[simplex.m_count]; vertex.indexA = indexB; vertex.wA.Copy(wB).SelfMulAdd(lambda, r); vertex.indexB = indexA; vertex.wB.Copy(wA); vertex.w.Copy(vertex.wB).SelfSub(vertex.wA); vertex.a = 1; simplex.m_count += 1; switch (simplex.m_count) { case 1: break; case 2: simplex.Solve2(); break; case 3: simplex.Solve3(); } if (3 === simplex.m_count) return false; simplex.GetClosestPoint(v); ++iter; } var pointA = b2ShapeCast_s_pointA; var pointB = b2ShapeCast_s_pointB; simplex.GetWitnessPoints(pointA, pointB); if (v.LengthSquared() > 0) { n.Copy(v).SelfNeg(); n.Normalize(); } output.normal.Copy(n); output.lambda = lambda; output.iterations = iter; return true; } (function(b2ContactFeatureType) { b2ContactFeatureType[b2ContactFeatureType["e_vertex"] = 0] = "e_vertex"; b2ContactFeatureType[b2ContactFeatureType["e_face"] = 1] = "e_face"; })(exports.b2ContactFeatureType || (exports.b2ContactFeatureType = {})); var b2ContactFeature = (function() { function b2ContactFeature() { this._key = 0; this._key_invalid = false; this._indexA = 0; this._indexB = 0; this._typeA = 0; this._typeB = 0; } Object.defineProperty(b2ContactFeature.prototype, "key", { get: function() { if (this._key_invalid) { this._key_invalid = false; this._key = this._indexA | this._indexB << 8 | this._typeA << 16 | this._typeB << 24; } return this._key; }, set: function(value) { this._key = value; this._key_invalid = false; this._indexA = 255 & this._key; this._indexB = this._key >> 8 & 255; this._typeA = this._key >> 16 & 255; this._typeB = this._key >> 24 & 255; }, enumerable: true, configurable: true }); Object.defineProperty(b2ContactFeature.prototype, "indexA", { get: function() { return this._indexA; }, set: function(value) { this._indexA = value; this._key_invalid = true; }, enumerable: true, configurable: true }); Object.defineProperty(b2ContactFeature.prototype, "indexB", { get: function() { return this._indexB; }, set: function(value) { this._indexB = value; this._key_invalid = true; }, enumerable: true, configurable: true }); Object.defineProperty(b2ContactFeature.prototype, "typeA", { get: function() { return this._typeA; }, set: function(value) { this._typeA = value; this._key_invalid = true; }, enumerable: true, configurable: true }); Object.defineProperty(b2ContactFeature.prototype, "typeB", { get: function() { return this._typeB; }, set: function(value) { this._typeB = value; this._key_invalid = true; }, enumerable: true, configurable: true }); return b2ContactFeature; })(); var b2ContactID = (function() { function b2ContactID() { this.cf = new b2ContactFeature(); } b2ContactID.prototype.Copy = function(o) { this.key = o.key; return this; }; b2ContactID.prototype.Clone = function() { return new b2ContactID().Copy(this); }; Object.defineProperty(b2ContactID.prototype, "key", { get: function() { return this.cf.key; }, set: function(value) { this.cf.key = value; }, enumerable: true, configurable: true }); return b2ContactID; })(); var b2ManifoldPoint = (function() { function b2ManifoldPoint() { this.localPoint = new b2Vec2(); this.normalImpulse = 0; this.tangentImpulse = 0; this.id = new b2ContactID(); } b2ManifoldPoint.MakeArray = function(length) { return b2MakeArray(length, (function(i) { return new b2ManifoldPoint(); })); }; b2ManifoldPoint.prototype.Reset = function() { this.localPoint.SetZero(); this.normalImpulse = 0; this.tangentImpulse = 0; this.id.key = 0; }; b2ManifoldPoint.prototype.Copy = function(o) { this.localPoint.Copy(o.localPoint); this.normalImpulse = o.normalImpulse; this.tangentImpulse = o.tangentImpulse; this.id.Copy(o.id); return this; }; return b2ManifoldPoint; })(); (function(b2ManifoldType) { b2ManifoldType[b2ManifoldType["e_unknown"] = -1] = "e_unknown"; b2ManifoldType[b2ManifoldType["e_circles"] = 0] = "e_circles"; b2ManifoldType[b2ManifoldType["e_faceA"] = 1] = "e_faceA"; b2ManifoldType[b2ManifoldType["e_faceB"] = 2] = "e_faceB"; })(exports.b2ManifoldType || (exports.b2ManifoldType = {})); var b2Manifold = (function() { function b2Manifold() { this.points = b2ManifoldPoint.MakeArray(b2_maxManifoldPoints); this.localNormal = new b2Vec2(); this.localPoint = new b2Vec2(); this.type = exports.b2ManifoldType.e_unknown; this.pointCount = 0; } b2Manifold.prototype.Reset = function() { for (var i = 0; i < b2_maxManifoldPoints; ++i) this.points[i].Reset(); this.localNormal.SetZero(); this.localPoint.SetZero(); this.type = exports.b2ManifoldType.e_unknown; this.pointCount = 0; }; b2Manifold.prototype.Copy = function(o) { this.pointCount = o.pointCount; for (var i = 0; i < b2_maxManifoldPoints; ++i) this.points[i].Copy(o.points[i]); this.localNormal.Copy(o.localNormal); this.localPoint.Copy(o.localPoint); this.type = o.type; return this; }; b2Manifold.prototype.Clone = function() { return new b2Manifold().Copy(this); }; return b2Manifold; })(); var b2WorldManifold = (function() { function b2WorldManifold() { this.normal = new b2Vec2(); this.points = b2Vec2.MakeArray(b2_maxManifoldPoints); this.separations = b2MakeNumberArray(b2_maxManifoldPoints); } b2WorldManifold.prototype.Initialize = function(manifold, xfA, radiusA, xfB, radiusB) { if (0 === manifold.pointCount) return; switch (manifold.type) { case exports.b2ManifoldType.e_circles: this.normal.Set(1, 0); var pointA = b2Transform.MulXV(xfA, manifold.localPoint, b2WorldManifold.Initialize_s_pointA); var pointB = b2Transform.MulXV(xfB, manifold.points[0].localPoint, b2WorldManifold.Initialize_s_pointB); b2Vec2.DistanceSquaredVV(pointA, pointB) > b2_epsilon_sq && b2Vec2.SubVV(pointB, pointA, this.normal).SelfNormalize(); var cA = b2Vec2.AddVMulSV(pointA, radiusA, this.normal, b2WorldManifold.Initialize_s_cA); var cB = b2Vec2.SubVMulSV(pointB, radiusB, this.normal, b2WorldManifold.Initialize_s_cB); b2Vec2.MidVV(cA, cB, this.points[0]); this.separations[0] = b2Vec2.DotVV(b2Vec2.SubVV(cB, cA, b2Vec2.s_t0), this.normal); break; case exports.b2ManifoldType.e_faceA: b2Rot.MulRV(xfA.q, manifold.localNormal, this.normal); var planePoint = b2Transform.MulXV(xfA, manifold.localPoint, b2WorldManifold.Initialize_s_planePoint); for (var i = 0; i < manifold.pointCount; ++i) { var clipPoint = b2Transform.MulXV(xfB, manifold.points[i].localPoint, b2WorldManifold.Initialize_s_clipPoint); var s = radiusA - b2Vec2.DotVV(b2Vec2.SubVV(clipPoint, planePoint, b2Vec2.s_t0), this.normal); var cA = b2Vec2.AddVMulSV(clipPoint, s, this.normal, b2WorldManifold.Initialize_s_cA); var cB = b2Vec2.SubVMulSV(clipPoint, radiusB, this.normal, b2WorldManifold.Initialize_s_cB); b2Vec2.MidVV(cA, cB, this.points[i]); this.separations[i] = b2Vec2.DotVV(b2Vec2.SubVV(cB, cA, b2Vec2.s_t0), this.normal); } break; case exports.b2ManifoldType.e_faceB: b2Rot.MulRV(xfB.q, manifold.localNormal, this.normal); var planePoint = b2Transform.MulXV(xfB, manifold.localPoint, b2WorldManifold.Initialize_s_planePoint); for (var i = 0; i < manifold.pointCount; ++i) { var clipPoint = b2Transform.MulXV(xfA, manifold.points[i].localPoint, b2WorldManifold.Initialize_s_clipPoint); var s = radiusB - b2Vec2.DotVV(b2Vec2.SubVV(clipPoint, planePoint, b2Vec2.s_t0), this.normal); var cB = b2Vec2.AddVMulSV(clipPoint, s, this.normal, b2WorldManifold.Initialize_s_cB); var cA = b2Vec2.SubVMulSV(clipPoint, radiusA, this.normal, b2WorldManifold.Initialize_s_cA); b2Vec2.MidVV(cA, cB, this.points[i]); this.separations[i] = b2Vec2.DotVV(b2Vec2.SubVV(cA, cB, b2Vec2.s_t0), this.normal); } this.normal.SelfNeg(); } }; b2WorldManifold.Initialize_s_pointA = new b2Vec2(); b2WorldManifold.Initialize_s_pointB = new b2Vec2(); b2WorldManifold.Initialize_s_cA = new b2Vec2(); b2WorldManifold.Initialize_s_cB = new b2Vec2(); b2WorldManifold.Initialize_s_planePoint = new b2Vec2(); b2WorldManifold.Initialize_s_clipPoint = new b2Vec2(); return b2WorldManifold; })(); (function(b2PointState) { b2PointState[b2PointState["b2_nullState"] = 0] = "b2_nullState"; b2PointState[b2PointState["b2_addState"] = 1] = "b2_addState"; b2PointState[b2PointState["b2_persistState"] = 2] = "b2_persistState"; b2PointState[b2PointState["b2_removeState"] = 3] = "b2_removeState"; })(exports.b2PointState || (exports.b2PointState = {})); function b2GetPointStates(state1, state2, manifold1, manifold2) { var i; for (i = 0; i < manifold1.pointCount; ++i) { var id = manifold1.points[i].id; var key = id.key; state1[i] = exports.b2PointState.b2_removeState; for (var j = 0, jct = manifold2.pointCount; j < jct; ++j) if (manifold2.points[j].id.key === key) { state1[i] = exports.b2PointState.b2_persistState; break; } } for (;i < b2_maxManifoldPoints; ++i) state1[i] = exports.b2PointState.b2_nullState; for (i = 0; i < manifold2.pointCount; ++i) { var id = manifold2.points[i].id; var key = id.key; state2[i] = exports.b2PointState.b2_addState; for (var j = 0, jct = manifold1.pointCount; j < jct; ++j) if (manifold1.points[j].id.key === key) { state2[i] = exports.b2PointState.b2_persistState; break; } } for (;i < b2_maxManifoldPoints; ++i) state2[i] = exports.b2PointState.b2_nullState; } var b2ClipVertex = (function() { function b2ClipVertex() { this.v = new b2Vec2(); this.id = new b2ContactID(); } b2ClipVertex.MakeArray = function(length) { return b2MakeArray(length, (function(i) { return new b2ClipVertex(); })); }; b2ClipVertex.prototype.Copy = function(other) { this.v.Copy(other.v); this.id.Copy(other.id); return this; }; return b2ClipVertex; })(); var b2RayCastInput = (function() { function b2RayCastInput() { this.p1 = new b2Vec2(); this.p2 = new b2Vec2(); this.maxFraction = 1; } b2RayCastInput.prototype.Copy = function(o) { this.p1.Copy(o.p1); this.p2.Copy(o.p2); this.maxFraction = o.maxFraction; return this; }; return b2RayCastInput; })(); var b2RayCastOutput = (function() { function b2RayCastOutput() { this.normal = new b2Vec2(); this.fraction = 0; } b2RayCastOutput.prototype.Copy = function(o) { this.normal.Copy(o.normal); this.fraction = o.fraction; return this; }; return b2RayCastOutput; })(); var b2AABB = (function() { function b2AABB() { this.lowerBound = new b2Vec2(); this.upperBound = new b2Vec2(); this.m_cache_center = new b2Vec2(); this.m_cache_extent = new b2Vec2(); } b2AABB.prototype.Copy = function(o) { this.lowerBound.Copy(o.lowerBound); this.upperBound.Copy(o.upperBound); return this; }; b2AABB.prototype.IsValid = function() { var d_x = this.upperBound.x - this.lowerBound.x; var d_y = this.upperBound.y - this.lowerBound.y; var valid = d_x >= 0 && d_y >= 0; valid = valid && this.lowerBound.IsValid() && this.upperBound.IsValid(); return valid; }; b2AABB.prototype.GetCenter = function() { return b2Vec2.MidVV(this.lowerBound, this.upperBound, this.m_cache_center); }; b2AABB.prototype.GetExtents = function() { return b2Vec2.ExtVV(this.lowerBound, this.upperBound, this.m_cache_extent); }; b2AABB.prototype.GetPerimeter = function() { var wx = this.upperBound.x - this.lowerBound.x; var wy = this.upperBound.y - this.lowerBound.y; return 2 * (wx + wy); }; b2AABB.prototype.Combine1 = function(aabb) { this.lowerBound.x = b2Min(this.lowerBound.x, aabb.lowerBound.x); this.lowerBound.y = b2Min(this.lowerBound.y, aabb.lowerBound.y); this.upperBound.x = b2Max(this.upperBound.x, aabb.upperBound.x); this.upperBound.y = b2Max(this.upperBound.y, aabb.upperBound.y); return this; }; b2AABB.prototype.Combine2 = function(aabb1, aabb2) { this.lowerBound.x = b2Min(aabb1.lowerBound.x, aabb2.lowerBound.x); this.lowerBound.y = b2Min(aabb1.lowerBound.y, aabb2.lowerBound.y); this.upperBound.x = b2Max(aabb1.upperBound.x, aabb2.upperBound.x); this.upperBound.y = b2Max(aabb1.upperBound.y, aabb2.upperBound.y); return this; }; b2AABB.Combine = function(aabb1, aabb2, out) { out.Combine2(aabb1, aabb2); return out; }; b2AABB.prototype.Contains = function(aabb) { var result = true; result = result && this.lowerBound.x <= aabb.lowerBound.x; result = result && this.lowerBound.y <= aabb.lowerBound.y; result = result && aabb.upperBound.x <= this.upperBound.x; result = result && aabb.upperBound.y <= this.upperBound.y; return result; }; b2AABB.prototype.RayCast = function(output, input) { var tmin = -b2_maxFloat; var tmax = b2_maxFloat; var p_x = input.p1.x; var p_y = input.p1.y; var d_x = input.p2.x - input.p1.x; var d_y = input.p2.y - input.p1.y; var absD_x = b2Abs(d_x); var absD_y = b2Abs(d_y); var normal = output.normal; if (absD_x < b2_epsilon) { if (p_x < this.lowerBound.x || this.upperBound.x < p_x) return false; } else { var inv_d = 1 / d_x; var t1 = (this.lowerBound.x - p_x) * inv_d; var t2 = (this.upperBound.x - p_x) * inv_d; var s = -1; if (t1 > t2) { var t3 = t1; t1 = t2; t2 = t3; s = 1; } if (t1 > tmin) { normal.x = s; normal.y = 0; tmin = t1; } tmax = b2Min(tmax, t2); if (tmin > tmax) return false; } if (absD_y < b2_epsilon) { if (p_y < this.lowerBound.y || this.upperBound.y < p_y) return false; } else { var inv_d = 1 / d_y; var t1 = (this.lowerBound.y - p_y) * inv_d; var t2 = (this.upperBound.y - p_y) * inv_d; var s = -1; if (t1 > t2) { var t3 = t1; t1 = t2; t2 = t3; s = 1; } if (t1 > tmin) { normal.x = 0; normal.y = s; tmin = t1; } tmax = b2Min(tmax, t2); if (tmin > tmax) return false; } if (tmin < 0 || input.maxFraction < tmin) return false; output.fraction = tmin; return true; }; b2AABB.prototype.TestContain = function(point) { if (point.x < this.lowerBound.x || this.upperBound.x < point.x) return false; if (point.y < this.lowerBound.y || this.upperBound.y < point.y) return false; return true; }; b2AABB.prototype.TestOverlap = function(other) { var d1_x = other.lowerBound.x - this.upperBound.x; var d1_y = other.lowerBound.y - this.upperBound.y; var d2_x = this.lowerBound.x - other.upperBound.x; var d2_y = this.lowerBound.y - other.upperBound.y; if (d1_x > 0 || d1_y > 0) return false; if (d2_x > 0 || d2_y > 0) return false; return true; }; return b2AABB; })(); function b2TestOverlapAABB(a, b) { var d1_x = b.lowerBound.x - a.upperBound.x; var d1_y = b.lowerBound.y - a.upperBound.y; var d2_x = a.lowerBound.x - b.upperBound.x; var d2_y = a.lowerBound.y - b.upperBound.y; if (d1_x > 0 || d1_y > 0) return false; if (d2_x > 0 || d2_y > 0) return false; return true; } function b2ClipSegmentToLine(vOut, vIn, normal, offset, vertexIndexA) { var numOut = 0; var vIn0 = vIn[0]; var vIn1 = vIn[1]; var distance0 = b2Vec2.DotVV(normal, vIn0.v) - offset; var distance1 = b2Vec2.DotVV(normal, vIn1.v) - offset; distance0 <= 0 && vOut[numOut++].Copy(vIn0); distance1 <= 0 && vOut[numOut++].Copy(vIn1); if (distance0 * distance1 < 0) { var interp = distance0 / (distance0 - distance1); var v = vOut[numOut].v; v.x = vIn0.v.x + interp * (vIn1.v.x - vIn0.v.x); v.y = vIn0.v.y + interp * (vIn1.v.y - vIn0.v.y); var id = vOut[numOut].id; id.cf.indexA = vertexIndexA; id.cf.indexB = vIn0.id.cf.indexB; id.cf.typeA = exports.b2ContactFeatureType.e_vertex; id.cf.typeB = exports.b2ContactFeatureType.e_face; ++numOut; } return numOut; } var b2TestOverlapShape_s_input = new b2DistanceInput(); var b2TestOverlapShape_s_simplexCache = new b2SimplexCache(); var b2TestOverlapShape_s_output = new b2DistanceOutput(); function b2TestOverlapShape(shapeA, indexA, shapeB, indexB, xfA, xfB) { var input = b2TestOverlapShape_s_input.Reset(); input.proxyA.SetShape(shapeA, indexA); input.proxyB.SetShape(shapeB, indexB); input.transformA.Copy(xfA); input.transformB.Copy(xfB); input.useRadii = true; var simplexCache = b2TestOverlapShape_s_simplexCache.Reset(); simplexCache.count = 0; var output = b2TestOverlapShape_s_output.Reset(); b2Distance(output, simplexCache, input); return output.distance < 10 * b2_epsilon; } function verify(value) { if (null === value) throw new Error(); return value; } var b2TreeNode = (function() { function b2TreeNode(id) { void 0 === id && (id = 0); this.m_id = 0; this.aabb = new b2AABB(); this.parent = null; this.child1 = null; this.child2 = null; this.height = 0; this.m_id = id; } b2TreeNode.prototype.IsLeaf = function() { return null === this.child1; }; return b2TreeNode; })(); var b2DynamicTree = (function() { function b2DynamicTree() { this.m_root = null; this.m_freeList = null; this.m_path = 0; this.m_insertionCount = 0; this.m_stack = new b2GrowableStack(256); } b2DynamicTree.prototype.Query = function(aabb, callback) { if (null === this.m_root) return; var stack = this.m_stack.Reset(); stack.Push(this.m_root); while (stack.GetCount() > 0) { var node = stack.Pop(); if (node.aabb.TestOverlap(aabb)) if (node.IsLeaf()) { var proceed = callback(node); if (!proceed) return; } else { stack.Push(verify(node.child1)); stack.Push(verify(node.child2)); } } }; b2DynamicTree.prototype.QueryPoint = function(point, callback) { if (null === this.m_root) return; var stack = this.m_stack.Reset(); stack.Push(this.m_root); while (stack.GetCount() > 0) { var node = stack.Pop(); if (node.aabb.TestContain(point)) if (node.IsLeaf()) { var proceed = callback(node); if (!proceed) return; } else { stack.Push(verify(node.child1)); stack.Push(verify(node.child2)); } } }; b2DynamicTree.prototype.RayCast = function(input, callback) { if (null === this.m_root) return; var p1 = input.p1; var p2 = input.p2; var r = b2Vec2.SubVV(p2, p1, b2DynamicTree.s_r); r.Normalize(); var v = b2Vec2.CrossOneV(r, b2DynamicTree.s_v); var abs_v = b2Vec2.AbsV(v, b2DynamicTree.s_abs_v); var maxFraction = input.maxFraction; var segmentAABB = b2DynamicTree.s_segmentAABB; var t_x = p1.x + maxFraction * (p2.x - p1.x); var t_y = p1.y + maxFraction * (p2.y - p1.y); segmentAABB.lowerBound.x = b2Min(p1.x, t_x); segmentAABB.lowerBound.y = b2Min(p1.y, t_y); segmentAABB.upperBound.x = b2Max(p1.x, t_x); segmentAABB.upperBound.y = b2Max(p1.y, t_y); var stack = this.m_stack.Reset(); stack.Push(this.m_root); while (stack.GetCount() > 0) { var node = stack.Pop(); if (!b2TestOverlapAABB(node.aabb, segmentAABB)) continue; var c = node.aabb.GetCenter(); var h = node.aabb.GetExtents(); var separation = b2Abs(b2Vec2.DotVV(v, b2Vec2.SubVV(p1, c, b2Vec2.s_t0))) - b2Vec2.DotVV(abs_v, h); if (separation > 0) continue; if (node.IsLeaf()) { var subInput = b2DynamicTree.s_subInput; subInput.p1.Copy(input.p1); subInput.p2.Copy(input.p2); subInput.maxFraction = maxFraction; var value = callback(subInput, node); if (0 === value) return; if (value > 0) { maxFraction = value; t_x = p1.x + maxFraction * (p2.x - p1.x); t_y = p1.y + maxFraction * (p2.y - p1.y); segmentAABB.lowerBound.x = b2Min(p1.x, t_x); segmentAABB.lowerBound.y = b2Min(p1.y, t_y); segmentAABB.upperBound.x = b2Max(p1.x, t_x); segmentAABB.upperBound.y = b2Max(p1.y, t_y); } } else { stack.Push(verify(node.child1)); stack.Push(verify(node.child2)); } } }; b2DynamicTree.prototype.AllocateNode = function() { if (this.m_freeList) { var node = this.m_freeList; this.m_freeList = node.parent; node.parent = null; node.child1 = null; node.child2 = null; node.height = 0; delete node.userData; return node; } return new b2TreeNode(b2DynamicTree.s_node_id++); }; b2DynamicTree.prototype.FreeNode = function(node) { node.parent = this.m_freeList; node.child1 = null; node.child2 = null; node.height = -1; delete node.userData; this.m_freeList = node; }; b2DynamicTree.prototype.CreateProxy = function(aabb, userData) { var node = this.AllocateNode(); var r_x = b2_aabbExtension; var r_y = b2_aabbExtension; node.aabb.lowerBound.x = aabb.lowerBound.x - r_x; node.aabb.lowerBound.y = aabb.lowerBound.y - r_y; node.aabb.upperBound.x = aabb.upperBound.x + r_x; node.aabb.upperBound.y = aabb.upperBound.y + r_y; node.userData = userData; node.height = 0; this.InsertLeaf(node); return node; }; b2DynamicTree.prototype.DestroyProxy = function(proxy) { this.RemoveLeaf(proxy); this.FreeNode(proxy); }; b2DynamicTree.prototype.MoveProxy = function(proxy, aabb, displacement) { if (proxy.aabb.Contains(aabb)) return false; this.RemoveLeaf(proxy); var r_x = b2_aabbExtension + b2_aabbMultiplier * (displacement.x > 0 ? displacement.x : -displacement.x); var r_y = b2_aabbExtension + b2_aabbMultiplier * (displacement.y > 0 ? displacement.y : -displacement.y); proxy.aabb.lowerBound.x = aabb.lowerBound.x - r_x; proxy.aabb.lowerBound.y = aabb.lowerBound.y - r_y; proxy.aabb.upperBound.x = aabb.upperBound.x + r_x; proxy.aabb.upperBound.y = aabb.upperBound.y + r_y; this.InsertLeaf(proxy); return true; }; b2DynamicTree.prototype.InsertLeaf = function(leaf) { ++this.m_insertionCount; if (null === this.m_root) { this.m_root = leaf; this.m_root.parent = null; return; } var leafAABB = leaf.aabb; var index = this.m_root; while (!index.IsLeaf()) { var child1 = verify(index.child1); var child2 = verify(index.child2); var area = index.aabb.GetPerimeter(); var combinedAABB = b2DynamicTree.s_combinedAABB; combinedAABB.Combine2(index.aabb, leafAABB); var combinedArea = combinedAABB.GetPerimeter(); var cost = 2 * combinedArea; var inheritanceCost = 2 * (combinedArea - area); var cost1 = void 0; var aabb = b2DynamicTree.s_aabb; var oldArea = void 0; var newArea = void 0; if (child1.IsLeaf()) { aabb.Combine2(leafAABB, child1.aabb); cost1 = aabb.GetPerimeter() + inheritanceCost; } else { aabb.Combine2(leafAABB, child1.aabb); oldArea = child1.aabb.GetPerimeter(); newArea = aabb.GetPerimeter(); cost1 = newArea - oldArea + inheritanceCost; } var cost2 = void 0; if (child2.IsLeaf()) { aabb.Combine2(leafAABB, child2.aabb); cost2 = aabb.GetPerimeter() + inheritanceCost; } else { aabb.Combine2(leafAABB, child2.aabb); oldArea = child2.aabb.GetPerimeter(); newArea = aabb.GetPerimeter(); cost2 = newArea - oldArea + inheritanceCost; } if (cost < cost1 && cost < cost2) break; index = cost1 < cost2 ? child1 : child2; } var sibling = index; var oldParent = sibling.parent; var newParent = this.AllocateNode(); newParent.parent = oldParent; delete newParent.userData; newParent.aabb.Combine2(leafAABB, sibling.aabb); newParent.height = sibling.height + 1; if (oldParent) { oldParent.child1 === sibling ? oldParent.child1 = newParent : oldParent.child2 = newParent; newParent.child1 = sibling; newParent.child2 = leaf; sibling.parent = newParent; leaf.parent = newParent; } else { newParent.child1 = sibling; newParent.child2 = leaf; sibling.parent = newParent; leaf.parent = newParent; this.m_root = newParent; } var index2 = leaf.parent; while (null !== index2) { index2 = this.Balance(index2); var child1 = verify(index2.child1); var child2 = verify(index2.child2); index2.height = 1 + b2Max(child1.height, child2.height); index2.aabb.Combine2(child1.aabb, child2.aabb); index2 = index2.parent; } }; b2DynamicTree.prototype.RemoveLeaf = function(leaf) { if (leaf === this.m_root) { this.m_root = null; return; } var parent = verify(leaf.parent); var grandParent = parent && parent.parent; var sibling; sibling = parent.child1 === leaf ? verify(parent.child2) : verify(parent.child1); if (grandParent) { grandParent.child1 === parent ? grandParent.child1 = sibling : grandParent.child2 = sibling; sibling.parent = grandParent; this.FreeNode(parent); var index = grandParent; while (index) { index = this.Balance(index); var child1 = verify(index.child1); var child2 = verify(index.child2); index.aabb.Combine2(child1.aabb, child2.aabb); index.height = 1 + b2Max(child1.height, child2.height); index = index.parent; } } else { this.m_root = sibling; sibling.parent = null; this.FreeNode(parent); } }; b2DynamicTree.prototype.Balance = function(A) { if (A.IsLeaf() || A.height < 2) return A; var B = verify(A.child1); var C = verify(A.child2); var balance = C.height - B.height; if (balance > 1) { var F = verify(C.child1); var G = verify(C.child2); C.child1 = A; C.parent = A.parent; A.parent = C; null !== C.parent ? C.parent.child1 === A ? C.parent.child1 = C : C.parent.child2 = C : this.m_root = C; if (F.height > G.height) { C.child2 = F; A.child2 = G; G.parent = A; A.aabb.Combine2(B.aabb, G.aabb); C.aabb.Combine2(A.aabb, F.aabb); A.height = 1 + b2Max(B.height, G.height); C.height = 1 + b2Max(A.height, F.height); } else { C.child2 = G; A.child2 = F; F.parent = A; A.aabb.Combine2(B.aabb, F.aabb); C.aabb.Combine2(A.aabb, G.aabb); A.height = 1 + b2Max(B.height, F.height); C.height = 1 + b2Max(A.height, G.height); } return C; } if (balance < -1) { var D = verify(B.child1); var E = verify(B.child2); B.child1 = A; B.parent = A.parent; A.parent = B; null !== B.parent ? B.parent.child1 === A ? B.parent.child1 = B : B.parent.child2 = B : this.m_root = B; if (D.height > E.height) { B.child2 = D; A.child1 = E; E.parent = A; A.aabb.Combine2(C.aabb, E.aabb); B.aabb.Combine2(A.aabb, D.aabb); A.height = 1 + b2Max(C.height, E.height); B.height = 1 + b2Max(A.height, D.height); } else { B.child2 = E; A.child1 = D; D.parent = A; A.aabb.Combine2(C.aabb, D.aabb); B.aabb.Combine2(A.aabb, E.aabb); A.height = 1 + b2Max(C.height, D.height); B.height = 1 + b2Max(A.height, E.height); } return B; } return A; }; b2DynamicTree.prototype.GetHeight = function() { if (null === this.m_root) return 0; return this.m_root.height; }; b2DynamicTree.GetAreaNode = function(node) { if (null === node) return 0; if (node.IsLeaf()) return 0; var area = node.aabb.GetPerimeter(); area += b2DynamicTree.GetAreaNode(node.child1); area += b2DynamicTree.GetAreaNode(node.child2); return area; }; b2DynamicTree.prototype.GetAreaRatio = function() { if (null === this.m_root) return 0; var root = this.m_root; var rootArea = root.aabb.GetPerimeter(); var totalArea = b2DynamicTree.GetAreaNode(this.m_root); return totalArea / rootArea; }; b2DynamicTree.prototype.ComputeHeightNode = function(node) { if (!node || node.IsLeaf()) return 0; var height1 = this.ComputeHeightNode(node.child1); var height2 = this.ComputeHeightNode(node.child2); return 1 + b2Max(height1, height2); }; b2DynamicTree.prototype.ComputeHeight = function() { var height = this.ComputeHeightNode(this.m_root); return height; }; b2DynamicTree.prototype.ValidateStructure = function(index) { if (null === index) return; index === this.m_root; var node = index; if (node.IsLeaf()) return; var child1 = verify(node.child1); var child2 = verify(node.child2); this.ValidateStructure(child1); this.ValidateStructure(child2); }; b2DynamicTree.prototype.ValidateMetrics = function(index) { if (null === index) return; var node = index; if (node.IsLeaf()) return; var child1 = verify(node.child1); var child2 = verify(node.child2); var aabb = b2DynamicTree.s_aabb; aabb.Combine2(child1.aabb, child2.aabb); this.ValidateMetrics(child1); this.ValidateMetrics(child2); }; b2DynamicTree.prototype.Validate = function() {}; b2DynamicTree.GetMaxBalanceNode = function(node, maxBalance) { if (null === node) return maxBalance; if (node.height <= 1) return maxBalance; var child1 = verify(node.child1); var child2 = verify(node.child2); var balance = b2Abs(child2.height - child1.height); return b2Max(maxBalance, balance); }; b2DynamicTree.prototype.GetMaxBalance = function() { var maxBalance = b2DynamicTree.GetMaxBalanceNode(this.m_root, 0); return maxBalance; }; b2DynamicTree.prototype.RebuildBottomUp = function() { this.Validate(); }; b2DynamicTree.ShiftOriginNode = function(node, newOrigin) { if (null === node) return; if (node.height <= 1) return; var child1 = node.child1; var child2 = node.child2; b2DynamicTree.ShiftOriginNode(child1, newOrigin); b2DynamicTree.ShiftOriginNode(child2, newOrigin); node.aabb.lowerBound.SelfSub(newOrigin); node.aabb.upperBound.SelfSub(newOrigin); }; b2DynamicTree.prototype.ShiftOrigin = function(newOrigin) { b2DynamicTree.ShiftOriginNode(this.m_root, newOrigin); }; b2DynamicTree.s_r = new b2Vec2(); b2DynamicTree.s_v = new b2Vec2(); b2DynamicTree.s_abs_v = new b2Vec2(); b2DynamicTree.s_segmentAABB = new b2AABB(); b2DynamicTree.s_subInput = new b2RayCastInput(); b2DynamicTree.s_combinedAABB = new b2AABB(); b2DynamicTree.s_aabb = new b2AABB(); b2DynamicTree.s_node_id = 0; return b2DynamicTree; })(); var b2Pair = (function() { function b2Pair(proxyA, proxyB) { this.proxyA = proxyA; this.proxyB = proxyB; } return b2Pair; })(); var b2BroadPhase = (function() { function b2BroadPhase() { this.m_tree = new b2DynamicTree(); this.m_proxyCount = 0; this.m_moveCount = 0; this.m_moveBuffer = []; this.m_pairCount = 0; this.m_pairBuffer = []; } b2BroadPhase.prototype.CreateProxy = function(aabb, userData) { var proxy = this.m_tree.CreateProxy(aabb, userData); ++this.m_proxyCount; this.BufferMove(proxy); return proxy; }; b2BroadPhase.prototype.DestroyProxy = function(proxy) { this.UnBufferMove(proxy); --this.m_proxyCount; this.m_tree.DestroyProxy(proxy); }; b2BroadPhase.prototype.MoveProxy = function(proxy, aabb, displacement) { var buffer = this.m_tree.MoveProxy(proxy, aabb, displacement); buffer && this.BufferMove(proxy); }; b2BroadPhase.prototype.TouchProxy = function(proxy) { this.BufferMove(proxy); }; b2BroadPhase.prototype.GetProxyCount = function() { return this.m_proxyCount; }; b2BroadPhase.prototype.UpdatePairs = function(callback) { var _this = this; this.m_pairCount = 0; var _loop_1 = function(i_1) { var queryProxy = this_1.m_moveBuffer[i_1]; if (null === queryProxy) return "continue"; var fatAABB = queryProxy.aabb; this_1.m_tree.Query(fatAABB, (function(proxy) { if (proxy.m_id === queryProxy.m_id) return true; var proxyA; var proxyB; if (proxy.m_id < queryProxy.m_id) { proxyA = proxy; proxyB = queryProxy; } else { proxyA = queryProxy; proxyB = proxy; } if (_this.m_pairCount === _this.m_pairBuffer.length) _this.m_pairBuffer[_this.m_pairCount] = new b2Pair(proxyA, proxyB); else { var pair = _this.m_pairBuffer[_this.m_pairCount]; pair.proxyA = proxyA; pair.proxyB = proxyB; } ++_this.m_pairCount; return true; })); }; var this_1 = this; for (var i_1 = 0; i_1 < this.m_moveCount; ++i_1) _loop_1(i_1); this.m_moveCount = 0; this.m_pairBuffer.length = this.m_pairCount; this.m_pairBuffer.sort(b2PairLessThan); var i = 0; while (i < this.m_pairCount) { var primaryPair = this.m_pairBuffer[i]; var userDataA = primaryPair.proxyA.userData; var userDataB = primaryPair.proxyB.userData; userDataA && userDataB && callback(userDataA, userDataB); ++i; while (i < this.m_pairCount) { var pair = this.m_pairBuffer[i]; if (pair.proxyA.m_id !== primaryPair.proxyA.m_id || pair.proxyB.m_id !== primaryPair.proxyB.m_id) break; ++i; } } }; b2BroadPhase.prototype.Query = function(aabb, callback) { this.m_tree.Query(aabb, callback); }; b2BroadPhase.prototype.QueryPoint = function(point, callback) { this.m_tree.QueryPoint(point, callback); }; b2BroadPhase.prototype.RayCast = function(input, callback) { this.m_tree.RayCast(input, callback); }; b2BroadPhase.prototype.GetTreeHeight = function() { return this.m_tree.GetHeight(); }; b2BroadPhase.prototype.GetTreeBalance = function() { return this.m_tree.GetMaxBalance(); }; b2BroadPhase.prototype.GetTreeQuality = function() { return this.m_tree.GetAreaRatio(); }; b2BroadPhase.prototype.ShiftOrigin = function(newOrigin) { this.m_tree.ShiftOrigin(newOrigin); }; b2BroadPhase.prototype.BufferMove = function(proxy) { this.m_moveBuffer[this.m_moveCount] = proxy; ++this.m_moveCount; }; b2BroadPhase.prototype.UnBufferMove = function(proxy) { var i = this.m_moveBuffer.indexOf(proxy); this.m_moveBuffer[i] = null; }; return b2BroadPhase; })(); function b2PairLessThan(pair1, pair2) { if (pair1.proxyA.m_id === pair2.proxyA.m_id) return pair1.proxyB.m_id - pair2.proxyB.m_id; return pair1.proxyA.m_id - pair2.proxyA.m_id; } exports.b2_toiTime = 0; exports.b2_toiMaxTime = 0; exports.b2_toiCalls = 0; exports.b2_toiIters = 0; exports.b2_toiMaxIters = 0; exports.b2_toiRootIters = 0; exports.b2_toiMaxRootIters = 0; function b2_toi_reset() { exports.b2_toiTime = 0; exports.b2_toiMaxTime = 0; exports.b2_toiCalls = 0; exports.b2_toiIters = 0; exports.b2_toiMaxIters = 0; exports.b2_toiRootIters = 0; exports.b2_toiMaxRootIters = 0; } var b2TimeOfImpact_s_xfA = new b2Transform(); var b2TimeOfImpact_s_xfB = new b2Transform(); var b2TimeOfImpact_s_pointA = new b2Vec2(); var b2TimeOfImpact_s_pointB = new b2Vec2(); var b2TimeOfImpact_s_normal = new b2Vec2(); var b2TimeOfImpact_s_axisA = new b2Vec2(); var b2TimeOfImpact_s_axisB = new b2Vec2(); var b2TOIInput = (function() { function b2TOIInput() { this.proxyA = new b2DistanceProxy(); this.proxyB = new b2DistanceProxy(); this.sweepA = new b2Sweep(); this.sweepB = new b2Sweep(); this.tMax = 0; } return b2TOIInput; })(); (function(b2TOIOutputState) { b2TOIOutputState[b2TOIOutputState["e_unknown"] = 0] = "e_unknown"; b2TOIOutputState[b2TOIOutputState["e_failed"] = 1] = "e_failed"; b2TOIOutputState[b2TOIOutputState["e_overlapped"] = 2] = "e_overlapped"; b2TOIOutputState[b2TOIOutputState["e_touching"] = 3] = "e_touching"; b2TOIOutputState[b2TOIOutputState["e_separated"] = 4] = "e_separated"; })(exports.b2TOIOutputState || (exports.b2TOIOutputState = {})); var b2TOIOutput = (function() { function b2TOIOutput() { this.state = exports.b2TOIOutputState.e_unknown; this.t = 0; } return b2TOIOutput; })(); (function(b2SeparationFunctionType) { b2SeparationFunctionType[b2SeparationFunctionType["e_unknown"] = -1] = "e_unknown"; b2SeparationFunctionType[b2SeparationFunctionType["e_points"] = 0] = "e_points"; b2SeparationFunctionType[b2SeparationFunctionType["e_faceA"] = 1] = "e_faceA"; b2SeparationFunctionType[b2SeparationFunctionType["e_faceB"] = 2] = "e_faceB"; })(exports.b2SeparationFunctionType || (exports.b2SeparationFunctionType = {})); var b2SeparationFunction = (function() { function b2SeparationFunction() { this.m_sweepA = new b2Sweep(); this.m_sweepB = new b2Sweep(); this.m_type = exports.b2SeparationFunctionType.e_unknown; this.m_localPoint = new b2Vec2(); this.m_axis = new b2Vec2(); } b2SeparationFunction.prototype.Initialize = function(cache, proxyA, sweepA, proxyB, sweepB, t1) { this.m_proxyA = proxyA; this.m_proxyB = proxyB; var count = cache.count; this.m_sweepA.Copy(sweepA); this.m_sweepB.Copy(sweepB); var xfA = b2TimeOfImpact_s_xfA; var xfB = b2TimeOfImpact_s_xfB; this.m_sweepA.GetTransform(xfA, t1); this.m_sweepB.GetTransform(xfB, t1); if (1 === count) { this.m_type = exports.b2SeparationFunctionType.e_points; var localPointA = this.m_proxyA.GetVertex(cache.indexA[0]); var localPointB = this.m_proxyB.GetVertex(cache.indexB[0]); var pointA = b2Transform.MulXV(xfA, localPointA, b2TimeOfImpact_s_pointA); var pointB = b2Transform.MulXV(xfB, localPointB, b2TimeOfImpact_s_pointB); b2Vec2.SubVV(pointB, pointA, this.m_axis); var s = this.m_axis.Normalize(); this.m_localPoint.SetZero(); return s; } if (cache.indexA[0] === cache.indexA[1]) { this.m_type = exports.b2SeparationFunctionType.e_faceB; var localPointB1 = this.m_proxyB.GetVertex(cache.indexB[0]); var localPointB2 = this.m_proxyB.GetVertex(cache.indexB[1]); b2Vec2.CrossVOne(b2Vec2.SubVV(localPointB2, localPointB1, b2Vec2.s_t0), this.m_axis).SelfNormalize(); var normal = b2Rot.MulRV(xfB.q, this.m_axis, b2TimeOfImpact_s_normal); b2Vec2.MidVV(localPointB1, localPointB2, this.m_localPoint); var pointB = b2Transform.MulXV(xfB, this.m_localPoint, b2TimeOfImpact_s_pointB); var localPointA = this.m_proxyA.GetVertex(cache.indexA[0]); var pointA = b2Transform.MulXV(xfA, localPointA, b2TimeOfImpact_s_pointA); var s = b2Vec2.DotVV(b2Vec2.SubVV(pointA, pointB, b2Vec2.s_t0), normal); if (s < 0) { this.m_axis.SelfNeg(); s = -s; } return s; } this.m_type = exports.b2SeparationFunctionType.e_faceA; var localPointA1 = this.m_proxyA.GetVertex(cache.indexA[0]); var localPointA2 = this.m_proxyA.GetVertex(cache.indexA[1]); b2Vec2.CrossVOne(b2Vec2.SubVV(localPointA2, localPointA1, b2Vec2.s_t0), this.m_axis).SelfNormalize(); var normal = b2Rot.MulRV(xfA.q, this.m_axis, b2TimeOfImpact_s_normal); b2Vec2.MidVV(localPointA1, localPointA2, this.m_localPoint); var pointA = b2Transform.MulXV(xfA, this.m_localPoint, b2TimeOfImpact_s_pointA); var localPointB = this.m_proxyB.GetVertex(cache.indexB[0]); var pointB = b2Transform.MulXV(xfB, localPointB, b2TimeOfImpact_s_pointB); var s = b2Vec2.DotVV(b2Vec2.SubVV(pointB, pointA, b2Vec2.s_t0), normal); if (s < 0) { this.m_axis.SelfNeg(); s = -s; } return s; }; b2SeparationFunction.prototype.FindMinSeparation = function(indexA, indexB, t) { var xfA = b2TimeOfImpact_s_xfA; var xfB = b2TimeOfImpact_s_xfB; this.m_sweepA.GetTransform(xfA, t); this.m_sweepB.GetTransform(xfB, t); switch (this.m_type) { case exports.b2SeparationFunctionType.e_points: var axisA = b2Rot.MulTRV(xfA.q, this.m_axis, b2TimeOfImpact_s_axisA); var axisB = b2Rot.MulTRV(xfB.q, b2Vec2.NegV(this.m_axis, b2Vec2.s_t0), b2TimeOfImpact_s_axisB); indexA[0] = this.m_proxyA.GetSupport(axisA); indexB[0] = this.m_proxyB.GetSupport(axisB); var localPointA = this.m_proxyA.GetVertex(indexA[0]); var localPointB = this.m_proxyB.GetVertex(indexB[0]); var pointA = b2Transform.MulXV(xfA, localPointA, b2TimeOfImpact_s_pointA); var pointB = b2Transform.MulXV(xfB, localPointB, b2TimeOfImpact_s_pointB); var separation = b2Vec2.DotVV(b2Vec2.SubVV(pointB, pointA, b2Vec2.s_t0), this.m_axis); return separation; case exports.b2SeparationFunctionType.e_faceA: var normal = b2Rot.MulRV(xfA.q, this.m_axis, b2TimeOfImpact_s_normal); var pointA = b2Transform.MulXV(xfA, this.m_localPoint, b2TimeOfImpact_s_pointA); var axisB = b2Rot.MulTRV(xfB.q, b2Vec2.NegV(normal, b2Vec2.s_t0), b2TimeOfImpact_s_axisB); indexA[0] = -1; indexB[0] = this.m_proxyB.GetSupport(axisB); var localPointB = this.m_proxyB.GetVertex(indexB[0]); var pointB = b2Transform.MulXV(xfB, localPointB, b2TimeOfImpact_s_pointB); var separation = b2Vec2.DotVV(b2Vec2.SubVV(pointB, pointA, b2Vec2.s_t0), normal); return separation; case exports.b2SeparationFunctionType.e_faceB: var normal = b2Rot.MulRV(xfB.q, this.m_axis, b2TimeOfImpact_s_normal); var pointB = b2Transform.MulXV(xfB, this.m_localPoint, b2TimeOfImpact_s_pointB); var axisA = b2Rot.MulTRV(xfA.q, b2Vec2.NegV(normal, b2Vec2.s_t0), b2TimeOfImpact_s_axisA); indexB[0] = -1; indexA[0] = this.m_proxyA.GetSupport(axisA); var localPointA = this.m_proxyA.GetVertex(indexA[0]); var pointA = b2Transform.MulXV(xfA, localPointA, b2TimeOfImpact_s_pointA); var separation = b2Vec2.DotVV(b2Vec2.SubVV(pointA, pointB, b2Vec2.s_t0), normal); return separation; default: indexA[0] = -1; indexB[0] = -1; return 0; } }; b2SeparationFunction.prototype.Evaluate = function(indexA, indexB, t) { var xfA = b2TimeOfImpact_s_xfA; var xfB = b2TimeOfImpact_s_xfB; this.m_sweepA.GetTransform(xfA, t); this.m_sweepB.GetTransform(xfB, t); switch (this.m_type) { case exports.b2SeparationFunctionType.e_points: var localPointA = this.m_proxyA.GetVertex(indexA); var localPointB = this.m_proxyB.GetVertex(indexB); var pointA = b2Transform.MulXV(xfA, localPointA, b2TimeOfImpact_s_pointA); var pointB = b2Transform.MulXV(xfB, localPointB, b2TimeOfImpact_s_pointB); var separation = b2Vec2.DotVV(b2Vec2.SubVV(pointB, pointA, b2Vec2.s_t0), this.m_axis); return separation; case exports.b2SeparationFunctionType.e_faceA: var normal = b2Rot.MulRV(xfA.q, this.m_axis, b2TimeOfImpact_s_normal); var pointA = b2Transform.MulXV(xfA, this.m_localPoint, b2TimeOfImpact_s_pointA); var localPointB = this.m_proxyB.GetVertex(indexB); var pointB = b2Transform.MulXV(xfB, localPointB, b2TimeOfImpact_s_pointB); var separation = b2Vec2.DotVV(b2Vec2.SubVV(pointB, pointA, b2Vec2.s_t0), normal); return separation; case exports.b2SeparationFunctionType.e_faceB: var normal = b2Rot.MulRV(xfB.q, this.m_axis, b2TimeOfImpact_s_normal); var pointB = b2Transform.MulXV(xfB, this.m_localPoint, b2TimeOfImpact_s_pointB); var localPointA = this.m_proxyA.GetVertex(indexA); var pointA = b2Transform.MulXV(xfA, localPointA, b2TimeOfImpact_s_pointA); var separation = b2Vec2.DotVV(b2Vec2.SubVV(pointA, pointB, b2Vec2.s_t0), normal); return separation; default: return 0; } }; return b2SeparationFunction; })(); var b2TimeOfImpact_s_timer = new b2Timer(); var b2TimeOfImpact_s_cache = new b2SimplexCache(); var b2TimeOfImpact_s_distanceInput = new b2DistanceInput(); var b2TimeOfImpact_s_distanceOutput = new b2DistanceOutput(); var b2TimeOfImpact_s_fcn = new b2SeparationFunction(); var b2TimeOfImpact_s_indexA = [ 0 ]; var b2TimeOfImpact_s_indexB = [ 0 ]; var b2TimeOfImpact_s_sweepA = new b2Sweep(); var b2TimeOfImpact_s_sweepB = new b2Sweep(); function b2TimeOfImpact(output, input) { var timer = b2TimeOfImpact_s_timer.Reset(); ++exports.b2_toiCalls; output.state = exports.b2TOIOutputState.e_unknown; output.t = input.tMax; var proxyA = input.proxyA; var proxyB = input.proxyB; var sweepA = b2TimeOfImpact_s_sweepA.Copy(input.sweepA); var sweepB = b2TimeOfImpact_s_sweepB.Copy(input.sweepB); sweepA.Normalize(); sweepB.Normalize(); var tMax = input.tMax; var totalRadius = proxyA.m_radius + proxyB.m_radius; var target = b2Max(b2_linearSlop, totalRadius - 3 * b2_linearSlop); var tolerance = .25 * b2_linearSlop; var t1 = 0; var k_maxIterations = 20; var iter = 0; var cache = b2TimeOfImpact_s_cache; cache.count = 0; var distanceInput = b2TimeOfImpact_s_distanceInput; distanceInput.proxyA.Copy(input.proxyA); distanceInput.proxyB.Copy(input.proxyB); distanceInput.useRadii = false; for (;;) { var xfA = b2TimeOfImpact_s_xfA; var xfB = b2TimeOfImpact_s_xfB; sweepA.GetTransform(xfA, t1); sweepB.GetTransform(xfB, t1); distanceInput.transformA.Copy(xfA); distanceInput.transformB.Copy(xfB); var distanceOutput = b2TimeOfImpact_s_distanceOutput; b2Distance(distanceOutput, cache, distanceInput); if (distanceOutput.distance <= 0) { output.state = exports.b2TOIOutputState.e_overlapped; output.t = 0; break; } if (distanceOutput.distance < target + tolerance) { output.state = exports.b2TOIOutputState.e_touching; output.t = t1; break; } var fcn = b2TimeOfImpact_s_fcn; fcn.Initialize(cache, proxyA, sweepA, proxyB, sweepB, t1); var done = false; var t2 = tMax; var pushBackIter = 0; for (;;) { var indexA = b2TimeOfImpact_s_indexA; var indexB = b2TimeOfImpact_s_indexB; var s2 = fcn.FindMinSeparation(indexA, indexB, t2); if (s2 > target + tolerance) { output.state = exports.b2TOIOutputState.e_separated; output.t = tMax; done = true; break; } if (s2 > target - tolerance) { t1 = t2; break; } var s1 = fcn.Evaluate(indexA[0], indexB[0], t1); if (s1 < target - tolerance) { output.state = exports.b2TOIOutputState.e_failed; output.t = t1; done = true; break; } if (s1 <= target + tolerance) { output.state = exports.b2TOIOutputState.e_touching; output.t = t1; done = true; break; } var rootIterCount = 0; var a1 = t1; var a2 = t2; for (;;) { var t = 0; t = 1 & rootIterCount ? a1 + (target - s1) * (a2 - a1) / (s2 - s1) : .5 * (a1 + a2); ++rootIterCount; ++exports.b2_toiRootIters; var s = fcn.Evaluate(indexA[0], indexB[0], t); if (b2Abs(s - target) < tolerance) { t2 = t; break; } if (s > target) { a1 = t; s1 = s; } else { a2 = t; s2 = s; } if (50 === rootIterCount) break; } exports.b2_toiMaxRootIters = b2Max(exports.b2_toiMaxRootIters, rootIterCount); ++pushBackIter; if (pushBackIter === b2_maxPolygonVertices) break; } ++iter; ++exports.b2_toiIters; if (done) break; if (iter === k_maxIterations) { output.state = exports.b2TOIOutputState.e_failed; output.t = t1; break; } } exports.b2_toiMaxIters = b2Max(exports.b2_toiMaxIters, iter); var time = timer.GetMilliseconds(); exports.b2_toiMaxTime = b2Max(exports.b2_toiMaxTime, time); exports.b2_toiTime += time; } var b2CollideCircles_s_pA = new b2Vec2(); var b2CollideCircles_s_pB = new b2Vec2(); function b2CollideCircles(manifold, circleA, xfA, circleB, xfB) { manifold.pointCount = 0; var pA = b2Transform.MulXV(xfA, circleA.m_p, b2CollideCircles_s_pA); var pB = b2Transform.MulXV(xfB, circleB.m_p, b2CollideCircles_s_pB); var distSqr = b2Vec2.DistanceSquaredVV(pA, pB); var radius = circleA.m_radius + circleB.m_radius; if (distSqr > radius * radius) return; manifold.type = exports.b2ManifoldType.e_circles; manifold.localPoint.Copy(circleA.m_p); manifold.localNormal.SetZero(); manifold.pointCount = 1; manifold.points[0].localPoint.Copy(circleB.m_p); manifold.points[0].id.key = 0; } var b2CollidePolygonAndCircle_s_c = new b2Vec2(); var b2CollidePolygonAndCircle_s_cLocal = new b2Vec2(); var b2CollidePolygonAndCircle_s_faceCenter = new b2Vec2(); function b2CollidePolygonAndCircle(manifold, polygonA, xfA, circleB, xfB) { manifold.pointCount = 0; var c = b2Transform.MulXV(xfB, circleB.m_p, b2CollidePolygonAndCircle_s_c); var cLocal = b2Transform.MulTXV(xfA, c, b2CollidePolygonAndCircle_s_cLocal); var normalIndex = 0; var separation = -b2_maxFloat; var radius = polygonA.m_radius + circleB.m_radius; var vertexCount = polygonA.m_count; var vertices = polygonA.m_vertices; var normals = polygonA.m_normals; for (var i = 0; i < vertexCount; ++i) { var s = b2Vec2.DotVV(normals[i], b2Vec2.SubVV(cLocal, vertices[i], b2Vec2.s_t0)); if (s > radius) return; if (s > separation) { separation = s; normalIndex = i; } } var vertIndex1 = normalIndex; var vertIndex2 = (vertIndex1 + 1) % vertexCount; var v1 = vertices[vertIndex1]; var v2 = vertices[vertIndex2]; if (separation < b2_epsilon) { manifold.pointCount = 1; manifold.type = exports.b2ManifoldType.e_faceA; manifold.localNormal.Copy(normals[normalIndex]); b2Vec2.MidVV(v1, v2, manifold.localPoint); manifold.points[0].localPoint.Copy(circleB.m_p); manifold.points[0].id.key = 0; return; } var u1 = b2Vec2.DotVV(b2Vec2.SubVV(cLocal, v1, b2Vec2.s_t0), b2Vec2.SubVV(v2, v1, b2Vec2.s_t1)); var u2 = b2Vec2.DotVV(b2Vec2.SubVV(cLocal, v2, b2Vec2.s_t0), b2Vec2.SubVV(v1, v2, b2Vec2.s_t1)); if (u1 <= 0) { if (b2Vec2.DistanceSquaredVV(cLocal, v1) > radius * radius) return; manifold.pointCount = 1; manifold.type = exports.b2ManifoldType.e_faceA; b2Vec2.SubVV(cLocal, v1, manifold.localNormal).SelfNormalize(); manifold.localPoint.Copy(v1); manifold.points[0].localPoint.Copy(circleB.m_p); manifold.points[0].id.key = 0; } else if (u2 <= 0) { if (b2Vec2.DistanceSquaredVV(cLocal, v2) > radius * radius) return; manifold.pointCount = 1; manifold.type = exports.b2ManifoldType.e_faceA; b2Vec2.SubVV(cLocal, v2, manifold.localNormal).SelfNormalize(); manifold.localPoint.Copy(v2); manifold.points[0].localPoint.Copy(circleB.m_p); manifold.points[0].id.key = 0; } else { var faceCenter = b2Vec2.MidVV(v1, v2, b2CollidePolygonAndCircle_s_faceCenter); var separation_1 = b2Vec2.DotVV(b2Vec2.SubVV(cLocal, faceCenter, b2Vec2.s_t1), normals[vertIndex1]); if (separation_1 > radius) return; manifold.pointCount = 1; manifold.type = exports.b2ManifoldType.e_faceA; manifold.localNormal.Copy(normals[vertIndex1]).SelfNormalize(); manifold.localPoint.Copy(faceCenter); manifold.points[0].localPoint.Copy(circleB.m_p); manifold.points[0].id.key = 0; } } var b2EdgeSeparation_s_normal1World = new b2Vec2(); var b2EdgeSeparation_s_normal1 = new b2Vec2(); var b2EdgeSeparation_s_v1 = new b2Vec2(); var b2EdgeSeparation_s_v2 = new b2Vec2(); function b2EdgeSeparation(poly1, xf1, edge1, poly2, xf2) { var vertices1 = poly1.m_vertices; var normals1 = poly1.m_normals; var count2 = poly2.m_count; var vertices2 = poly2.m_vertices; var normal1World = b2Rot.MulRV(xf1.q, normals1[edge1], b2EdgeSeparation_s_normal1World); var normal1 = b2Rot.MulTRV(xf2.q, normal1World, b2EdgeSeparation_s_normal1); var index = 0; var minDot = b2_maxFloat; for (var i = 0; i < count2; ++i) { var dot = b2Vec2.DotVV(vertices2[i], normal1); if (dot < minDot) { minDot = dot; index = i; } } var v1 = b2Transform.MulXV(xf1, vertices1[edge1], b2EdgeSeparation_s_v1); var v2 = b2Transform.MulXV(xf2, vertices2[index], b2EdgeSeparation_s_v2); var separation = b2Vec2.DotVV(b2Vec2.SubVV(v2, v1, b2Vec2.s_t0), normal1World); return separation; } var b2FindMaxSeparation_s_d = new b2Vec2(); var b2FindMaxSeparation_s_dLocal1 = new b2Vec2(); function b2FindMaxSeparation(edgeIndex, poly1, xf1, poly2, xf2) { var count1 = poly1.m_count; var normals1 = poly1.m_normals; var d = b2Vec2.SubVV(b2Transform.MulXV(xf2, poly2.m_centroid, b2Vec2.s_t0), b2Transform.MulXV(xf1, poly1.m_centroid, b2Vec2.s_t1), b2FindMaxSeparation_s_d); var dLocal1 = b2Rot.MulTRV(xf1.q, d, b2FindMaxSeparation_s_dLocal1); var edge = 0; var maxDot = -b2_maxFloat; for (var i = 0; i < count1; ++i) { var dot = b2Vec2.DotVV(normals1[i], dLocal1); if (dot > maxDot) { maxDot = dot; edge = i; } } var s = b2EdgeSeparation(poly1, xf1, edge, poly2, xf2); var prevEdge = (edge + count1 - 1) % count1; var sPrev = b2EdgeSeparation(poly1, xf1, prevEdge, poly2, xf2); var nextEdge = (edge + 1) % count1; var sNext = b2EdgeSeparation(poly1, xf1, nextEdge, poly2, xf2); var bestEdge = 0; var bestSeparation = 0; var increment = 0; if (sPrev > s && sPrev > sNext) { increment = -1; bestEdge = prevEdge; bestSeparation = sPrev; } else { if (!(sNext > s)) { edgeIndex[0] = edge; return s; } increment = 1; bestEdge = nextEdge; bestSeparation = sNext; } while (true) { edge = -1 === increment ? (bestEdge + count1 - 1) % count1 : (bestEdge + 1) % count1; s = b2EdgeSeparation(poly1, xf1, edge, poly2, xf2); if (!(s > bestSeparation)) break; bestEdge = edge; bestSeparation = s; } edgeIndex[0] = bestEdge; return bestSeparation; } var b2FindIncidentEdge_s_normal1 = new b2Vec2(); function b2FindIncidentEdge(c, poly1, xf1, edge1, poly2, xf2) { var normals1 = poly1.m_normals; var count2 = poly2.m_count; var vertices2 = poly2.m_vertices; var normals2 = poly2.m_normals; var normal1 = b2Rot.MulTRV(xf2.q, b2Rot.MulRV(xf1.q, normals1[edge1], b2Vec2.s_t0), b2FindIncidentEdge_s_normal1); var index = 0; var minDot = b2_maxFloat; for (var i = 0; i < count2; ++i) { var dot = b2Vec2.DotVV(normal1, normals2[i]); if (dot < minDot) { minDot = dot; index = i; } } var i1 = index; var i2 = (i1 + 1) % count2; var c0 = c[0]; b2Transform.MulXV(xf2, vertices2[i1], c0.v); var cf0 = c0.id.cf; cf0.indexA = edge1; cf0.indexB = i1; cf0.typeA = exports.b2ContactFeatureType.e_face; cf0.typeB = exports.b2ContactFeatureType.e_vertex; var c1 = c[1]; b2Transform.MulXV(xf2, vertices2[i2], c1.v); var cf1 = c1.id.cf; cf1.indexA = edge1; cf1.indexB = i2; cf1.typeA = exports.b2ContactFeatureType.e_face; cf1.typeB = exports.b2ContactFeatureType.e_vertex; } var b2CollidePolygons_s_incidentEdge = b2ClipVertex.MakeArray(2); var b2CollidePolygons_s_clipPoints1 = b2ClipVertex.MakeArray(2); var b2CollidePolygons_s_clipPoints2 = b2ClipVertex.MakeArray(2); var b2CollidePolygons_s_edgeA = [ 0 ]; var b2CollidePolygons_s_edgeB = [ 0 ]; var b2CollidePolygons_s_localTangent = new b2Vec2(); var b2CollidePolygons_s_localNormal = new b2Vec2(); var b2CollidePolygons_s_planePoint = new b2Vec2(); var b2CollidePolygons_s_normal = new b2Vec2(); var b2CollidePolygons_s_tangent = new b2Vec2(); var b2CollidePolygons_s_ntangent = new b2Vec2(); var b2CollidePolygons_s_v11 = new b2Vec2(); var b2CollidePolygons_s_v12 = new b2Vec2(); function b2CollidePolygons(manifold, polyA, xfA, polyB, xfB) { manifold.pointCount = 0; var totalRadius = polyA.m_radius + polyB.m_radius; var edgeA = b2CollidePolygons_s_edgeA; edgeA[0] = 0; var separationA = b2FindMaxSeparation(edgeA, polyA, xfA, polyB, xfB); if (separationA > totalRadius) return; var edgeB = b2CollidePolygons_s_edgeB; edgeB[0] = 0; var separationB = b2FindMaxSeparation(edgeB, polyB, xfB, polyA, xfA); if (separationB > totalRadius) return; var poly1; var poly2; var xf1, xf2; var edge1 = 0; var flip = 0; var k_relativeTol = .98; var k_absoluteTol = .001; if (separationB > k_relativeTol * separationA + k_absoluteTol) { poly1 = polyB; poly2 = polyA; xf1 = xfB; xf2 = xfA; edge1 = edgeB[0]; manifold.type = exports.b2ManifoldType.e_faceB; flip = 1; } else { poly1 = polyA; poly2 = polyB; xf1 = xfA; xf2 = xfB; edge1 = edgeA[0]; manifold.type = exports.b2ManifoldType.e_faceA; flip = 0; } var incidentEdge = b2CollidePolygons_s_incidentEdge; b2FindIncidentEdge(incidentEdge, poly1, xf1, edge1, poly2, xf2); var count1 = poly1.m_count; var vertices1 = poly1.m_vertices; var iv1 = edge1; var iv2 = (edge1 + 1) % count1; var local_v11 = vertices1[iv1]; var local_v12 = vertices1[iv2]; var localTangent = b2Vec2.SubVV(local_v12, local_v11, b2CollidePolygons_s_localTangent); localTangent.Normalize(); var localNormal = b2Vec2.CrossVOne(localTangent, b2CollidePolygons_s_localNormal); var planePoint = b2Vec2.MidVV(local_v11, local_v12, b2CollidePolygons_s_planePoint); var tangent = b2Rot.MulRV(xf1.q, localTangent, b2CollidePolygons_s_tangent); var normal = b2Vec2.CrossVOne(tangent, b2CollidePolygons_s_normal); var v11 = b2Transform.MulXV(xf1, local_v11, b2CollidePolygons_s_v11); var v12 = b2Transform.MulXV(xf1, local_v12, b2CollidePolygons_s_v12); var frontOffset = b2Vec2.DotVV(normal, v11); var sideOffset1 = -b2Vec2.DotVV(tangent, v11) + totalRadius; var sideOffset2 = b2Vec2.DotVV(tangent, v12) + totalRadius; var clipPoints1 = b2CollidePolygons_s_clipPoints1; var clipPoints2 = b2CollidePolygons_s_clipPoints2; var np; var ntangent = b2Vec2.NegV(tangent, b2CollidePolygons_s_ntangent); np = b2ClipSegmentToLine(clipPoints1, incidentEdge, ntangent, sideOffset1, iv1); if (np < 2) return; np = b2ClipSegmentToLine(clipPoints2, clipPoints1, tangent, sideOffset2, iv2); if (np < 2) return; manifold.localNormal.Copy(localNormal); manifold.localPoint.Copy(planePoint); var pointCount = 0; for (var i = 0; i < b2_maxManifoldPoints; ++i) { var cv = clipPoints2[i]; var separation = b2Vec2.DotVV(normal, cv.v) - frontOffset; if (separation <= totalRadius) { var cp = manifold.points[pointCount]; b2Transform.MulTXV(xf2, cv.v, cp.localPoint); cp.id.Copy(cv.id); if (flip) { var cf = cp.id.cf; cp.id.cf.indexA = cf.indexB; cp.id.cf.indexB = cf.indexA; cp.id.cf.typeA = cf.typeB; cp.id.cf.typeB = cf.typeA; } ++pointCount; } } manifold.pointCount = pointCount; } var b2CollideEdgeAndCircle_s_Q = new b2Vec2(); var b2CollideEdgeAndCircle_s_e = new b2Vec2(); var b2CollideEdgeAndCircle_s_d = new b2Vec2(); var b2CollideEdgeAndCircle_s_e1 = new b2Vec2(); var b2CollideEdgeAndCircle_s_e2 = new b2Vec2(); var b2CollideEdgeAndCircle_s_P = new b2Vec2(); var b2CollideEdgeAndCircle_s_n = new b2Vec2(); var b2CollideEdgeAndCircle_s_id = new b2ContactID(); function b2CollideEdgeAndCircle(manifold, edgeA, xfA, circleB, xfB) { manifold.pointCount = 0; var Q = b2Transform.MulTXV(xfA, b2Transform.MulXV(xfB, circleB.m_p, b2Vec2.s_t0), b2CollideEdgeAndCircle_s_Q); var A = edgeA.m_vertex1; var B = edgeA.m_vertex2; var e = b2Vec2.SubVV(B, A, b2CollideEdgeAndCircle_s_e); var u = b2Vec2.DotVV(e, b2Vec2.SubVV(B, Q, b2Vec2.s_t0)); var v = b2Vec2.DotVV(e, b2Vec2.SubVV(Q, A, b2Vec2.s_t0)); var radius = edgeA.m_radius + circleB.m_radius; var id = b2CollideEdgeAndCircle_s_id; id.cf.indexB = 0; id.cf.typeB = exports.b2ContactFeatureType.e_vertex; if (v <= 0) { var P_1 = A; var d_1 = b2Vec2.SubVV(Q, P_1, b2CollideEdgeAndCircle_s_d); var dd_1 = b2Vec2.DotVV(d_1, d_1); if (dd_1 > radius * radius) return; if (edgeA.m_hasVertex0) { var A1 = edgeA.m_vertex0; var B1 = A; var e1 = b2Vec2.SubVV(B1, A1, b2CollideEdgeAndCircle_s_e1); var u1 = b2Vec2.DotVV(e1, b2Vec2.SubVV(B1, Q, b2Vec2.s_t0)); if (u1 > 0) return; } id.cf.indexA = 0; id.cf.typeA = exports.b2ContactFeatureType.e_vertex; manifold.pointCount = 1; manifold.type = exports.b2ManifoldType.e_circles; manifold.localNormal.SetZero(); manifold.localPoint.Copy(P_1); manifold.points[0].id.Copy(id); manifold.points[0].localPoint.Copy(circleB.m_p); return; } if (u <= 0) { var P_2 = B; var d_2 = b2Vec2.SubVV(Q, P_2, b2CollideEdgeAndCircle_s_d); var dd_2 = b2Vec2.DotVV(d_2, d_2); if (dd_2 > radius * radius) return; if (edgeA.m_hasVertex3) { var B2 = edgeA.m_vertex3; var A2 = B; var e2 = b2Vec2.SubVV(B2, A2, b2CollideEdgeAndCircle_s_e2); var v2 = b2Vec2.DotVV(e2, b2Vec2.SubVV(Q, A2, b2Vec2.s_t0)); if (v2 > 0) return; } id.cf.indexA = 1; id.cf.typeA = exports.b2ContactFeatureType.e_vertex; manifold.pointCount = 1; manifold.type = exports.b2ManifoldType.e_circles; manifold.localNormal.SetZero(); manifold.localPoint.Copy(P_2); manifold.points[0].id.Copy(id); manifold.points[0].localPoint.Copy(circleB.m_p); return; } var den = b2Vec2.DotVV(e, e); var P = b2CollideEdgeAndCircle_s_P; P.x = 1 / den * (u * A.x + v * B.x); P.y = 1 / den * (u * A.y + v * B.y); var d = b2Vec2.SubVV(Q, P, b2CollideEdgeAndCircle_s_d); var dd = b2Vec2.DotVV(d, d); if (dd > radius * radius) return; var n = b2CollideEdgeAndCircle_s_n.Set(-e.y, e.x); b2Vec2.DotVV(n, b2Vec2.SubVV(Q, A, b2Vec2.s_t0)) < 0 && n.Set(-n.x, -n.y); n.Normalize(); id.cf.indexA = 0; id.cf.typeA = exports.b2ContactFeatureType.e_face; manifold.pointCount = 1; manifold.type = exports.b2ManifoldType.e_faceA; manifold.localNormal.Copy(n); manifold.localPoint.Copy(A); manifold.points[0].id.Copy(id); manifold.points[0].localPoint.Copy(circleB.m_p); } var b2EPAxis = (function() { function b2EPAxis() { this.type = 0; this.index = 0; this.separation = 0; } return b2EPAxis; })(); var b2TempPolygon = (function() { function b2TempPolygon() { this.vertices = b2Vec2.MakeArray(b2_maxPolygonVertices); this.normals = b2Vec2.MakeArray(b2_maxPolygonVertices); this.count = 0; } return b2TempPolygon; })(); var b2ReferenceFace = (function() { function b2ReferenceFace() { this.i1 = 0; this.i2 = 0; this.v1 = new b2Vec2(); this.v2 = new b2Vec2(); this.normal = new b2Vec2(); this.sideNormal1 = new b2Vec2(); this.sideOffset1 = 0; this.sideNormal2 = new b2Vec2(); this.sideOffset2 = 0; } return b2ReferenceFace; })(); var b2EPCollider = (function() { function b2EPCollider() { this.m_polygonB = new b2TempPolygon(); this.m_xf = new b2Transform(); this.m_centroidB = new b2Vec2(); this.m_v0 = new b2Vec2(); this.m_v1 = new b2Vec2(); this.m_v2 = new b2Vec2(); this.m_v3 = new b2Vec2(); this.m_normal0 = new b2Vec2(); this.m_normal1 = new b2Vec2(); this.m_normal2 = new b2Vec2(); this.m_normal = new b2Vec2(); this.m_type1 = 0; this.m_type2 = 0; this.m_lowerLimit = new b2Vec2(); this.m_upperLimit = new b2Vec2(); this.m_radius = 0; this.m_front = false; } b2EPCollider.prototype.Collide = function(manifold, edgeA, xfA, polygonB, xfB) { b2Transform.MulTXX(xfA, xfB, this.m_xf); b2Transform.MulXV(this.m_xf, polygonB.m_centroid, this.m_centroidB); this.m_v0.Copy(edgeA.m_vertex0); this.m_v1.Copy(edgeA.m_vertex1); this.m_v2.Copy(edgeA.m_vertex2); this.m_v3.Copy(edgeA.m_vertex3); var hasVertex0 = edgeA.m_hasVertex0; var hasVertex3 = edgeA.m_hasVertex3; var edge1 = b2Vec2.SubVV(this.m_v2, this.m_v1, b2EPCollider.s_edge1); edge1.Normalize(); this.m_normal1.Set(edge1.y, -edge1.x); var offset1 = b2Vec2.DotVV(this.m_normal1, b2Vec2.SubVV(this.m_centroidB, this.m_v1, b2Vec2.s_t0)); var offset0 = 0; var offset2 = 0; var convex1 = false; var convex2 = false; if (hasVertex0) { var edge0 = b2Vec2.SubVV(this.m_v1, this.m_v0, b2EPCollider.s_edge0); edge0.Normalize(); this.m_normal0.Set(edge0.y, -edge0.x); convex1 = b2Vec2.CrossVV(edge0, edge1) >= 0; offset0 = b2Vec2.DotVV(this.m_normal0, b2Vec2.SubVV(this.m_centroidB, this.m_v0, b2Vec2.s_t0)); } if (hasVertex3) { var edge2 = b2Vec2.SubVV(this.m_v3, this.m_v2, b2EPCollider.s_edge2); edge2.Normalize(); this.m_normal2.Set(edge2.y, -edge2.x); convex2 = b2Vec2.CrossVV(edge1, edge2) > 0; offset2 = b2Vec2.DotVV(this.m_normal2, b2Vec2.SubVV(this.m_centroidB, this.m_v2, b2Vec2.s_t0)); } if (hasVertex0 && hasVertex3) if (convex1 && convex2) { this.m_front = offset0 >= 0 || offset1 >= 0 || offset2 >= 0; if (this.m_front) { this.m_normal.Copy(this.m_normal1); this.m_lowerLimit.Copy(this.m_normal0); this.m_upperLimit.Copy(this.m_normal2); } else { this.m_normal.Copy(this.m_normal1).SelfNeg(); this.m_lowerLimit.Copy(this.m_normal1).SelfNeg(); this.m_upperLimit.Copy(this.m_normal1).SelfNeg(); } } else if (convex1) { this.m_front = offset0 >= 0 || offset1 >= 0 && offset2 >= 0; if (this.m_front) { this.m_normal.Copy(this.m_normal1); this.m_lowerLimit.Copy(this.m_normal0); this.m_upperLimit.Copy(this.m_normal1); } else { this.m_normal.Copy(this.m_normal1).SelfNeg(); this.m_lowerLimit.Copy(this.m_normal2).SelfNeg(); this.m_upperLimit.Copy(this.m_normal1).SelfNeg(); } } else if (convex2) { this.m_front = offset2 >= 0 || offset0 >= 0 && offset1 >= 0; if (this.m_front) { this.m_normal.Copy(this.m_normal1); this.m_lowerLimit.Copy(this.m_normal1); this.m_upperLimit.Copy(this.m_normal2); } else { this.m_normal.Copy(this.m_normal1).SelfNeg(); this.m_lowerLimit.Copy(this.m_normal1).SelfNeg(); this.m_upperLimit.Copy(this.m_normal0).SelfNeg(); } } else { this.m_front = offset0 >= 0 && offset1 >= 0 && offset2 >= 0; if (this.m_front) { this.m_normal.Copy(this.m_normal1); this.m_lowerLimit.Copy(this.m_normal1); this.m_upperLimit.Copy(this.m_normal1); } else { this.m_normal.Copy(this.m_normal1).SelfNeg(); this.m_lowerLimit.Copy(this.m_normal2).SelfNeg(); this.m_upperLimit.Copy(this.m_normal0).SelfNeg(); } } else if (hasVertex0) if (convex1) { this.m_front = offset0 >= 0 || offset1 >= 0; if (this.m_front) { this.m_normal.Copy(this.m_normal1); this.m_lowerLimit.Copy(this.m_normal0); this.m_upperLimit.Copy(this.m_normal1).SelfNeg(); } else { this.m_normal.Copy(this.m_normal1).SelfNeg(); this.m_lowerLimit.Copy(this.m_normal1); this.m_upperLimit.Copy(this.m_normal1).SelfNeg(); } } else { this.m_front = offset0 >= 0 && offset1 >= 0; if (this.m_front) { this.m_normal.Copy(this.m_normal1); this.m_lowerLimit.Copy(this.m_normal1); this.m_upperLimit.Copy(this.m_normal1).SelfNeg(); } else { this.m_normal.Copy(this.m_normal1).SelfNeg(); this.m_lowerLimit.Copy(this.m_normal1); this.m_upperLimit.Copy(this.m_normal0).SelfNeg(); } } else if (hasVertex3) if (convex2) { this.m_front = offset1 >= 0 || offset2 >= 0; if (this.m_front) { this.m_normal.Copy(this.m_normal1); this.m_lowerLimit.Copy(this.m_normal1).SelfNeg(); this.m_upperLimit.Copy(this.m_normal2); } else { this.m_normal.Copy(this.m_normal1).SelfNeg(); this.m_lowerLimit.Copy(this.m_normal1).SelfNeg(); this.m_upperLimit.Copy(this.m_normal1); } } else { this.m_front = offset1 >= 0 && offset2 >= 0; if (this.m_front) { this.m_normal.Copy(this.m_normal1); this.m_lowerLimit.Copy(this.m_normal1).SelfNeg(); this.m_upperLimit.Copy(this.m_normal1); } else { this.m_normal.Copy(this.m_normal1).SelfNeg(); this.m_lowerLimit.Copy(this.m_normal2).SelfNeg(); this.m_upperLimit.Copy(this.m_normal1); } } else { this.m_front = offset1 >= 0; if (this.m_front) { this.m_normal.Copy(this.m_normal1); this.m_lowerLimit.Copy(this.m_normal1).SelfNeg(); this.m_upperLimit.Copy(this.m_normal1).SelfNeg(); } else { this.m_normal.Copy(this.m_normal1).SelfNeg(); this.m_lowerLimit.Copy(this.m_normal1); this.m_upperLimit.Copy(this.m_normal1); } } this.m_polygonB.count = polygonB.m_count; for (var i = 0; i < polygonB.m_count; ++i) { b2Transform.MulXV(this.m_xf, polygonB.m_vertices[i], this.m_polygonB.vertices[i]); b2Rot.MulRV(this.m_xf.q, polygonB.m_normals[i], this.m_polygonB.normals[i]); } this.m_radius = polygonB.m_radius + edgeA.m_radius; manifold.pointCount = 0; var edgeAxis = this.ComputeEdgeSeparation(b2EPCollider.s_edgeAxis); if (0 === edgeAxis.type) return; if (edgeAxis.separation > this.m_radius) return; var polygonAxis = this.ComputePolygonSeparation(b2EPCollider.s_polygonAxis); if (0 !== polygonAxis.type && polygonAxis.separation > this.m_radius) return; var k_relativeTol = .98; var k_absoluteTol = .001; var primaryAxis; primaryAxis = 0 === polygonAxis.type ? edgeAxis : polygonAxis.separation > k_relativeTol * edgeAxis.separation + k_absoluteTol ? polygonAxis : edgeAxis; var ie = b2EPCollider.s_ie; var rf = b2EPCollider.s_rf; if (1 === primaryAxis.type) { manifold.type = exports.b2ManifoldType.e_faceA; var bestIndex = 0; var bestValue = b2Vec2.DotVV(this.m_normal, this.m_polygonB.normals[0]); for (var i = 1; i < this.m_polygonB.count; ++i) { var value = b2Vec2.DotVV(this.m_normal, this.m_polygonB.normals[i]); if (value < bestValue) { bestValue = value; bestIndex = i; } } var i1 = bestIndex; var i2 = (i1 + 1) % this.m_polygonB.count; var ie0 = ie[0]; ie0.v.Copy(this.m_polygonB.vertices[i1]); ie0.id.cf.indexA = 0; ie0.id.cf.indexB = i1; ie0.id.cf.typeA = exports.b2ContactFeatureType.e_face; ie0.id.cf.typeB = exports.b2ContactFeatureType.e_vertex; var ie1 = ie[1]; ie1.v.Copy(this.m_polygonB.vertices[i2]); ie1.id.cf.indexA = 0; ie1.id.cf.indexB = i2; ie1.id.cf.typeA = exports.b2ContactFeatureType.e_face; ie1.id.cf.typeB = exports.b2ContactFeatureType.e_vertex; if (this.m_front) { rf.i1 = 0; rf.i2 = 1; rf.v1.Copy(this.m_v1); rf.v2.Copy(this.m_v2); rf.normal.Copy(this.m_normal1); } else { rf.i1 = 1; rf.i2 = 0; rf.v1.Copy(this.m_v2); rf.v2.Copy(this.m_v1); rf.normal.Copy(this.m_normal1).SelfNeg(); } } else { manifold.type = exports.b2ManifoldType.e_faceB; var ie0 = ie[0]; ie0.v.Copy(this.m_v1); ie0.id.cf.indexA = 0; ie0.id.cf.indexB = primaryAxis.index; ie0.id.cf.typeA = exports.b2ContactFeatureType.e_vertex; ie0.id.cf.typeB = exports.b2ContactFeatureType.e_face; var ie1 = ie[1]; ie1.v.Copy(this.m_v2); ie1.id.cf.indexA = 0; ie1.id.cf.indexB = primaryAxis.index; ie1.id.cf.typeA = exports.b2ContactFeatureType.e_vertex; ie1.id.cf.typeB = exports.b2ContactFeatureType.e_face; rf.i1 = primaryAxis.index; rf.i2 = (rf.i1 + 1) % this.m_polygonB.count; rf.v1.Copy(this.m_polygonB.vertices[rf.i1]); rf.v2.Copy(this.m_polygonB.vertices[rf.i2]); rf.normal.Copy(this.m_polygonB.normals[rf.i1]); } rf.sideNormal1.Set(rf.normal.y, -rf.normal.x); rf.sideNormal2.Copy(rf.sideNormal1).SelfNeg(); rf.sideOffset1 = b2Vec2.DotVV(rf.sideNormal1, rf.v1); rf.sideOffset2 = b2Vec2.DotVV(rf.sideNormal2, rf.v2); var clipPoints1 = b2EPCollider.s_clipPoints1; var clipPoints2 = b2EPCollider.s_clipPoints2; var np = 0; np = b2ClipSegmentToLine(clipPoints1, ie, rf.sideNormal1, rf.sideOffset1, rf.i1); if (np < b2_maxManifoldPoints) return; np = b2ClipSegmentToLine(clipPoints2, clipPoints1, rf.sideNormal2, rf.sideOffset2, rf.i2); if (np < b2_maxManifoldPoints) return; if (1 === primaryAxis.type) { manifold.localNormal.Copy(rf.normal); manifold.localPoint.Copy(rf.v1); } else { manifold.localNormal.Copy(polygonB.m_normals[rf.i1]); manifold.localPoint.Copy(polygonB.m_vertices[rf.i1]); } var pointCount = 0; for (var i = 0; i < b2_maxManifoldPoints; ++i) { var separation = void 0; separation = b2Vec2.DotVV(rf.normal, b2Vec2.SubVV(clipPoints2[i].v, rf.v1, b2Vec2.s_t0)); if (separation <= this.m_radius) { var cp = manifold.points[pointCount]; if (1 === primaryAxis.type) { b2Transform.MulTXV(this.m_xf, clipPoints2[i].v, cp.localPoint); cp.id = clipPoints2[i].id; } else { cp.localPoint.Copy(clipPoints2[i].v); cp.id.cf.typeA = clipPoints2[i].id.cf.typeB; cp.id.cf.typeB = clipPoints2[i].id.cf.typeA; cp.id.cf.indexA = clipPoints2[i].id.cf.indexB; cp.id.cf.indexB = clipPoints2[i].id.cf.indexA; } ++pointCount; } } manifold.pointCount = pointCount; }; b2EPCollider.prototype.ComputeEdgeSeparation = function(out) { var axis = out; axis.type = 1; axis.index = this.m_front ? 0 : 1; axis.separation = b2_maxFloat; for (var i = 0; i < this.m_polygonB.count; ++i) { var s = b2Vec2.DotVV(this.m_normal, b2Vec2.SubVV(this.m_polygonB.vertices[i], this.m_v1, b2Vec2.s_t0)); s < axis.separation && (axis.separation = s); } return axis; }; b2EPCollider.prototype.ComputePolygonSeparation = function(out) { var axis = out; axis.type = 0; axis.index = -1; axis.separation = -b2_maxFloat; var perp = b2EPCollider.s_perp.Set(-this.m_normal.y, this.m_normal.x); for (var i = 0; i < this.m_polygonB.count; ++i) { var n = b2Vec2.NegV(this.m_polygonB.normals[i], b2EPCollider.s_n); var s1 = b2Vec2.DotVV(n, b2Vec2.SubVV(this.m_polygonB.vertices[i], this.m_v1, b2Vec2.s_t0)); var s2 = b2Vec2.DotVV(n, b2Vec2.SubVV(this.m_polygonB.vertices[i], this.m_v2, b2Vec2.s_t0)); var s = b2Min(s1, s2); if (s > this.m_radius) { axis.type = 2; axis.index = i; axis.separation = s; return axis; } if (b2Vec2.DotVV(n, perp) >= 0) { if (b2Vec2.DotVV(b2Vec2.SubVV(n, this.m_upperLimit, b2Vec2.s_t0), this.m_normal) < -b2_angularSlop) continue; } else if (b2Vec2.DotVV(b2Vec2.SubVV(n, this.m_lowerLimit, b2Vec2.s_t0), this.m_normal) < -b2_angularSlop) continue; if (s > axis.separation) { axis.type = 2; axis.index = i; axis.separation = s; } } return axis; }; b2EPCollider.s_edge1 = new b2Vec2(); b2EPCollider.s_edge0 = new b2Vec2(); b2EPCollider.s_edge2 = new b2Vec2(); b2EPCollider.s_ie = b2ClipVertex.MakeArray(2); b2EPCollider.s_rf = new b2ReferenceFace(); b2EPCollider.s_clipPoints1 = b2ClipVertex.MakeArray(2); b2EPCollider.s_clipPoints2 = b2ClipVertex.MakeArray(2); b2EPCollider.s_edgeAxis = new b2EPAxis(); b2EPCollider.s_polygonAxis = new b2EPAxis(); b2EPCollider.s_n = new b2Vec2(); b2EPCollider.s_perp = new b2Vec2(); return b2EPCollider; })(); var b2CollideEdgeAndPolygon_s_collider = new b2EPCollider(); function b2CollideEdgeAndPolygon(manifold, edgeA, xfA, polygonB, xfB) { var collider = b2CollideEdgeAndPolygon_s_collider; collider.Collide(manifold, edgeA, xfA, polygonB, xfB); } var b2MassData = (function() { function b2MassData() { this.mass = 0; this.center = new b2Vec2(0, 0); this.I = 0; } return b2MassData; })(); (function(b2ShapeType) { b2ShapeType[b2ShapeType["e_unknown"] = -1] = "e_unknown"; b2ShapeType[b2ShapeType["e_circleShape"] = 0] = "e_circleShape"; b2ShapeType[b2ShapeType["e_edgeShape"] = 1] = "e_edgeShape"; b2ShapeType[b2ShapeType["e_polygonShape"] = 2] = "e_polygonShape"; b2ShapeType[b2ShapeType["e_chainShape"] = 3] = "e_chainShape"; b2ShapeType[b2ShapeType["e_shapeTypeCount"] = 4] = "e_shapeTypeCount"; })(exports.b2ShapeType || (exports.b2ShapeType = {})); var b2Shape = (function() { function b2Shape(type, radius) { this.m_type = exports.b2ShapeType.e_unknown; this.m_radius = 0; this.m_type = type; this.m_radius = radius; } b2Shape.prototype.Copy = function(other) { this.m_radius = other.m_radius; return this; }; b2Shape.prototype.GetType = function() { return this.m_type; }; return b2Shape; })(); 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]); }; function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = null === b ? Object.create(b) : (__.prototype = b.prototype, new __()); } var b2CircleShape = (function(_super) { __extends(b2CircleShape, _super); function b2CircleShape(radius) { void 0 === radius && (radius = 0); var _this = _super.call(this, exports.b2ShapeType.e_circleShape, radius) || this; _this.m_p = new b2Vec2(); return _this; } b2CircleShape.prototype.Set = function(position, radius) { void 0 === radius && (radius = this.m_radius); this.m_p.Copy(position); this.m_radius = radius; return this; }; b2CircleShape.prototype.Clone = function() { return new b2CircleShape().Copy(this); }; b2CircleShape.prototype.Copy = function(other) { _super.prototype.Copy.call(this, other); this.m_p.Copy(other.m_p); return this; }; b2CircleShape.prototype.GetChildCount = function() { return 1; }; b2CircleShape.prototype.TestPoint = function(transform, p) { var center = b2Transform.MulXV(transform, this.m_p, b2CircleShape.TestPoint_s_center); var d = b2Vec2.SubVV(p, center, b2CircleShape.TestPoint_s_d); return b2Vec2.DotVV(d, d) <= b2Sq(this.m_radius); }; b2CircleShape.prototype.ComputeDistance = function(xf, p, normal, childIndex) { var center = b2Transform.MulXV(xf, this.m_p, b2CircleShape.ComputeDistance_s_center); b2Vec2.SubVV(p, center, normal); return normal.Normalize() - this.m_radius; }; b2CircleShape.prototype.RayCast = function(output, input, transform, childIndex) { var position = b2Transform.MulXV(transform, this.m_p, b2CircleShape.RayCast_s_position); var s = b2Vec2.SubVV(input.p1, position, b2CircleShape.RayCast_s_s); var b = b2Vec2.DotVV(s, s) - b2Sq(this.m_radius); var r = b2Vec2.SubVV(input.p2, input.p1, b2CircleShape.RayCast_s_r); var c = b2Vec2.DotVV(s, r); var rr = b2Vec2.DotVV(r, r); var sigma = c * c - rr * b; if (sigma < 0 || rr < b2_epsilon) return false; var a = -(c + b2Sqrt(sigma)); if (0 <= a && a <= input.maxFraction * rr) { a /= rr; output.fraction = a; b2Vec2.AddVMulSV(s, a, r, output.normal).SelfNormalize(); return true; } return false; }; b2CircleShape.prototype.ComputeAABB = function(aabb, transform, childIndex) { var p = b2Transform.MulXV(transform, this.m_p, b2CircleShape.ComputeAABB_s_p); aabb.lowerBound.Set(p.x - this.m_radius, p.y - this.m_radius); aabb.upperBound.Set(p.x + this.m_radius, p.y + this.m_radius); }; b2CircleShape.prototype.ComputeMass = function(massData, density) { var radius_sq = b2Sq(this.m_radius); massData.mass = density * b2_pi * radius_sq; massData.center.Copy(this.m_p); massData.I = massData.mass * (.5 * radius_sq + b2Vec2.DotVV(this.m_p, this.m_p)); }; b2CircleShape.prototype.SetupDistanceProxy = function(proxy, index) { proxy.m_vertices = proxy.m_buffer; proxy.m_vertices[0].Copy(this.m_p); proxy.m_count = 1; proxy.m_radius = this.m_radius; }; b2CircleShape.prototype.ComputeSubmergedArea = function(normal, offset, xf, c) { var p = b2Transform.MulXV(xf, this.m_p, new b2Vec2()); var l = -(b2Vec2.DotVV(normal, p) - offset); if (l < -this.m_radius + b2_epsilon) return 0; if (l > this.m_radius) { c.Copy(p); return b2_pi * this.m_radius * this.m_radius; } var r2 = this.m_radius * this.m_radius; var l2 = l * l; var area = r2 * (b2Asin(l / this.m_radius) + b2_pi / 2) + l * b2Sqrt(r2 - l2); var com = -2 / 3 * b2Pow(r2 - l2, 1.5) / area; c.x = p.x + normal.x * com; c.y = p.y + normal.y * com; return area; }; b2CircleShape.prototype.Dump = function(log) { log(" const shape: b2CircleShape = new b2CircleShape();\n"); log(" shape.m_radius = %.15f;\n", this.m_radius); log(" shape.m_p.Set(%.15f, %.15f);\n", this.m_p.x, this.m_p.y); }; b2CircleShape.TestPoint_s_center = new b2Vec2(); b2CircleShape.TestPoint_s_d = new b2Vec2(); b2CircleShape.ComputeDistance_s_center = new b2Vec2(); b2CircleShape.RayCast_s_position = new b2Vec2(); b2CircleShape.RayCast_s_s = new b2Vec2(); b2CircleShape.RayCast_s_r = new b2Vec2(); b2CircleShape.ComputeAABB_s_p = new b2Vec2(); return b2CircleShape; })(b2Shape); var b2PolygonShape = (function(_super) { __extends(b2PolygonShape, _super); function b2PolygonShape() { var _this = _super.call(this, exports.b2ShapeType.e_polygonShape, b2_polygonRadius) || this; _this.m_centroid = new b2Vec2(0, 0); _this.m_vertices = []; _this.m_normals = []; _this.m_count = 0; return _this; } b2PolygonShape.prototype.Clone = function() { return new b2PolygonShape().Copy(this); }; b2PolygonShape.prototype.Copy = function(other) { _super.prototype.Copy.call(this, other); this.m_centroid.Copy(other.m_centroid); this.m_count = other.m_count; this.m_vertices = b2Vec2.MakeArray(this.m_count); this.m_normals = b2Vec2.MakeArray(this.m_count); for (var i = 0; i < this.m_count; ++i) { this.m_vertices[i].Copy(other.m_vertices[i]); this.m_normals[i].Copy(other.m_normals[i]); } return this; }; b2PolygonShape.prototype.GetChildCount = function() { return 1; }; b2PolygonShape.prototype.Set = function(vertices, count, start) { void 0 === count && (count = vertices.length); void 0 === start && (start = 0); if (count < 3) return this.SetAsBox(1, 1); var n = b2Min(count, b2_maxPolygonVertices); var ps = b2PolygonShape.Set_s_ps; var tempCount = 0; for (var i = 0; i < n; ++i) { var v = vertices[start + i]; var unique = true; for (var j = 0; j < tempCount; ++j) if (b2Vec2.DistanceSquaredVV(v, ps[j]) < .5 * b2_linearSlop * (.5 * b2_linearSlop)) { unique = false; break; } unique && ps[tempCount++].Copy(v); } n = tempCount; if (n < 3) return this.SetAsBox(1, 1); var i0 = 0; var x0 = ps[0].x; for (var i = 1; i < n; ++i) { var x = ps[i].x; if (x > x0 || x === x0 && ps[i].y < ps[i0].y) { i0 = i; x0 = x; } } var hull = b2PolygonShape.Set_s_hull; var m = 0; var ih = i0; for (;;) { hull[m] = ih; var ie = 0; for (var j = 1; j < n; ++j) { if (ie === ih) { ie = j; continue; } var r = b2Vec2.SubVV(ps[ie], ps[hull[m]], b2PolygonShape.Set_s_r); var v = b2Vec2.SubVV(ps[j], ps[hull[m]], b2PolygonShape.Set_s_v); var c = b2Vec2.CrossVV(r, v); c < 0 && (ie = j); 0 === c && v.LengthSquared() > r.LengthSquared() && (ie = j); } ++m; ih = ie; if (ie === i0) break; } this.m_count = m; this.m_vertices = b2Vec2.MakeArray(this.m_count); this.m_normals = b2Vec2.MakeArray(this.m_count); for (var i = 0; i < m; ++i) this.m_vertices[i].Copy(ps[hull[i]]); for (var i = 0; i < m; ++i) { var vertexi1 = this.m_vertices[i]; var vertexi2 = this.m_vertices[(i + 1) % m]; var edge = b2Vec2.SubVV(vertexi2, vertexi1, b2Vec2.s_t0); b2Vec2.CrossVOne(edge, this.m_normals[i]).SelfNormalize(); } b2PolygonShape.ComputeCentroid(this.m_vertices, m, this.m_centroid); return this; }; b2PolygonShape.prototype.SetAsArray = function(vertices, count) { void 0 === count && (count = vertices.length); return this.Set(vertices, count); }; b2PolygonShape.prototype.SetAsBox = function(hx, hy, center, angle) { void 0 === angle && (angle = 0); this.m_count = 4; this.m_vertices = b2Vec2.MakeArray(this.m_count); this.m_normals = b2Vec2.MakeArray(this.m_count); this.m_vertices[0].Set(-hx, -hy); this.m_vertices[1].Set(hx, -hy); this.m_vertices[2].Set(hx, hy); this.m_vertices[3].Set(-hx, hy); this.m_normals[0].Set(0, -1); this.m_normals[1].Set(1, 0); this.m_normals[2].Set(0, 1); this.m_normals[3].Set(-1, 0); this.m_centroid.SetZero(); if (center) { this.m_centroid.Copy(center); var xf = new b2Transform(); xf.SetPosition(center); xf.SetRotationAngle(angle); for (var i = 0; i < this.m_count; ++i) { b2Transform.MulXV(xf, this.m_vertices[i], this.m_vertices[i]); b2Rot.MulRV(xf.q, this.m_normals[i], this.m_normals[i]); } } return this; }; b2PolygonShape.prototype.TestPoint = function(xf, p) { var pLocal = b2Transform.MulTXV(xf, p, b2PolygonShape.TestPoint_s_pLocal); for (var i = 0; i < this.m_count; ++i) { var dot = b2Vec2.DotVV(this.m_normals[i], b2Vec2.SubVV(pLocal, this.m_vertices[i], b2Vec2.s_t0)); if (dot > 0) return false; } return true; }; b2PolygonShape.prototype.ComputeDistance = function(xf, p, normal, childIndex) { var pLocal = b2Transform.MulTXV(xf, p, b2PolygonShape.ComputeDistance_s_pLocal); var maxDistance = -b2_maxFloat; var normalForMaxDistance = b2PolygonShape.ComputeDistance_s_normalForMaxDistance.Copy(pLocal); for (var i = 0; i < this.m_count; ++i) { var dot = b2Vec2.DotVV(this.m_normals[i], b2Vec2.SubVV(pLocal, this.m_vertices[i], b2Vec2.s_t0)); if (dot > maxDistance) { maxDistance = dot; normalForMaxDistance.Copy(this.m_normals[i]); } } if (maxDistance > 0) { var minDistance = b2PolygonShape.ComputeDistance_s_minDistance.Copy(normalForMaxDistance); var minDistance2 = maxDistance * maxDistance; for (var i = 0; i < this.m_count; ++i) { var distance = b2Vec2.SubVV(pLocal, this.m_vertices[i], b2PolygonShape.ComputeDistance_s_distance); var distance2 = distance.LengthSquared(); if (minDistance2 > distance2) { minDistance.Copy(distance); minDistance2 = distance2; } } b2Rot.MulRV(xf.q, minDistance, normal); normal.Normalize(); return Math.sqrt(minDistance2); } b2Rot.MulRV(xf.q, normalForMaxDistance, normal); return maxDistance; }; b2PolygonShape.prototype.RayCast = function(output, input, xf, childIndex) { var p1 = b2Transform.MulTXV(xf, input.p1, b2PolygonShape.RayCast_s_p1); var p2 = b2Transform.MulTXV(xf, input.p2, b2PolygonShape.RayCast_s_p2); var d = b2Vec2.SubVV(p2, p1, b2PolygonShape.RayCast_s_d); var lower = 0, upper = input.maxFraction; var index = -1; for (var i = 0; i < this.m_count; ++i) { var numerator = b2Vec2.DotVV(this.m_normals[i], b2Vec2.SubVV(this.m_vertices[i], p1, b2Vec2.s_t0)); var denominator = b2Vec2.DotVV(this.m_normals[i], d); if (0 === denominator) { if (numerator < 0) return false; } else if (denominator < 0 && numerator < lower * denominator) { lower = numerator / denominator; index = i; } else denominator > 0 && numerator < upper * denominator && (upper = numerator / denominator); if (upper < lower) return false; } if (index >= 0) { output.fraction = lower; b2Rot.MulRV(xf.q, this.m_normals[index], output.normal); return true; } return false; }; b2PolygonShape.prototype.ComputeAABB = function(aabb, xf, childIndex) { var lower = b2Transform.MulXV(xf, this.m_vertices[0], aabb.lowerBound); var upper = aabb.upperBound.Copy(lower); for (var i = 0; i < this.m_count; ++i) { var v = b2Transform.MulXV(xf, this.m_vertices[i], b2PolygonShape.ComputeAABB_s_v); b2Vec2.MinV(v, lower, lower); b2Vec2.MaxV(v, upper, upper); } var r = this.m_radius; lower.SelfSubXY(r, r); upper.SelfAddXY(r, r); }; b2PolygonShape.prototype.ComputeMass = function(massData, density) { var center = b2PolygonShape.ComputeMass_s_center.SetZero(); var area = 0; var I = 0; var s = b2PolygonShape.ComputeMass_s_s.SetZero(); for (var i = 0; i < this.m_count; ++i) s.SelfAdd(this.m_vertices[i]); s.SelfMul(1 / this.m_count); var k_inv3 = 1 / 3; for (var i = 0; i < this.m_count; ++i) { var e1 = b2Vec2.SubVV(this.m_vertices[i], s, b2PolygonShape.ComputeMass_s_e1); var e2 = b2Vec2.SubVV(this.m_vertices[(i + 1) % this.m_count], s, b2PolygonShape.ComputeMass_s_e2); var D = b2Vec2.CrossVV(e1, e2); var triangleArea = .5 * D; area += triangleArea; center.SelfAdd(b2Vec2.MulSV(triangleArea * k_inv3, b2Vec2.AddVV(e1, e2, b2Vec2.s_t0), b2Vec2.s_t1)); var ex1 = e1.x; var ey1 = e1.y; var ex2 = e2.x; var ey2 = e2.y; var intx2 = ex1 * ex1 + ex2 * ex1 + ex2 * ex2; var inty2 = ey1 * ey1 + ey2 * ey1 + ey2 * ey2; I += .25 * k_inv3 * D * (intx2 + inty2); } massData.mass = density * area; center.SelfMul(1 / area); b2Vec2.AddVV(center, s, massData.center); massData.I = density * I; massData.I += massData.mass * (b2Vec2.DotVV(massData.center, massData.center) - b2Vec2.DotVV(center, center)); }; b2PolygonShape.prototype.Validate = function() { for (var i = 0; i < this.m_count; ++i) { var i1 = i; var i2 = (i + 1) % this.m_count; var p = this.m_vertices[i1]; var e = b2Vec2.SubVV(this.m_vertices[i2], p, b2PolygonShape.Validate_s_e); for (var j = 0; j < this.m_count; ++j) { if (j === i1 || j === i2) continue; var v = b2Vec2.SubVV(this.m_vertices[j], p, b2PolygonShape.Validate_s_v); var c = b2Vec2.CrossVV(e, v); if (c < 0) return false; } } return true; }; b2PolygonShape.prototype.SetupDistanceProxy = function(proxy, index) { proxy.m_vertices = this.m_vertices; proxy.m_count = this.m_count; proxy.m_radius = this.m_radius; }; b2PolygonShape.prototype.ComputeSubmergedArea = function(normal, offset, xf, c) { var normalL = b2Rot.MulTRV(xf.q, normal, b2PolygonShape.ComputeSubmergedArea_s_normalL); var offsetL = offset - b2Vec2.DotVV(normal, xf.p); var depths = b2PolygonShape.ComputeSubmergedArea_s_depths; var diveCount = 0; var intoIndex = -1; var outoIndex = -1; var lastSubmerged = false; for (var i_1 = 0; i_1 < this.m_count; ++i_1) { depths[i_1] = b2Vec2.DotVV(normalL, this.m_vertices[i_1]) - offsetL; var isSubmerged = depths[i_1] < -b2_epsilon; if (i_1 > 0) if (isSubmerged) { if (!lastSubmerged) { intoIndex = i_1 - 1; diveCount++; } } else if (lastSubmerged) { outoIndex = i_1 - 1; diveCount++; } lastSubmerged = isSubmerged; } switch (diveCount) { case 0: if (lastSubmerged) { var md = b2PolygonShape.ComputeSubmergedArea_s_md; this.ComputeMass(md, 1); b2Transform.MulXV(xf, md.center, c); return md.mass; } return 0; case 1: -1 === intoIndex ? intoIndex = this.m_count - 1 : outoIndex = this.m_count - 1; } var intoIndex2 = (intoIndex + 1) % this.m_count; var outoIndex2 = (outoIndex + 1) % this.m_count; var intoLamdda = (0 - depths[intoIndex]) / (depths[intoIndex2] - depths[intoIndex]); var outoLamdda = (0 - depths[outoIndex]) / (depths[outoIndex2] - depths[outoIndex]); var intoVec = b2PolygonShape.ComputeSubmergedArea_s_intoVec.Set(this.m_vertices[intoIndex].x * (1 - intoLamdda) + this.m_vertices[intoIndex2].x * intoLamdda, this.m_vertices[intoIndex].y * (1 - intoLamdda) + this.m_vertices[intoIndex2].y * intoLamdda); var outoVec = b2PolygonShape.ComputeSubmergedArea_s_outoVec.Set(this.m_vertices[outoIndex].x * (1 - outoLamdda) + this.m_vertices[outoIndex2].x * outoLamdda, this.m_vertices[outoIndex].y * (1 - outoLamdda) + this.m_vertices[outoIndex2].y * outoLamdda); var area = 0; var center = b2PolygonShape.ComputeSubmergedArea_s_center.SetZero(); var p2 = this.m_vertices[intoIndex2]; var p3; var i = intoIndex2; while (i !== outoIndex2) { i = (i + 1) % this.m_count; p3 = i === outoIndex2 ? outoVec : this.m_vertices[i]; var triangleArea = .5 * ((p2.x - intoVec.x) * (p3.y - intoVec.y) - (p2.y - intoVec.y) * (p3.x - intoVec.x)); area += triangleArea; center.x += triangleArea * (intoVec.x + p2.x + p3.x) / 3; center.y += triangleArea * (intoVec.y + p2.y + p3.y) / 3; p2 = p3; } center.SelfMul(1 / area); b2Transform.MulXV(xf, center, c); return area; }; b2PolygonShape.prototype.Dump = function(log) { log(" const shape: b2PolygonShape = new b2PolygonShape();\n"); log(" const vs: b2Vec2[] = b2Vec2.MakeArray(%d);\n", b2_maxPolygonVertices); for (var i = 0; i < this.m_count; ++i) log(" vs[%d].Set(%.15f, %.15f);\n", i, this.m_vertices[i].x, this.m_vertices[i].y); log(" shape.Set(vs, %d);\n", this.m_count); }; b2PolygonShape.ComputeCentroid = function(vs, count, out) { var c = out; c.SetZero(); var area = 0; var pRef = b2PolygonShape.ComputeCentroid_s_pRef.SetZero(); var inv3 = 1 / 3; for (var i = 0; i < count; ++i) { var p1 = pRef; var p2 = vs[i]; var p3 = vs[(i + 1) % count]; var e1 = b2Vec2.SubVV(p2, p1, b2PolygonShape.ComputeCentroid_s_e1); var e2 = b2Vec2.SubVV(p3, p1, b2PolygonShape.ComputeCentroid_s_e2); var D = b2Vec2.CrossVV(e1, e2); var triangleArea = .5 * D; area += triangleArea; c.x += triangleArea * inv3 * (p1.x + p2.x + p3.x); c.y += triangleArea * inv3 * (p1.y + p2.y + p3.y); } c.SelfMul(1 / area); return c; }; b2PolygonShape.Set_s_ps = b2Vec2.MakeArray(b2_maxPolygonVertices); b2PolygonShape.Set_s_hull = b2MakeNumberArray(b2_maxPolygonVertices); b2PolygonShape.Set_s_r = new b2Vec2(); b2PolygonShape.Set_s_v = new b2Vec2(); b2PolygonShape.TestPoint_s_pLocal = new b2Vec2(); b2PolygonShape.ComputeDistance_s_pLocal = new b2Vec2(); b2PolygonShape.ComputeDistance_s_normalForMaxDistance = new b2Vec2(); b2PolygonShape.ComputeDistance_s_minDistance = new b2Vec2(); b2PolygonShape.ComputeDistance_s_distance = new b2Vec2(); b2PolygonShape.RayCast_s_p1 = new b2Vec2(); b2PolygonShape.RayCast_s_p2 = new b2Vec2(); b2PolygonShape.RayCast_s_d = new b2Vec2(); b2PolygonShape.ComputeAABB_s_v = new b2Vec2(); b2PolygonShape.ComputeMass_s_center = new b2Vec2(); b2PolygonShape.ComputeMass_s_s = new b2Vec2(); b2PolygonShape.ComputeMass_s_e1 = new b2Vec2(); b2PolygonShape.ComputeMass_s_e2 = new b2Vec2(); b2PolygonShape.Validate_s_e = new b2Vec2(); b2PolygonShape.Validate_s_v = new b2Vec2(); b2PolygonShape.ComputeSubmergedArea_s_normalL = new b2Vec2(); b2PolygonShape.ComputeSubmergedArea_s_depths = b2MakeNumberArray(b2_maxPolygonVertices); b2PolygonShape.ComputeSubmergedArea_s_md = new b2MassData(); b2PolygonShape.ComputeSubmergedArea_s_intoVec = new b2Vec2(); b2PolygonShape.ComputeSubmergedArea_s_outoVec = new b2Vec2(); b2PolygonShape.ComputeSubmergedArea_s_center = new b2Vec2(); b2PolygonShape.ComputeCentroid_s_pRef = new b2Vec2(); b2PolygonShape.ComputeCentroid_s_e1 = new b2Vec2(); b2PolygonShape.ComputeCentroid_s_e2 = new b2Vec2(); return b2PolygonShape; })(b2Shape); var b2EdgeShape = (function(_super) { __extends(b2EdgeShape, _super); function b2EdgeShape() { var _this = _super.call(this, exports.b2ShapeType.e_edgeShape, b2_polygonRadius) || this; _this.m_vertex1 = new b2Vec2(); _this.m_vertex2 = new b2Vec2(); _this.m_vertex0 = new b2Vec2(); _this.m_vertex3 = new b2Vec2(); _this.m_hasVertex0 = false; _this.m_hasVertex3 = false; return _this; } b2EdgeShape.prototype.Set = function(v1, v2) { this.m_vertex1.Copy(v1); this.m_vertex2.Copy(v2); this.m_hasVertex0 = false; this.m_hasVertex3 = false; return this; }; b2EdgeShape.prototype.Clone = function() { return new b2EdgeShape().Copy(this); }; b2EdgeShape.prototype.Copy = function(other) { _super.prototype.Copy.call(this, other); this.m_vertex1.Copy(other.m_vertex1); this.m_vertex2.Copy(other.m_vertex2); this.m_vertex0.Copy(other.m_vertex0); this.m_vertex3.Copy(other.m_vertex3); this.m_hasVertex0 = other.m_hasVertex0; this.m_hasVertex3 = other.m_hasVertex3; return this; }; b2EdgeShape.prototype.GetChildCount = function() { return 1; }; b2EdgeShape.prototype.TestPoint = function(xf, p) { return false; }; b2EdgeShape.prototype.ComputeDistance = function(xf, p, normal, childIndex) { var v1 = b2Transform.MulXV(xf, this.m_vertex1, b2EdgeShape.ComputeDistance_s_v1); var v2 = b2Transform.MulXV(xf, this.m_vertex2, b2EdgeShape.ComputeDistance_s_v2); var d = b2Vec2.SubVV(p, v1, b2EdgeShape.ComputeDistance_s_d); var s = b2Vec2.SubVV(v2, v1, b2EdgeShape.ComputeDistance_s_s); var ds = b2Vec2.DotVV(d, s); if (ds > 0) { var s2 = b2Vec2.DotVV(s, s); ds > s2 ? b2Vec2.SubVV(p, v2, d) : d.SelfMulSub(ds / s2, s); } normal.Copy(d); return normal.Normalize(); }; b2EdgeShape.prototype.RayCast = function(output, input, xf, childIndex) { var p1 = b2Transform.MulTXV(xf, input.p1, b2EdgeShape.RayCast_s_p1); var p2 = b2Transform.MulTXV(xf, input.p2, b2EdgeShape.RayCast_s_p2); var d = b2Vec2.SubVV(p2, p1, b2EdgeShape.RayCast_s_d); var v1 = this.m_vertex1; var v2 = this.m_vertex2; var e = b2Vec2.SubVV(v2, v1, b2EdgeShape.RayCast_s_e); var normal = output.normal.Set(e.y, -e.x).SelfNormalize(); var numerator = b2Vec2.DotVV(normal, b2Vec2.SubVV(v1, p1, b2Vec2.s_t0)); var denominator = b2Vec2.DotVV(normal, d); if (0 === denominator) return false; var t = numerator / denominator; if (t < 0 || input.maxFraction < t) return false; var q = b2Vec2.AddVMulSV(p1, t, d, b2EdgeShape.RayCast_s_q); var r = b2Vec2.SubVV(v2, v1, b2EdgeShape.RayCast_s_r); var rr = b2Vec2.DotVV(r, r); if (0 === rr) return false; var s = b2Vec2.DotVV(b2Vec2.SubVV(q, v1, b2Vec2.s_t0), r) / rr; if (s < 0 || 1 < s) return false; output.fraction = t; b2Rot.MulRV(xf.q, output.normal, output.normal); numerator > 0 && output.normal.SelfNeg(); return true; }; b2EdgeShape.prototype.ComputeAABB = function(aabb, xf, childIndex) { var v1 = b2Transform.MulXV(xf, this.m_vertex1, b2EdgeShape.ComputeAABB_s_v1); var v2 = b2Transform.MulXV(xf, this.m_vertex2, b2EdgeShape.ComputeAABB_s_v2); b2Vec2.MinV(v1, v2, aabb.lowerBound); b2Vec2.MaxV(v1, v2, aabb.upperBound); var r = this.m_radius; aabb.lowerBound.SelfSubXY(r, r); aabb.upperBound.SelfAddXY(r, r); }; b2EdgeShape.prototype.ComputeMass = function(massData, density) { massData.mass = 0; b2Vec2.MidVV(this.m_vertex1, this.m_vertex2, massData.center); massData.I = 0; }; b2EdgeShape.prototype.SetupDistanceProxy = function(proxy, index) { proxy.m_vertices = proxy.m_buffer; proxy.m_vertices[0].Copy(this.m_vertex1); proxy.m_vertices[1].Copy(this.m_vertex2); proxy.m_count = 2; proxy.m_radius = this.m_radius; }; b2EdgeShape.prototype.ComputeSubmergedArea = function(normal, offset, xf, c) { c.SetZero(); return 0; }; b2EdgeShape.prototype.Dump = function(log) { log(" const shape: b2EdgeShape = new b2EdgeShape();\n"); log(" shape.m_radius = %.15f;\n", this.m_radius); log(" shape.m_vertex0.Set(%.15f, %.15f);\n", this.m_vertex0.x, this.m_vertex0.y); log(" shape.m_vertex1.Set(%.15f, %.15f);\n", this.m_vertex1.x, this.m_vertex1.y); log(" shape.m_vertex2.Set(%.15f, %.15f);\n", this.m_vertex2.x, this.m_vertex2.y); log(" shape.m_vertex3.Set(%.15f, %.15f);\n", this.m_vertex3.x, this.m_vertex3.y); log(" shape.m_hasVertex0 = %s;\n", this.m_hasVertex0); log(" shape.m_hasVertex3 = %s;\n", this.m_hasVertex3); }; b2EdgeShape.ComputeDistance_s_v1 = new b2Vec2(); b2EdgeShape.ComputeDistance_s_v2 = new b2Vec2(); b2EdgeShape.ComputeDistance_s_d = new b2Vec2(); b2EdgeShape.ComputeDistance_s_s = new b2Vec2(); b2EdgeShape.RayCast_s_p1 = new b2Vec2(); b2EdgeShape.RayCast_s_p2 = new b2Vec2(); b2EdgeShape.RayCast_s_d = new b2Vec2(); b2EdgeShape.RayCast_s_e = new b2Vec2(); b2EdgeShape.RayCast_s_q = new b2Vec2(); b2EdgeShape.RayCast_s_r = new b2Vec2(); b2EdgeShape.ComputeAABB_s_v1 = new b2Vec2(); b2EdgeShape.ComputeAABB_s_v2 = new b2Vec2(); return b2EdgeShape; })(b2Shape); var b2ChainShape = (function(_super) { __extends(b2ChainShape, _super); function b2ChainShape() { var _this = _super.call(this, exports.b2ShapeType.e_chainShape, b2_polygonRadius) || this; _this.m_vertices = []; _this.m_count = 0; _this.m_prevVertex = new b2Vec2(); _this.m_nextVertex = new b2Vec2(); _this.m_hasPrevVertex = false; _this.m_hasNextVertex = false; return _this; } b2ChainShape.prototype.CreateLoop = function(vertices, count, start) { void 0 === count && (count = vertices.length); void 0 === start && (start = 0); if (count < 3) return this; this.m_count = count + 1; this.m_vertices = b2Vec2.MakeArray(this.m_count); for (var i = 0; i < count; ++i) this.m_vertices[i].Copy(vertices[start + i]); this.m_vertices[count].Copy(this.m_vertices[0]); this.m_prevVertex.Copy(this.m_vertices[this.m_count - 2]); this.m_nextVertex.Copy(this.m_vertices[1]); this.m_hasPrevVertex = true; this.m_hasNextVertex = true; return this; }; b2ChainShape.prototype.CreateChain = function(vertices, count, start) { void 0 === count && (count = vertices.length); void 0 === start && (start = 0); this.m_count = count; this.m_vertices = b2Vec2.MakeArray(count); for (var i = 0; i < count; ++i) this.m_vertices[i].Copy(vertices[start + i]); this.m_hasPrevVertex = false; this.m_hasNextVertex = false; this.m_prevVertex.SetZero(); this.m_nextVertex.SetZero(); return this; }; b2ChainShape.prototype.SetPrevVertex = function(prevVertex) { this.m_prevVertex.Copy(prevVertex); this.m_hasPrevVertex = true; return this; }; b2ChainShape.prototype.SetNextVertex = function(nextVertex) { this.m_nextVertex.Copy(nextVertex); this.m_hasNextVertex = true; return this; }; b2ChainShape.prototype.Clone = function() { return new b2ChainShape().Copy(this); }; b2ChainShape.prototype.Copy = function(other) { _super.prototype.Copy.call(this, other); this.CreateChain(other.m_vertices, other.m_count); this.m_prevVertex.Copy(other.m_prevVertex); this.m_nextVertex.Copy(other.m_nextVertex); this.m_hasPrevVertex = other.m_hasPrevVertex; this.m_hasNextVertex = other.m_hasNextVertex; return this; }; b2ChainShape.prototype.GetChildCount = function() { return this.m_count - 1; }; b2ChainShape.prototype.GetChildEdge = function(edge, index) { edge.m_type = exports.b2ShapeType.e_edgeShape; edge.m_radius = this.m_radius; edge.m_vertex1.Copy(this.m_vertices[index]); edge.m_vertex2.Copy(this.m_vertices[index + 1]); if (index > 0) { edge.m_vertex0.Copy(this.m_vertices[index - 1]); edge.m_hasVertex0 = true; } else { edge.m_vertex0.Copy(this.m_prevVertex); edge.m_hasVertex0 = this.m_hasPrevVertex; } if (index < this.m_count - 2) { edge.m_vertex3.Copy(this.m_vertices[index + 2]); edge.m_hasVertex3 = true; } else { edge.m_vertex3.Copy(this.m_nextVertex); edge.m_hasVertex3 = this.m_hasNextVertex; } }; b2ChainShape.prototype.TestPoint = function(xf, p) { return false; }; b2ChainShape.prototype.ComputeDistance = function(xf, p, normal, childIndex) { var edge = b2ChainShape.ComputeDistance_s_edgeShape; this.GetChildEdge(edge, childIndex); return edge.ComputeDistance(xf, p, normal, 0); }; b2ChainShape.prototype.RayCast = function(output, input, xf, childIndex) { var edgeShape = b2ChainShape.RayCast_s_edgeShape; edgeShape.m_vertex1.Copy(this.m_vertices[childIndex]); edgeShape.m_vertex2.Copy(this.m_vertices[(childIndex + 1) % this.m_count]); return edgeShape.RayCast(output, input, xf, 0); }; b2ChainShape.prototype.ComputeAABB = function(aabb, xf, childIndex) { var vertexi1 = this.m_vertices[childIndex]; var vertexi2 = this.m_vertices[(childIndex + 1) % this.m_count]; var v1 = b2Transform.MulXV(xf, vertexi1, b2ChainShape.ComputeAABB_s_v1); var v2 = b2Transform.MulXV(xf, vertexi2, b2ChainShape.ComputeAABB_s_v2); b2Vec2.MinV(v1, v2, aabb.lowerBound); b2Vec2.MaxV(v1, v2, aabb.upperBound); }; b2ChainShape.prototype.ComputeMass = function(massData, density) { massData.mass = 0; massData.center.SetZero(); massData.I = 0; }; b2ChainShape.prototype.SetupDistanceProxy = function(proxy, index) { proxy.m_vertices = proxy.m_buffer; proxy.m_vertices[0].Copy(this.m_vertices[index]); index + 1 < this.m_count ? proxy.m_vertices[1].Copy(this.m_vertices[index + 1]) : proxy.m_vertices[1].Copy(this.m_vertices[0]); proxy.m_count = 2; proxy.m_radius = this.m_radius; }; b2ChainShape.prototype.ComputeSubmergedArea = function(normal, offset, xf, c) { c.SetZero(); return 0; }; b2ChainShape.prototype.Dump = function(log) { log(" const shape: b2ChainShape = new b2ChainShape();\n"); log(" const vs: b2Vec2[] = b2Vec2.MakeArray(%d);\n", b2_maxPolygonVertices); for (var i = 0; i < this.m_count; ++i) log(" vs[%d].Set(%.15f, %.15f);\n", i, this.m_vertices[i].x, this.m_vertices[i].y); log(" shape.CreateChain(vs, %d);\n", this.m_count); log(" shape.m_prevVertex.Set(%.15f, %.15f);\n", this.m_prevVertex.x, this.m_prevVertex.y); log(" shape.m_nextVertex.Set(%.15f, %.15f);\n", this.m_nextVertex.x, this.m_nextVertex.y); log(" shape.m_hasPrevVertex = %s;\n", this.m_hasPrevVertex ? "true" : "false"); log(" shape.m_hasNextVertex = %s;\n", this.m_hasNextVertex ? "true" : "false"); }; b2ChainShape.ComputeDistance_s_edgeShape = new b2EdgeShape(); b2ChainShape.RayCast_s_edgeShape = new b2EdgeShape(); b2ChainShape.ComputeAABB_s_v1 = new b2Vec2(); b2ChainShape.ComputeAABB_s_v2 = new b2Vec2(); return b2ChainShape; })(b2Shape); var b2Filter = (function() { function b2Filter() { this.categoryBits = 1; this.maskBits = 65535; this.groupIndex = 0; } b2Filter.prototype.Clone = function() { return new b2Filter().Copy(this); }; b2Filter.prototype.Copy = function(other) { this.categoryBits = other.categoryBits; this.maskBits = other.maskBits; this.groupIndex = other.groupIndex || 0; return this; }; b2Filter.DEFAULT = new b2Filter(); return b2Filter; })(); var b2FixtureDef = (function() { function b2FixtureDef() { this.userData = null; this.friction = .2; this.restitution = 0; this.density = 0; this.isSensor = false; this.filter = new b2Filter(); } return b2FixtureDef; })(); var b2FixtureProxy = (function() { function b2FixtureProxy(fixture) { this.aabb = new b2AABB(); this.childIndex = 0; this.fixture = fixture; } return b2FixtureProxy; })(); var b2Fixture = (function() { function b2Fixture(def, body) { this.m_density = 0; this.m_next = null; this.m_friction = 0; this.m_restitution = 0; this.m_proxies = []; this.m_proxyCount = 0; this.m_filter = new b2Filter(); this.m_isSensor = false; this.m_userData = null; this.m_body = body; this.m_shape = def.shape.Clone(); } b2Fixture.prototype.GetType = function() { return this.m_shape.GetType(); }; b2Fixture.prototype.GetShape = function() { return this.m_shape; }; b2Fixture.prototype.SetSensor = function(sensor) { if (sensor !== this.m_isSensor) { this.m_body.SetAwake(true); this.m_isSensor = sensor; } }; b2Fixture.prototype.IsSensor = function() { return this.m_isSensor; }; b2Fixture.prototype.SetFilterData = function(filter) { this.m_filter.Copy(filter); this.Refilter(); }; b2Fixture.prototype.GetFilterData = function() { return this.m_filter; }; b2Fixture.prototype.Refilter = function() { var edge = this.m_body.GetContactList(); while (edge) { var contact = edge.contact; var fixtureA = contact.GetFixtureA(); var fixtureB = contact.GetFixtureB(); fixtureA !== this && fixtureB !== this || contact.FlagForFiltering(); edge = edge.next; } var world = this.m_body.GetWorld(); if (null === world) return; var broadPhase = world.m_contactManager.m_broadPhase; for (var i = 0; i < this.m_proxyCount; ++i) broadPhase.TouchProxy(this.m_proxies[i].treeNode); }; b2Fixture.prototype.GetBody = function() { return this.m_body; }; b2Fixture.prototype.GetNext = function() { return this.m_next; }; b2Fixture.prototype.GetUserData = function() { return this.m_userData; }; b2Fixture.prototype.SetUserData = function(data) { this.m_userData = data; }; b2Fixture.prototype.TestPoint = function(p) { return this.m_shape.TestPoint(this.m_body.GetTransform(), p); }; b2Fixture.prototype.ComputeDistance = function(p, normal, childIndex) { return this.m_shape.ComputeDistance(this.m_body.GetTransform(), p, normal, childIndex); }; b2Fixture.prototype.RayCast = function(output, input, childIndex) { return this.m_shape.RayCast(output, input, this.m_body.GetTransform(), childIndex); }; b2Fixture.prototype.GetMassData = function(massData) { void 0 === massData && (massData = new b2MassData()); this.m_shape.ComputeMass(massData, this.m_density); return massData; }; b2Fixture.prototype.SetDensity = function(density) { this.m_density = density; }; b2Fixture.prototype.GetDensity = function() { return this.m_density; }; b2Fixture.prototype.GetFriction = function() { return this.m_friction; }; b2Fixture.prototype.SetFriction = function(friction) { this.m_friction = friction; }; b2Fixture.prototype.GetRestitution = function() { return this.m_restitution; }; b2Fixture.prototype.SetRestitution = function(restitution) { this.m_restitution = restitution; }; b2Fixture.prototype.GetAABB = function(childIndex) { return this.m_proxies[childIndex].aabb; }; b2Fixture.prototype.Dump = function(log, bodyIndex) { log(" const fd: b2FixtureDef = new b2FixtureDef();\n"); log(" fd.friction = %.15f;\n", this.m_friction); log(" fd.restitution = %.15f;\n", this.m_restitution); log(" fd.density = %.15f;\n", this.m_density); log(" fd.isSensor = %s;\n", this.m_isSensor ? "true" : "false"); log(" fd.filter.categoryBits = %d;\n", this.m_filter.categoryBits); log(" fd.filter.maskBits = %d;\n", this.m_filter.maskBits); log(" fd.filter.groupIndex = %d;\n", this.m_filter.groupIndex); this.m_shape.Dump(log); log("\n"); log(" fd.shape = shape;\n"); log("\n"); log(" bodies[%d].CreateFixture(fd);\n", bodyIndex); }; b2Fixture.prototype.Create = function(def) { var _this = this; this.m_userData = def.userData; this.m_friction = b2Maybe(def.friction, .2); this.m_restitution = b2Maybe(def.restitution, 0); this.m_next = null; this.m_filter.Copy(b2Maybe(def.filter, b2Filter.DEFAULT)); this.m_isSensor = b2Maybe(def.isSensor, false); this.m_proxies = b2MakeArray(this.m_shape.GetChildCount(), (function(i) { return new b2FixtureProxy(_this); })); this.m_proxyCount = 0; this.m_density = b2Maybe(def.density, 0); }; b2Fixture.prototype.Destroy = function() {}; b2Fixture.prototype.CreateProxies = function(xf) { var broadPhase = this.m_body.m_world.m_contactManager.m_broadPhase; this.m_proxyCount = this.m_shape.GetChildCount(); for (var i = 0; i < this.m_proxyCount; ++i) { var proxy = this.m_proxies[i] = new b2FixtureProxy(this); this.m_shape.ComputeAABB(proxy.aabb, xf, i); proxy.treeNode = broadPhase.CreateProxy(proxy.aabb, proxy); proxy.childIndex = i; } }; b2Fixture.prototype.DestroyProxies = function() { var broadPhase = this.m_body.m_world.m_contactManager.m_broadPhase; for (var i = 0; i < this.m_proxyCount; ++i) { var proxy = this.m_proxies[i]; delete proxy.treeNode.userData; broadPhase.DestroyProxy(proxy.treeNode); delete proxy.treeNode; } this.m_proxyCount = 0; }; b2Fixture.prototype.TouchProxies = function() { var broadPhase = this.m_body.m_world.m_contactManager.m_broadPhase; var proxyCount = this.m_proxyCount; for (var i = 0; i < proxyCount; ++i) broadPhase.TouchProxy(this.m_proxies[i].treeNode); }; b2Fixture.prototype.Synchronize = function(transform1, transform2) { if (0 === this.m_proxyCount) return; var broadPhase = this.m_body.m_world.m_contactManager.m_broadPhase; for (var i = 0; i < this.m_proxyCount; ++i) { var proxy = this.m_proxies[i]; var aabb1 = b2Fixture.Synchronize_s_aabb1; var aabb2 = b2Fixture.Synchronize_s_aabb2; this.m_shape.ComputeAABB(aabb1, transform1, i); this.m_shape.ComputeAABB(aabb2, transform2, i); proxy.aabb.Combine2(aabb1, aabb2); var displacement = b2Vec2.SubVV(transform2.p, transform1.p, b2Fixture.Synchronize_s_displacement); broadPhase.MoveProxy(proxy.treeNode, proxy.aabb, displacement); } }; b2Fixture.Synchronize_s_aabb1 = new b2AABB(); b2Fixture.Synchronize_s_aabb2 = new b2AABB(); b2Fixture.Synchronize_s_displacement = new b2Vec2(); return b2Fixture; })(); (function(b2BodyType) { b2BodyType[b2BodyType["b2_unknown"] = -1] = "b2_unknown"; b2BodyType[b2BodyType["b2_staticBody"] = 0] = "b2_staticBody"; b2BodyType[b2BodyType["b2_kinematicBody"] = 1] = "b2_kinematicBody"; b2BodyType[b2BodyType["b2_dynamicBody"] = 2] = "b2_dynamicBody"; })(exports.b2BodyType || (exports.b2BodyType = {})); var b2BodyDef = (function() { function b2BodyDef() { this.type = exports.b2BodyType.b2_staticBody; this.position = new b2Vec2(0, 0); this.angle = 0; this.linearVelocity = new b2Vec2(0, 0); this.angularVelocity = 0; this.linearDamping = 0; this.angularDamping = 0; this.allowSleep = true; this.awake = true; this.fixedRotation = false; this.bullet = false; this.active = true; this.userData = null; this.gravityScale = 1; } return b2BodyDef; })(); var b2Body = (function() { function b2Body(bd, world) { this.m_type = exports.b2BodyType.b2_staticBody; this.m_islandFlag = false; this.m_awakeFlag = false; this.m_autoSleepFlag = false; this.m_bulletFlag = false; this.m_fixedRotationFlag = false; this.m_activeFlag = false; this.m_toiFlag = false; this.m_islandIndex = 0; this.m_xf = new b2Transform(); this.m_xf0 = new b2Transform(); this.m_sweep = new b2Sweep(); this.m_linearVelocity = new b2Vec2(); this.m_angularVelocity = 0; this.m_force = new b2Vec2(); this.m_torque = 0; this.m_prev = null; this.m_next = null; this.m_fixtureList = null; this.m_fixtureCount = 0; this.m_jointList = null; this.m_contactList = null; this.m_mass = 1; this.m_invMass = 1; this.m_I = 0; this.m_invI = 0; this.m_linearDamping = 0; this.m_angularDamping = 0; this.m_gravityScale = 1; this.m_sleepTime = 0; this.m_userData = null; this.m_controllerList = null; this.m_controllerCount = 0; this.m_bulletFlag = b2Maybe(bd.bullet, false); this.m_fixedRotationFlag = b2Maybe(bd.fixedRotation, false); this.m_autoSleepFlag = b2Maybe(bd.allowSleep, true); this.m_awakeFlag = b2Maybe(bd.awake, true); this.m_activeFlag = b2Maybe(bd.active, true); this.m_world = world; this.m_xf.p.Copy(b2Maybe(bd.position, b2Vec2.ZERO)); this.m_xf.q.SetAngle(b2Maybe(bd.angle, 0)); this.m_xf0.Copy(this.m_xf); this.m_sweep.localCenter.SetZero(); this.m_sweep.c0.Copy(this.m_xf.p); this.m_sweep.c.Copy(this.m_xf.p); this.m_sweep.a0 = this.m_sweep.a = this.m_xf.q.GetAngle(); this.m_sweep.alpha0 = 0; this.m_linearVelocity.Copy(b2Maybe(bd.linearVelocity, b2Vec2.ZERO)); this.m_angularVelocity = b2Maybe(bd.angularVelocity, 0); this.m_linearDamping = b2Maybe(bd.linearDamping, 0); this.m_angularDamping = b2Maybe(bd.angularDamping, 0); this.m_gravityScale = b2Maybe(bd.gravityScale, 1); this.m_force.SetZero(); this.m_torque = 0; this.m_sleepTime = 0; this.m_type = b2Maybe(bd.type, exports.b2BodyType.b2_staticBody); if (bd.type === exports.b2BodyType.b2_dynamicBody) { this.m_mass = 1; this.m_invMass = 1; } else { this.m_mass = 0; this.m_invMass = 0; } this.m_I = 0; this.m_invI = 0; this.m_userData = bd.userData; this.m_fixtureList = null; this.m_fixtureCount = 0; this.m_controllerList = null; this.m_controllerCount = 0; } b2Body.prototype.CreateFixture = function(a, b) { void 0 === b && (b = 0); return a instanceof b2Shape ? this.CreateFixtureShapeDensity(a, b) : this.CreateFixtureDef(a); }; b2Body.prototype.CreateFixtureDef = function(def) { if (this.m_world.IsLocked()) throw new Error(); var fixture = new b2Fixture(def, this); fixture.Create(def); this.m_activeFlag && fixture.CreateProxies(this.m_xf); fixture.m_next = this.m_fixtureList; this.m_fixtureList = fixture; ++this.m_fixtureCount; fixture.m_density > 0 && this.ResetMassData(); this.m_world.m_newFixture = true; return fixture; }; b2Body.prototype.CreateFixtureShapeDensity = function(shape, density) { void 0 === density && (density = 0); var def = b2Body.CreateFixtureShapeDensity_s_def; def.shape = shape; def.density = density; return this.CreateFixtureDef(def); }; b2Body.prototype.DestroyFixture = function(fixture) { if (this.m_world.IsLocked()) throw new Error(); var node = this.m_fixtureList; var ppF = null; while (null !== node) { if (node === fixture) { ppF ? ppF.m_next = fixture.m_next : this.m_fixtureList = fixture.m_next; break; } ppF = node; node = node.m_next; } var edge = this.m_contactList; while (edge) { var c = edge.contact; edge = edge.next; var fixtureA = c.GetFixtureA(); var fixtureB = c.GetFixtureB(); fixture !== fixtureA && fixture !== fixtureB || this.m_world.m_contactManager.Destroy(c); } this.m_activeFlag && fixture.DestroyProxies(); fixture.m_next = null; fixture.Destroy(); --this.m_fixtureCount; this.ResetMassData(); }; b2Body.prototype.SetTransformVec = function(position, angle) { this.SetTransformXY(position.x, position.y, angle); }; b2Body.prototype.SetTransformXY = function(x, y, angle) { if (this.m_world.IsLocked()) throw new Error(); this.m_xf.q.SetAngle(angle); this.m_xf.p.Set(x, y); this.m_xf0.Copy(this.m_xf); b2Transform.MulXV(this.m_xf, this.m_sweep.localCenter, this.m_sweep.c); this.m_sweep.a = angle; this.m_sweep.c0.Copy(this.m_sweep.c); this.m_sweep.a0 = angle; for (var f = this.m_fixtureList; f; f = f.m_next) f.Synchronize(this.m_xf, this.m_xf); this.m_world.m_contactManager.FindNewContacts(); }; b2Body.prototype.SetTransform = function(xf) { this.SetTransformVec(xf.p, xf.GetAngle()); }; b2Body.prototype.GetTransform = function() { return this.m_xf; }; b2Body.prototype.GetPosition = function() { return this.m_xf.p; }; b2Body.prototype.SetPosition = function(position) { this.SetTransformVec(position, this.GetAngle()); }; b2Body.prototype.SetPositionXY = function(x, y) { this.SetTransformXY(x, y, this.GetAngle()); }; b2Body.prototype.GetAngle = function() { return this.m_sweep.a; }; b2Body.prototype.SetAngle = function(angle) { this.SetTransformVec(this.GetPosition(), angle); }; b2Body.prototype.GetWorldCenter = function() { return this.m_sweep.c; }; b2Body.prototype.GetLocalCenter = function() { return this.m_sweep.localCenter; }; b2Body.prototype.SetLinearVelocity = function(v) { if (this.m_type === exports.b2BodyType.b2_staticBody) return; b2Vec2.DotVV(v, v) > 0 && this.SetAwake(true); this.m_linearVelocity.Copy(v); }; b2Body.prototype.GetLinearVelocity = function() { return this.m_linearVelocity; }; b2Body.prototype.SetAngularVelocity = function(w) { if (this.m_type === exports.b2BodyType.b2_staticBody) return; w * w > 0 && this.SetAwake(true); this.m_angularVelocity = w; }; b2Body.prototype.GetAngularVelocity = function() { return this.m_angularVelocity; }; b2Body.prototype.GetDefinition = function(bd) { bd.type = this.GetType(); bd.allowSleep = this.m_autoSleepFlag; bd.angle = this.GetAngle(); bd.angularDamping = this.m_angularDamping; bd.gravityScale = this.m_gravityScale; bd.angularVelocity = this.m_angularVelocity; bd.fixedRotation = this.m_fixedRotationFlag; bd.bullet = this.m_bulletFlag; bd.awake = this.m_awakeFlag; bd.linearDamping = this.m_linearDamping; bd.linearVelocity.Copy(this.GetLinearVelocity()); bd.position.Copy(this.GetPosition()); bd.userData = this.GetUserData(); return bd; }; b2Body.prototype.ApplyForce = function(force, point, wake) { void 0 === wake && (wake = true); if (this.m_type !== exports.b2BodyType.b2_dynamicBody) return; wake && !this.m_awakeFlag && this.SetAwake(true); if (this.m_awakeFlag) { this.m_force.x += force.x; this.m_force.y += force.y; this.m_torque += (point.x - this.m_sweep.c.x) * force.y - (point.y - this.m_sweep.c.y) * force.x; } }; b2Body.prototype.ApplyForceToCenter = function(force, wake) { void 0 === wake && (wake = true); if (this.m_type !== exports.b2BodyType.b2_dynamicBody) return; wake && !this.m_awakeFlag && this.SetAwake(true); if (this.m_awakeFlag) { this.m_force.x += force.x; this.m_force.y += force.y; } }; b2Body.prototype.ApplyTorque = function(torque, wake) { void 0 === wake && (wake = true); if (this.m_type !== exports.b2BodyType.b2_dynamicBody) return; wake && !this.m_awakeFlag && this.SetAwake(true); this.m_awakeFlag && (this.m_torque += torque); }; b2Body.prototype.ApplyLinearImpulse = function(impulse, point, wake) { void 0 === wake && (wake = true); if (this.m_type !== exports.b2BodyType.b2_dynamicBody) return; wake && !this.m_awakeFlag && this.SetAwake(true); if (this.m_awakeFlag) { this.m_linearVelocity.x += this.m_invMass * impulse.x; this.m_linearVelocity.y += this.m_invMass * impulse.y; this.m_angularVelocity += this.m_invI * ((point.x - this.m_sweep.c.x) * impulse.y - (point.y - this.m_sweep.c.y) * impulse.x); } }; b2Body.prototype.ApplyLinearImpulseToCenter = function(impulse, wake) { void 0 === wake && (wake = true); if (this.m_type !== exports.b2BodyType.b2_dynamicBody) return; wake && !this.m_awakeFlag && this.SetAwake(true); if (this.m_awakeFlag) { this.m_linearVelocity.x += this.m_invMass * impulse.x; this.m_linearVelocity.y += this.m_invMass * impulse.y; } }; b2Body.prototype.ApplyAngularImpulse = function(impulse, wake) { void 0 === wake && (wake = true); if (this.m_type !== exports.b2BodyType.b2_dynamicBody) return; wake && !this.m_awakeFlag && this.SetAwake(true); this.m_awakeFlag && (this.m_angularVelocity += this.m_invI * impulse); }; b2Body.prototype.GetMass = function() { return this.m_mass; }; b2Body.prototype.GetInertia = function() { return this.m_I + this.m_mass * b2Vec2.DotVV(this.m_sweep.localCenter, this.m_sweep.localCenter); }; b2Body.prototype.GetMassData = function(data) { data.mass = this.m_mass; data.I = this.m_I + this.m_mass * b2Vec2.DotVV(this.m_sweep.localCenter, this.m_sweep.localCenter); data.center.Copy(this.m_sweep.localCenter); return data; }; b2Body.prototype.SetMassData = function(massData) { if (this.m_world.IsLocked()) throw new Error(); if (this.m_type !== exports.b2BodyType.b2_dynamicBody) return; this.m_invMass = 0; this.m_I = 0; this.m_invI = 0; this.m_mass = massData.mass; this.m_mass <= 0 && (this.m_mass = 1); this.m_invMass = 1 / this.m_mass; if (massData.I > 0 && !this.m_fixedRotationFlag) { this.m_I = massData.I - this.m_mass * b2Vec2.DotVV(massData.center, massData.center); this.m_invI = 1 / this.m_I; } var oldCenter = b2Body.SetMassData_s_oldCenter.Copy(this.m_sweep.c); this.m_sweep.localCenter.Copy(massData.center); b2Transform.MulXV(this.m_xf, this.m_sweep.localCenter, this.m_sweep.c); this.m_sweep.c0.Copy(this.m_sweep.c); b2Vec2.AddVCrossSV(this.m_linearVelocity, this.m_angularVelocity, b2Vec2.SubVV(this.m_sweep.c, oldCenter, b2Vec2.s_t0), this.m_linearVelocity); }; b2Body.prototype.ResetMassData = function() { this.m_mass = 0; this.m_invMass = 0; this.m_I = 0; this.m_invI = 0; this.m_sweep.localCenter.SetZero(); if (this.m_type === exports.b2BodyType.b2_staticBody || this.m_type === exports.b2BodyType.b2_kinematicBody) { this.m_sweep.c0.Copy(this.m_xf.p); this.m_sweep.c.Copy(this.m_xf.p); this.m_sweep.a0 = this.m_sweep.a; return; } var localCenter = b2Body.ResetMassData_s_localCenter.SetZero(); for (var f = this.m_fixtureList; f; f = f.m_next) { if (0 === f.m_density) continue; var massData = f.GetMassData(b2Body.ResetMassData_s_massData); this.m_mass += massData.mass; localCenter.x += massData.center.x * massData.mass; localCenter.y += massData.center.y * massData.mass; this.m_I += massData.I; } if (this.m_mass > 0) { this.m_invMass = 1 / this.m_mass; localCenter.x *= this.m_invMass; localCenter.y *= this.m_invMass; } else { this.m_mass = 1; this.m_invMass = 1; } if (this.m_I > 0 && !this.m_fixedRotationFlag) { this.m_I -= this.m_mass * b2Vec2.DotVV(localCenter, localCenter); this.m_invI = 1 / this.m_I; } else { this.m_I = 0; this.m_invI = 0; } var oldCenter = b2Body.ResetMassData_s_oldCenter.Copy(this.m_sweep.c); this.m_sweep.localCenter.Copy(localCenter); b2Transform.MulXV(this.m_xf, this.m_sweep.localCenter, this.m_sweep.c); this.m_sweep.c0.Copy(this.m_sweep.c); b2Vec2.AddVCrossSV(this.m_linearVelocity, this.m_angularVelocity, b2Vec2.SubVV(this.m_sweep.c, oldCenter, b2Vec2.s_t0), this.m_linearVelocity); }; b2Body.prototype.GetWorldPoint = function(localPoint, out) { return b2Transform.MulXV(this.m_xf, localPoint, out); }; b2Body.prototype.GetWorldVector = function(localVector, out) { return b2Rot.MulRV(this.m_xf.q, localVector, out); }; b2Body.prototype.GetLocalPoint = function(worldPoint, out) { return b2Transform.MulTXV(this.m_xf, worldPoint, out); }; b2Body.prototype.GetLocalVector = function(worldVector, out) { return b2Rot.MulTRV(this.m_xf.q, worldVector, out); }; b2Body.prototype.GetLinearVelocityFromWorldPoint = function(worldPoint, out) { return b2Vec2.AddVCrossSV(this.m_linearVelocity, this.m_angularVelocity, b2Vec2.SubVV(worldPoint, this.m_sweep.c, b2Vec2.s_t0), out); }; b2Body.prototype.GetLinearVelocityFromLocalPoint = function(localPoint, out) { return this.GetLinearVelocityFromWorldPoint(this.GetWorldPoint(localPoint, out), out); }; b2Body.prototype.GetLinearDamping = function() { return this.m_linearDamping; }; b2Body.prototype.SetLinearDamping = function(linearDamping) { this.m_linearDamping = linearDamping; }; b2Body.prototype.GetAngularDamping = function() { return this.m_angularDamping; }; b2Body.prototype.SetAngularDamping = function(angularDamping) { this.m_angularDamping = angularDamping; }; b2Body.prototype.GetGravityScale = function() { return this.m_gravityScale; }; b2Body.prototype.SetGravityScale = function(scale) { this.m_gravityScale = scale; }; b2Body.prototype.SetType = function(type) { if (this.m_world.IsLocked()) throw new Error(); if (this.m_type === type) return; this.m_type = type; this.ResetMassData(); if (this.m_type === exports.b2BodyType.b2_staticBody) { this.m_linearVelocity.SetZero(); this.m_angularVelocity = 0; this.m_sweep.a0 = this.m_sweep.a; this.m_sweep.c0.Copy(this.m_sweep.c); this.SynchronizeFixtures(); } this.SetAwake(true); this.m_force.SetZero(); this.m_torque = 0; var ce = this.m_contactList; while (ce) { var ce0 = ce; ce = ce.next; this.m_world.m_contactManager.Destroy(ce0.contact); } this.m_contactList = null; for (var f = this.m_fixtureList; f; f = f.m_next) f.TouchProxies(); }; b2Body.prototype.GetType = function() { return this.m_type; }; b2Body.prototype.SetBullet = function(flag) { this.m_bulletFlag = flag; }; b2Body.prototype.IsBullet = function() { return this.m_bulletFlag; }; b2Body.prototype.SetSleepingAllowed = function(flag) { this.m_autoSleepFlag = flag; flag || this.SetAwake(true); }; b2Body.prototype.IsSleepingAllowed = function() { return this.m_autoSleepFlag; }; b2Body.prototype.SetAwake = function(flag) { if (flag) { this.m_awakeFlag = true; this.m_sleepTime = 0; } else { this.m_awakeFlag = false; this.m_sleepTime = 0; this.m_linearVelocity.SetZero(); this.m_angularVelocity = 0; this.m_force.SetZero(); this.m_torque = 0; } }; b2Body.prototype.IsAwake = function() { return this.m_awakeFlag; }; b2Body.prototype.SetActive = function(flag) { if (this.m_world.IsLocked()) throw new Error(); if (flag === this.IsActive()) return; this.m_activeFlag = flag; if (flag) for (var f = this.m_fixtureList; f; f = f.m_next) f.CreateProxies(this.m_xf); else { for (var f = this.m_fixtureList; f; f = f.m_next) f.DestroyProxies(); var ce = this.m_contactList; while (ce) { var ce0 = ce; ce = ce.next; this.m_world.m_contactManager.Destroy(ce0.contact); } this.m_contactList = null; } }; b2Body.prototype.IsActive = function() { return this.m_activeFlag; }; b2Body.prototype.SetFixedRotation = function(flag) { if (this.m_fixedRotationFlag === flag) return; this.m_fixedRotationFlag = flag; this.m_angularVelocity = 0; this.ResetMassData(); }; b2Body.prototype.IsFixedRotation = function() { return this.m_fixedRotationFlag; }; b2Body.prototype.GetFixtureList = function() { return this.m_fixtureList; }; b2Body.prototype.GetJointList = function() { return this.m_jointList; }; b2Body.prototype.GetContactList = function() { return this.m_contactList; }; b2Body.prototype.GetNext = function() { return this.m_next; }; b2Body.prototype.GetUserData = function() { return this.m_userData; }; b2Body.prototype.SetUserData = function(data) { this.m_userData = data; }; b2Body.prototype.GetWorld = function() { return this.m_world; }; b2Body.prototype.Dump = function(log) { var bodyIndex = this.m_islandIndex; log("{\n"); log(" const bd: b2BodyDef = new b2BodyDef();\n"); var type_str = ""; switch (this.m_type) { case exports.b2BodyType.b2_staticBody: type_str = "b2BodyType.b2_staticBody"; break; case exports.b2BodyType.b2_kinematicBody: type_str = "b2BodyType.b2_kinematicBody"; break; case exports.b2BodyType.b2_dynamicBody: type_str = "b2BodyType.b2_dynamicBody"; } log(" bd.type = %s;\n", type_str); log(" bd.position.Set(%.15f, %.15f);\n", this.m_xf.p.x, this.m_xf.p.y); log(" bd.angle = %.15f;\n", this.m_sweep.a); log(" bd.linearVelocity.Set(%.15f, %.15f);\n", this.m_linearVelocity.x, this.m_linearVelocity.y); log(" bd.angularVelocity = %.15f;\n", this.m_angularVelocity); log(" bd.linearDamping = %.15f;\n", this.m_linearDamping); log(" bd.angularDamping = %.15f;\n", this.m_angularDamping); log(" bd.allowSleep = %s;\n", this.m_autoSleepFlag ? "true" : "false"); log(" bd.awake = %s;\n", this.m_awakeFlag ? "true" : "false"); log(" bd.fixedRotation = %s;\n", this.m_fixedRotationFlag ? "true" : "false"); log(" bd.bullet = %s;\n", this.m_bulletFlag ? "true" : "false"); log(" bd.active = %s;\n", this.m_activeFlag ? "true" : "false"); log(" bd.gravityScale = %.15f;\n", this.m_gravityScale); log("\n"); log(" bodies[%d] = this.m_world.CreateBody(bd);\n", this.m_islandIndex); log("\n"); for (var f = this.m_fixtureList; f; f = f.m_next) { log(" {\n"); f.Dump(log, bodyIndex); log(" }\n"); } log("}\n"); }; b2Body.prototype.SynchronizeFixtures = function() { var xf1 = b2Body.SynchronizeFixtures_s_xf1; xf1.q.SetAngle(this.m_sweep.a0); b2Rot.MulRV(xf1.q, this.m_sweep.localCenter, xf1.p); b2Vec2.SubVV(this.m_sweep.c0, xf1.p, xf1.p); for (var f = this.m_fixtureList; f; f = f.m_next) f.Synchronize(xf1, this.m_xf); }; b2Body.prototype.SynchronizeTransform = function() { this.m_xf.q.SetAngle(this.m_sweep.a); b2Rot.MulRV(this.m_xf.q, this.m_sweep.localCenter, this.m_xf.p); b2Vec2.SubVV(this.m_sweep.c, this.m_xf.p, this.m_xf.p); }; b2Body.prototype.ShouldCollide = function(other) { if (this.m_type === exports.b2BodyType.b2_staticBody && other.m_type === exports.b2BodyType.b2_staticBody) return false; return this.ShouldCollideConnected(other); }; b2Body.prototype.ShouldCollideConnected = function(other) { for (var jn = this.m_jointList; jn; jn = jn.next) if (jn.other === other && !jn.joint.m_collideConnected) return false; return true; }; b2Body.prototype.Advance = function(alpha) { this.m_sweep.Advance(alpha); this.m_sweep.c.Copy(this.m_sweep.c0); this.m_sweep.a = this.m_sweep.a0; this.m_xf.q.SetAngle(this.m_sweep.a); b2Rot.MulRV(this.m_xf.q, this.m_sweep.localCenter, this.m_xf.p); b2Vec2.SubVV(this.m_sweep.c, this.m_xf.p, this.m_xf.p); }; b2Body.prototype.GetControllerList = function() { return this.m_controllerList; }; b2Body.prototype.GetControllerCount = function() { return this.m_controllerCount; }; b2Body.CreateFixtureShapeDensity_s_def = new b2FixtureDef(); b2Body.SetMassData_s_oldCenter = new b2Vec2(); b2Body.ResetMassData_s_localCenter = new b2Vec2(); b2Body.ResetMassData_s_oldCenter = new b2Vec2(); b2Body.ResetMassData_s_massData = new b2MassData(); b2Body.SynchronizeFixtures_s_xf1 = new b2Transform(); return b2Body; })(); (function(b2JointType) { b2JointType[b2JointType["e_unknownJoint"] = 0] = "e_unknownJoint"; b2JointType[b2JointType["e_revoluteJoint"] = 1] = "e_revoluteJoint"; b2JointType[b2JointType["e_prismaticJoint"] = 2] = "e_prismaticJoint"; b2JointType[b2JointType["e_distanceJoint"] = 3] = "e_distanceJoint"; b2JointType[b2JointType["e_pulleyJoint"] = 4] = "e_pulleyJoint"; b2JointType[b2JointType["e_mouseJoint"] = 5] = "e_mouseJoint"; b2JointType[b2JointType["e_gearJoint"] = 6] = "e_gearJoint"; b2JointType[b2JointType["e_wheelJoint"] = 7] = "e_wheelJoint"; b2JointType[b2JointType["e_weldJoint"] = 8] = "e_weldJoint"; b2JointType[b2JointType["e_frictionJoint"] = 9] = "e_frictionJoint"; b2JointType[b2JointType["e_ropeJoint"] = 10] = "e_ropeJoint"; b2JointType[b2JointType["e_motorJoint"] = 11] = "e_motorJoint"; b2JointType[b2JointType["e_areaJoint"] = 12] = "e_areaJoint"; })(exports.b2JointType || (exports.b2JointType = {})); (function(b2LimitState) { b2LimitState[b2LimitState["e_inactiveLimit"] = 0] = "e_inactiveLimit"; b2LimitState[b2LimitState["e_atLowerLimit"] = 1] = "e_atLowerLimit"; b2LimitState[b2LimitState["e_atUpperLimit"] = 2] = "e_atUpperLimit"; b2LimitState[b2LimitState["e_equalLimits"] = 3] = "e_equalLimits"; })(exports.b2LimitState || (exports.b2LimitState = {})); var b2Jacobian = (function() { function b2Jacobian() { this.linear = new b2Vec2(); this.angularA = 0; this.angularB = 0; } b2Jacobian.prototype.SetZero = function() { this.linear.SetZero(); this.angularA = 0; this.angularB = 0; return this; }; b2Jacobian.prototype.Set = function(x, a1, a2) { this.linear.Copy(x); this.angularA = a1; this.angularB = a2; return this; }; return b2Jacobian; })(); var b2JointEdge = (function() { function b2JointEdge(joint, other) { this.prev = null; this.next = null; this.joint = joint; this.other = other; } return b2JointEdge; })(); var b2JointDef = (function() { function b2JointDef(type) { this.type = exports.b2JointType.e_unknownJoint; this.userData = null; this.collideConnected = false; this.type = type; } return b2JointDef; })(); var b2Joint = (function() { function b2Joint(def) { this.m_type = exports.b2JointType.e_unknownJoint; this.m_prev = null; this.m_next = null; this.m_index = 0; this.m_islandFlag = false; this.m_collideConnected = false; this.m_userData = null; this.m_type = def.type; this.m_edgeA = new b2JointEdge(this, def.bodyB); this.m_edgeB = new b2JointEdge(this, def.bodyA); this.m_bodyA = def.bodyA; this.m_bodyB = def.bodyB; this.m_collideConnected = b2Maybe(def.collideConnected, false); this.m_userData = def.userData; } b2Joint.prototype.GetType = function() { return this.m_type; }; b2Joint.prototype.GetBodyA = function() { return this.m_bodyA; }; b2Joint.prototype.GetBodyB = function() { return this.m_bodyB; }; b2Joint.prototype.GetNext = function() { return this.m_next; }; b2Joint.prototype.GetUserData = function() { return this.m_userData; }; b2Joint.prototype.SetUserData = function(data) { this.m_userData = data; }; b2Joint.prototype.IsActive = function() { return this.m_bodyA.IsActive() && this.m_bodyB.IsActive(); }; b2Joint.prototype.GetCollideConnected = function() { return this.m_collideConnected; }; b2Joint.prototype.Dump = function(log) { log("// Dump is not supported for this joint type.\n"); }; b2Joint.prototype.ShiftOrigin = function(newOrigin) {}; return b2Joint; })(); var b2DistanceJointDef = (function(_super) { __extends(b2DistanceJointDef, _super); function b2DistanceJointDef() { var _this = _super.call(this, exports.b2JointType.e_distanceJoint) || this; _this.localAnchorA = new b2Vec2(); _this.localAnchorB = new b2Vec2(); _this.length = 1; _this.frequencyHz = 0; _this.dampingRatio = 0; return _this; } b2DistanceJointDef.prototype.Initialize = function(b1, b2, anchor1, anchor2) { this.bodyA = b1; this.bodyB = b2; this.bodyA.GetLocalPoint(anchor1, this.localAnchorA); this.bodyB.GetLocalPoint(anchor2, this.localAnchorB); this.length = b2Vec2.DistanceVV(anchor1, anchor2); this.frequencyHz = 0; this.dampingRatio = 0; }; return b2DistanceJointDef; })(b2JointDef); var b2DistanceJoint = (function(_super) { __extends(b2DistanceJoint, _super); function b2DistanceJoint(def) { var _this = _super.call(this, def) || this; _this.m_frequencyHz = 0; _this.m_dampingRatio = 0; _this.m_bias = 0; _this.m_localAnchorA = new b2Vec2(); _this.m_localAnchorB = new b2Vec2(); _this.m_gamma = 0; _this.m_impulse = 0; _this.m_length = 0; _this.m_indexA = 0; _this.m_indexB = 0; _this.m_u = new b2Vec2(); _this.m_rA = new b2Vec2(); _this.m_rB = new b2Vec2(); _this.m_localCenterA = new b2Vec2(); _this.m_localCenterB = new b2Vec2(); _this.m_invMassA = 0; _this.m_invMassB = 0; _this.m_invIA = 0; _this.m_invIB = 0; _this.m_mass = 0; _this.m_qA = new b2Rot(); _this.m_qB = new b2Rot(); _this.m_lalcA = new b2Vec2(); _this.m_lalcB = new b2Vec2(); _this.m_frequencyHz = b2Maybe(def.frequencyHz, 0); _this.m_dampingRatio = b2Maybe(def.dampingRatio, 0); _this.m_localAnchorA.Copy(def.localAnchorA); _this.m_localAnchorB.Copy(def.localAnchorB); _this.m_length = def.length; return _this; } b2DistanceJoint.prototype.GetAnchorA = function(out) { return this.m_bodyA.GetWorldPoint(this.m_localAnchorA, out); }; b2DistanceJoint.prototype.GetAnchorB = function(out) { return this.m_bodyB.GetWorldPoint(this.m_localAnchorB, out); }; b2DistanceJoint.prototype.GetReactionForce = function(inv_dt, out) { out.x = inv_dt * this.m_impulse * this.m_u.x; out.y = inv_dt * this.m_impulse * this.m_u.y; return out; }; b2DistanceJoint.prototype.GetReactionTorque = function(inv_dt) { return 0; }; b2DistanceJoint.prototype.GetLocalAnchorA = function() { return this.m_localAnchorA; }; b2DistanceJoint.prototype.GetLocalAnchorB = function() { return this.m_localAnchorB; }; b2DistanceJoint.prototype.SetLength = function(length) { this.m_length = length; }; b2DistanceJoint.prototype.Length = function() { return this.m_length; }; b2DistanceJoint.prototype.SetFrequency = function(hz) { this.m_frequencyHz = hz; }; b2DistanceJoint.prototype.GetFrequency = function() { return this.m_frequencyHz; }; b2DistanceJoint.prototype.SetDampingRatio = function(ratio) { this.m_dampingRatio = ratio; }; b2DistanceJoint.prototype.GetDampingRatio = function() { return this.m_dampingRatio; }; b2DistanceJoint.prototype.Dump = function(log) { var indexA = this.m_bodyA.m_islandIndex; var indexB = this.m_bodyB.m_islandIndex; log(" const jd: b2DistanceJointDef = new b2DistanceJointDef();\n"); log(" jd.bodyA = bodies[%d];\n", indexA); log(" jd.bodyB = bodies[%d];\n", indexB); log(" jd.collideConnected = %s;\n", this.m_collideConnected ? "true" : "false"); log(" jd.localAnchorA.Set(%.15f, %.15f);\n", this.m_localAnchorA.x, this.m_localAnchorA.y); log(" jd.localAnchorB.Set(%.15f, %.15f);\n", this.m_localAnchorB.x, this.m_localAnchorB.y); log(" jd.length = %.15f;\n", this.m_length); log(" jd.frequencyHz = %.15f;\n", this.m_frequencyHz); log(" jd.dampingRatio = %.15f;\n", this.m_dampingRatio); log(" joints[%d] = this.m_world.CreateJoint(jd);\n", this.m_index); }; b2DistanceJoint.prototype.InitVelocityConstraints = function(data) { this.m_indexA = this.m_bodyA.m_islandIndex; this.m_indexB = this.m_bodyB.m_islandIndex; this.m_localCenterA.Copy(this.m_bodyA.m_sweep.localCenter); this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter); this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var cA = data.positions[this.m_indexA].c; var aA = data.positions[this.m_indexA].a; var vA = data.velocities[this.m_indexA].v; var wA = data.velocities[this.m_indexA].w; var cB = data.positions[this.m_indexB].c; var aB = data.positions[this.m_indexB].a; var vB = data.velocities[this.m_indexB].v; var wB = data.velocities[this.m_indexB].w; var qA = this.m_qA.SetAngle(aA), qB = this.m_qB.SetAngle(aB); b2Vec2.SubVV(this.m_localAnchorA, this.m_localCenterA, this.m_lalcA); b2Rot.MulRV(qA, this.m_lalcA, this.m_rA); b2Vec2.SubVV(this.m_localAnchorB, this.m_localCenterB, this.m_lalcB); b2Rot.MulRV(qB, this.m_lalcB, this.m_rB); this.m_u.x = cB.x + this.m_rB.x - cA.x - this.m_rA.x; this.m_u.y = cB.y + this.m_rB.y - cA.y - this.m_rA.y; var length = this.m_u.Length(); length > b2_linearSlop ? this.m_u.SelfMul(1 / length) : this.m_u.SetZero(); var crAu = b2Vec2.CrossVV(this.m_rA, this.m_u); var crBu = b2Vec2.CrossVV(this.m_rB, this.m_u); var invMass = this.m_invMassA + this.m_invIA * crAu * crAu + this.m_invMassB + this.m_invIB * crBu * crBu; this.m_mass = 0 !== invMass ? 1 / invMass : 0; if (this.m_frequencyHz > 0) { var C = length - this.m_length; var omega = 2 * b2_pi * this.m_frequencyHz; var d = 2 * this.m_mass * this.m_dampingRatio * omega; var k = this.m_mass * omega * omega; var h = data.step.dt; this.m_gamma = h * (d + h * k); this.m_gamma = 0 !== this.m_gamma ? 1 / this.m_gamma : 0; this.m_bias = C * h * k * this.m_gamma; invMass += this.m_gamma; this.m_mass = 0 !== invMass ? 1 / invMass : 0; } else { this.m_gamma = 0; this.m_bias = 0; } if (data.step.warmStarting) { this.m_impulse *= data.step.dtRatio; var P = b2Vec2.MulSV(this.m_impulse, this.m_u, b2DistanceJoint.InitVelocityConstraints_s_P); vA.SelfMulSub(this.m_invMassA, P); wA -= this.m_invIA * b2Vec2.CrossVV(this.m_rA, P); vB.SelfMulAdd(this.m_invMassB, P); wB += this.m_invIB * b2Vec2.CrossVV(this.m_rB, P); } else this.m_impulse = 0; data.velocities[this.m_indexA].w = wA; data.velocities[this.m_indexB].w = wB; }; b2DistanceJoint.prototype.SolveVelocityConstraints = function(data) { var vA = data.velocities[this.m_indexA].v; var wA = data.velocities[this.m_indexA].w; var vB = data.velocities[this.m_indexB].v; var wB = data.velocities[this.m_indexB].w; var vpA = b2Vec2.AddVCrossSV(vA, wA, this.m_rA, b2DistanceJoint.SolveVelocityConstraints_s_vpA); var vpB = b2Vec2.AddVCrossSV(vB, wB, this.m_rB, b2DistanceJoint.SolveVelocityConstraints_s_vpB); var Cdot = b2Vec2.DotVV(this.m_u, b2Vec2.SubVV(vpB, vpA, b2Vec2.s_t0)); var impulse = -this.m_mass * (Cdot + this.m_bias + this.m_gamma * this.m_impulse); this.m_impulse += impulse; var P = b2Vec2.MulSV(impulse, this.m_u, b2DistanceJoint.SolveVelocityConstraints_s_P); vA.SelfMulSub(this.m_invMassA, P); wA -= this.m_invIA * b2Vec2.CrossVV(this.m_rA, P); vB.SelfMulAdd(this.m_invMassB, P); wB += this.m_invIB * b2Vec2.CrossVV(this.m_rB, P); data.velocities[this.m_indexA].w = wA; data.velocities[this.m_indexB].w = wB; }; b2DistanceJoint.prototype.SolvePositionConstraints = function(data) { if (this.m_frequencyHz > 0) return true; var cA = data.positions[this.m_indexA].c; var aA = data.positions[this.m_indexA].a; var cB = data.positions[this.m_indexB].c; var aB = data.positions[this.m_indexB].a; var qA = this.m_qA.SetAngle(aA), qB = this.m_qB.SetAngle(aB); var rA = b2Rot.MulRV(qA, this.m_lalcA, this.m_rA); var rB = b2Rot.MulRV(qB, this.m_lalcB, this.m_rB); var u = this.m_u; u.x = cB.x + rB.x - cA.x - rA.x; u.y = cB.y + rB.y - cA.y - rA.y; var length = this.m_u.Normalize(); var C = length - this.m_length; C = b2Clamp(C, -b2_maxLinearCorrection, b2_maxLinearCorrection); var impulse = -this.m_mass * C; var P = b2Vec2.MulSV(impulse, u, b2DistanceJoint.SolvePositionConstraints_s_P); cA.SelfMulSub(this.m_invMassA, P); aA -= this.m_invIA * b2Vec2.CrossVV(rA, P); cB.SelfMulAdd(this.m_invMassB, P); aB += this.m_invIB * b2Vec2.CrossVV(rB, P); data.positions[this.m_indexA].a = aA; data.positions[this.m_indexB].a = aB; return b2Abs(C) < b2_linearSlop; }; b2DistanceJoint.InitVelocityConstraints_s_P = new b2Vec2(); b2DistanceJoint.SolveVelocityConstraints_s_vpA = new b2Vec2(); b2DistanceJoint.SolveVelocityConstraints_s_vpB = new b2Vec2(); b2DistanceJoint.SolveVelocityConstraints_s_P = new b2Vec2(); b2DistanceJoint.SolvePositionConstraints_s_P = new b2Vec2(); return b2DistanceJoint; })(b2Joint); var b2AreaJointDef = (function(_super) { __extends(b2AreaJointDef, _super); function b2AreaJointDef() { var _this = _super.call(this, exports.b2JointType.e_areaJoint) || this; _this.bodies = []; _this.frequencyHz = 0; _this.dampingRatio = 0; return _this; } b2AreaJointDef.prototype.AddBody = function(body) { this.bodies.push(body); 1 === this.bodies.length ? this.bodyA = body : 2 === this.bodies.length && (this.bodyB = body); }; return b2AreaJointDef; })(b2JointDef); var b2AreaJoint = (function(_super) { __extends(b2AreaJoint, _super); function b2AreaJoint(def) { var _this = _super.call(this, def) || this; _this.m_frequencyHz = 0; _this.m_dampingRatio = 0; _this.m_impulse = 0; _this.m_targetArea = 0; _this.m_bodies = def.bodies; _this.m_frequencyHz = b2Maybe(def.frequencyHz, 0); _this.m_dampingRatio = b2Maybe(def.dampingRatio, 0); _this.m_targetLengths = b2MakeNumberArray(def.bodies.length); _this.m_normals = b2Vec2.MakeArray(def.bodies.length); _this.m_joints = []; _this.m_deltas = b2Vec2.MakeArray(def.bodies.length); _this.m_delta = new b2Vec2(); var djd = new b2DistanceJointDef(); djd.frequencyHz = _this.m_frequencyHz; djd.dampingRatio = _this.m_dampingRatio; _this.m_targetArea = 0; for (var i = 0; i < _this.m_bodies.length; ++i) { var body = _this.m_bodies[i]; var next = _this.m_bodies[(i + 1) % _this.m_bodies.length]; var body_c = body.GetWorldCenter(); var next_c = next.GetWorldCenter(); _this.m_targetLengths[i] = b2Vec2.DistanceVV(body_c, next_c); _this.m_targetArea += b2Vec2.CrossVV(body_c, next_c); djd.Initialize(body, next, body_c, next_c); _this.m_joints[i] = body.GetWorld().CreateJoint(djd); } _this.m_targetArea *= .5; return _this; } b2AreaJoint.prototype.GetAnchorA = function(out) { return out; }; b2AreaJoint.prototype.GetAnchorB = function(out) { return out; }; b2AreaJoint.prototype.GetReactionForce = function(inv_dt, out) { return out; }; b2AreaJoint.prototype.GetReactionTorque = function(inv_dt) { return 0; }; b2AreaJoint.prototype.SetFrequency = function(hz) { this.m_frequencyHz = hz; for (var i = 0; i < this.m_joints.length; ++i) this.m_joints[i].SetFrequency(hz); }; b2AreaJoint.prototype.GetFrequency = function() { return this.m_frequencyHz; }; b2AreaJoint.prototype.SetDampingRatio = function(ratio) { this.m_dampingRatio = ratio; for (var i = 0; i < this.m_joints.length; ++i) this.m_joints[i].SetDampingRatio(ratio); }; b2AreaJoint.prototype.GetDampingRatio = function() { return this.m_dampingRatio; }; b2AreaJoint.prototype.Dump = function(log) { log("Area joint dumping is not supported.\n"); }; b2AreaJoint.prototype.InitVelocityConstraints = function(data) { for (var i = 0; i < this.m_bodies.length; ++i) { var prev = this.m_bodies[(i + this.m_bodies.length - 1) % this.m_bodies.length]; var next = this.m_bodies[(i + 1) % this.m_bodies.length]; var prev_c = data.positions[prev.m_islandIndex].c; var next_c = data.positions[next.m_islandIndex].c; var delta = this.m_deltas[i]; b2Vec2.SubVV(next_c, prev_c, delta); } if (data.step.warmStarting) { this.m_impulse *= data.step.dtRatio; for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; var body_v = data.velocities[body.m_islandIndex].v; var delta = this.m_deltas[i]; body_v.x += body.m_invMass * delta.y * .5 * this.m_impulse; body_v.y += body.m_invMass * -delta.x * .5 * this.m_impulse; } } else this.m_impulse = 0; }; b2AreaJoint.prototype.SolveVelocityConstraints = function(data) { var dotMassSum = 0; var crossMassSum = 0; for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; var body_v = data.velocities[body.m_islandIndex].v; var delta = this.m_deltas[i]; dotMassSum += delta.LengthSquared() / body.GetMass(); crossMassSum += b2Vec2.CrossVV(body_v, delta); } var lambda = -2 * crossMassSum / dotMassSum; this.m_impulse += lambda; for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; var body_v = data.velocities[body.m_islandIndex].v; var delta = this.m_deltas[i]; body_v.x += body.m_invMass * delta.y * .5 * lambda; body_v.y += body.m_invMass * -delta.x * .5 * lambda; } }; b2AreaJoint.prototype.SolvePositionConstraints = function(data) { var perimeter = 0; var area = 0; for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; var next = this.m_bodies[(i + 1) % this.m_bodies.length]; var body_c = data.positions[body.m_islandIndex].c; var next_c = data.positions[next.m_islandIndex].c; var delta = b2Vec2.SubVV(next_c, body_c, this.m_delta); var dist = delta.Length(); dist < b2_epsilon && (dist = 1); this.m_normals[i].x = delta.y / dist; this.m_normals[i].y = -delta.x / dist; perimeter += dist; area += b2Vec2.CrossVV(body_c, next_c); } area *= .5; var deltaArea = this.m_targetArea - area; var toExtrude = .5 * deltaArea / perimeter; var done = true; for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; var body_c = data.positions[body.m_islandIndex].c; var next_i = (i + 1) % this.m_bodies.length; var delta = b2Vec2.AddVV(this.m_normals[i], this.m_normals[next_i], this.m_delta); delta.SelfMul(toExtrude); var norm_sq = delta.LengthSquared(); norm_sq > b2Sq(b2_maxLinearCorrection) && delta.SelfMul(b2_maxLinearCorrection / b2Sqrt(norm_sq)); norm_sq > b2Sq(b2_linearSlop) && (done = false); body_c.x += delta.x; body_c.y += delta.y; } return done; }; return b2AreaJoint; })(b2Joint); var b2FrictionJointDef = (function(_super) { __extends(b2FrictionJointDef, _super); function b2FrictionJointDef() { var _this = _super.call(this, exports.b2JointType.e_frictionJoint) || this; _this.localAnchorA = new b2Vec2(); _this.localAnchorB = new b2Vec2(); _this.maxForce = 0; _this.maxTorque = 0; return _this; } b2FrictionJointDef.prototype.Initialize = function(bA, bB, anchor) { this.bodyA = bA; this.bodyB = bB; this.bodyA.GetLocalPoint(anchor, this.localAnchorA); this.bodyB.GetLocalPoint(anchor, this.localAnchorB); }; return b2FrictionJointDef; })(b2JointDef); var b2FrictionJoint = (function(_super) { __extends(b2FrictionJoint, _super); function b2FrictionJoint(def) { var _this = _super.call(this, def) || this; _this.m_localAnchorA = new b2Vec2(); _this.m_localAnchorB = new b2Vec2(); _this.m_linearImpulse = new b2Vec2(); _this.m_angularImpulse = 0; _this.m_maxForce = 0; _this.m_maxTorque = 0; _this.m_indexA = 0; _this.m_indexB = 0; _this.m_rA = new b2Vec2(); _this.m_rB = new b2Vec2(); _this.m_localCenterA = new b2Vec2(); _this.m_localCenterB = new b2Vec2(); _this.m_invMassA = 0; _this.m_invMassB = 0; _this.m_invIA = 0; _this.m_invIB = 0; _this.m_linearMass = new b2Mat22(); _this.m_angularMass = 0; _this.m_qA = new b2Rot(); _this.m_qB = new b2Rot(); _this.m_lalcA = new b2Vec2(); _this.m_lalcB = new b2Vec2(); _this.m_K = new b2Mat22(); _this.m_localAnchorA.Copy(def.localAnchorA); _this.m_localAnchorB.Copy(def.localAnchorB); _this.m_linearImpulse.SetZero(); _this.m_maxForce = b2Maybe(def.maxForce, 0); _this.m_maxTorque = b2Maybe(def.maxTorque, 0); _this.m_linearMass.SetZero(); return _this; } b2FrictionJoint.prototype.InitVelocityConstraints = function(data) { this.m_indexA = this.m_bodyA.m_islandIndex; this.m_indexB = this.m_bodyB.m_islandIndex; this.m_localCenterA.Copy(this.m_bodyA.m_sweep.localCenter); this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter); this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var aA = data.positions[this.m_indexA].a; var vA = data.velocities[this.m_indexA].v; var wA = data.velocities[this.m_indexA].w; var aB = data.positions[this.m_indexB].a; var vB = data.velocities[this.m_indexB].v; var wB = data.velocities[this.m_indexB].w; var qA = this.m_qA.SetAngle(aA), qB = this.m_qB.SetAngle(aB); b2Vec2.SubVV(this.m_localAnchorA, this.m_localCenterA, this.m_lalcA); var rA = b2Rot.MulRV(qA, this.m_lalcA, this.m_rA); b2Vec2.SubVV(this.m_localAnchorB, this.m_localCenterB, this.m_lalcB); var rB = b2Rot.MulRV(qB, this.m_lalcB, this.m_rB); var mA = this.m_invMassA, mB = this.m_invMassB; var iA = this.m_invIA, iB = this.m_invIB; var K = this.m_K; K.ex.x = mA + mB + iA * rA.y * rA.y + iB * rB.y * rB.y; K.ex.y = -iA * rA.x * rA.y - iB * rB.x * rB.y; K.ey.x = K.ex.y; K.ey.y = mA + mB + iA * rA.x * rA.x + iB * rB.x * rB.x; K.GetInverse(this.m_linearMass); this.m_angularMass = iA + iB; this.m_angularMass > 0 && (this.m_angularMass = 1 / this.m_angularMass); if (data.step.warmStarting) { this.m_linearImpulse.SelfMul(data.step.dtRatio); this.m_angularImpulse *= data.step.dtRatio; var P = this.m_linearImpulse; vA.SelfMulSub(mA, P); wA -= iA * (b2Vec2.CrossVV(this.m_rA, P) + this.m_angularImpulse); vB.SelfMulAdd(mB, P); wB += iB * (b2Vec2.CrossVV(this.m_rB, P) + this.m_angularImpulse); } else { this.m_linearImpulse.SetZero(); this.m_angularImpulse = 0; } data.velocities[this.m_indexA].w = wA; data.velocities[this.m_indexB].w = wB; }; b2FrictionJoint.prototype.SolveVelocityConstraints = function(data) { var vA = data.velocities[this.m_indexA].v; var wA = data.velocities[this.m_indexA].w; var vB = data.velocities[this.m_indexB].v; var wB = data.velocities[this.m_indexB].w; var mA = this.m_invMassA, mB = this.m_invMassB; var iA = this.m_invIA, iB = this.m_invIB; var h = data.step.dt; var Cdot = wB - wA; var impulse = -this.m_angularMass * Cdot; var oldImpulse = this.m_angularImpulse; var maxImpulse = h * this.m_maxTorque; this.m_angularImpulse = b2Clamp(this.m_angularImpulse + impulse, -maxImpulse, maxImpulse); impulse = this.m_angularImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; var Cdot_v2 = b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB, wB, this.m_rB, b2Vec2.s_t0), b2Vec2.AddVCrossSV(vA, wA, this.m_rA, b2Vec2.s_t1), b2FrictionJoint.SolveVelocityConstraints_s_Cdot_v2); var impulseV = b2Mat22.MulMV(this.m_linearMass, Cdot_v2, b2FrictionJoint.SolveVelocityConstraints_s_impulseV).SelfNeg(); var oldImpulseV = b2FrictionJoint.SolveVelocityConstraints_s_oldImpulseV.Copy(this.m_linearImpulse); this.m_linearImpulse.SelfAdd(impulseV); var maxImpulse = h * this.m_maxForce; if (this.m_linearImpulse.LengthSquared() > maxImpulse * maxImpulse) { this.m_linearImpulse.Normalize(); this.m_linearImpulse.SelfMul(maxImpulse); } b2Vec2.SubVV(this.m_linearImpulse, oldImpulseV, impulseV); vA.SelfMulSub(mA, impulseV); wA -= iA * b2Vec2.CrossVV(this.m_rA, impulseV); vB.SelfMulAdd(mB, impulseV); wB += iB * b2Vec2.CrossVV(this.m_rB, impulseV); data.velocities[this.m_indexA].w = wA; data.velocities[this.m_indexB].w = wB; }; b2FrictionJoint.prototype.SolvePositionConstraints = function(data) { return true; }; b2FrictionJoint.prototype.GetAnchorA = function(out) { return this.m_bodyA.GetWorldPoint(this.m_localAnchorA, out); }; b2FrictionJoint.prototype.GetAnchorB = function(out) { return this.m_bodyB.GetWorldPoint(this.m_localAnchorB, out); }; b2FrictionJoint.prototype.GetReactionForce = function(inv_dt, out) { out.x = inv_dt * this.m_linearImpulse.x; out.y = inv_dt * this.m_linearImpulse.y; return out; }; b2FrictionJoint.prototype.GetReactionTorque = function(inv_dt) { return inv_dt * this.m_angularImpulse; }; b2FrictionJoint.prototype.GetLocalAnchorA = function() { return this.m_localAnchorA; }; b2FrictionJoint.prototype.GetLocalAnchorB = function() { return this.m_localAnchorB; }; b2FrictionJoint.prototype.SetMaxForce = function(force) { this.m_maxForce = force; }; b2FrictionJoint.prototype.GetMaxForce = function() { return this.m_maxForce; }; b2FrictionJoint.prototype.SetMaxTorque = function(torque) { this.m_maxTorque = torque; }; b2FrictionJoint.prototype.GetMaxTorque = function() { return this.m_maxTorque; }; b2FrictionJoint.prototype.Dump = function(log) { var indexA = this.m_bodyA.m_islandIndex; var indexB = this.m_bodyB.m_islandIndex; log(" const jd: b2FrictionJointDef = new b2FrictionJointDef();\n"); log(" jd.bodyA = bodies[%d];\n", indexA); log(" jd.bodyB = bodies[%d];\n", indexB); log(" jd.collideConnected = %s;\n", this.m_collideConnected ? "true" : "false"); log(" jd.localAnchorA.Set(%.15f, %.15f);\n", this.m_localAnchorA.x, this.m_localAnchorA.y); log(" jd.localAnchorB.Set(%.15f, %.15f);\n", this.m_localAnchorB.x, this.m_localAnchorB.y); log(" jd.maxForce = %.15f;\n", this.m_maxForce); log(" jd.maxTorque = %.15f;\n", this.m_maxTorque); log(" joints[%d] = this.m_world.CreateJoint(jd);\n", this.m_index); }; b2FrictionJoint.SolveVelocityConstraints_s_Cdot_v2 = new b2Vec2(); b2FrictionJoint.SolveVelocityConstraints_s_impulseV = new b2Vec2(); b2FrictionJoint.SolveVelocityConstraints_s_oldImpulseV = new b2Vec2(); return b2FrictionJoint; })(b2Joint); var b2GearJointDef = (function(_super) { __extends(b2GearJointDef, _super); function b2GearJointDef() { var _this = _super.call(this, exports.b2JointType.e_gearJoint) || this; _this.ratio = 1; return _this; } return b2GearJointDef; })(b2JointDef); var b2GearJoint = (function(_super) { __extends(b2GearJoint, _super); function b2GearJoint(def) { var _this = _super.call(this, def) || this; _this.m_typeA = exports.b2JointType.e_unknownJoint; _this.m_typeB = exports.b2JointType.e_unknownJoint; _this.m_localAnchorA = new b2Vec2(); _this.m_localAnchorB = new b2Vec2(); _this.m_localAnchorC = new b2Vec2(); _this.m_localAnchorD = new b2Vec2(); _this.m_localAxisC = new b2Vec2(); _this.m_localAxisD = new b2Vec2(); _this.m_referenceAngleA = 0; _this.m_referenceAngleB = 0; _this.m_constant = 0; _this.m_ratio = 0; _this.m_impulse = 0; _this.m_indexA = 0; _this.m_indexB = 0; _this.m_indexC = 0; _this.m_indexD = 0; _this.m_lcA = new b2Vec2(); _this.m_lcB = new b2Vec2(); _this.m_lcC = new b2Vec2(); _this.m_lcD = new b2Vec2(); _this.m_mA = 0; _this.m_mB = 0; _this.m_mC = 0; _this.m_mD = 0; _this.m_iA = 0; _this.m_iB = 0; _this.m_iC = 0; _this.m_iD = 0; _this.m_JvAC = new b2Vec2(); _this.m_JvBD = new b2Vec2(); _this.m_JwA = 0; _this.m_JwB = 0; _this.m_JwC = 0; _this.m_JwD = 0; _this.m_mass = 0; _this.m_qA = new b2Rot(); _this.m_qB = new b2Rot(); _this.m_qC = new b2Rot(); _this.m_qD = new b2Rot(); _this.m_lalcA = new b2Vec2(); _this.m_lalcB = new b2Vec2(); _this.m_lalcC = new b2Vec2(); _this.m_lalcD = new b2Vec2(); _this.m_joint1 = def.joint1; _this.m_joint2 = def.joint2; _this.m_typeA = _this.m_joint1.GetType(); _this.m_typeB = _this.m_joint2.GetType(); var coordinateA, coordinateB; _this.m_bodyC = _this.m_joint1.GetBodyA(); _this.m_bodyA = _this.m_joint1.GetBodyB(); var xfA = _this.m_bodyA.m_xf; var aA = _this.m_bodyA.m_sweep.a; var xfC = _this.m_bodyC.m_xf; var aC = _this.m_bodyC.m_sweep.a; if (_this.m_typeA === exports.b2JointType.e_revoluteJoint) { var revolute = def.joint1; _this.m_localAnchorC.Copy(revolute.m_localAnchorA); _this.m_localAnchorA.Copy(revolute.m_localAnchorB); _this.m_referenceAngleA = revolute.m_referenceAngle; _this.m_localAxisC.SetZero(); coordinateA = aA - aC - _this.m_referenceAngleA; } else { var prismatic = def.joint1; _this.m_localAnchorC.Copy(prismatic.m_localAnchorA); _this.m_localAnchorA.Copy(prismatic.m_localAnchorB); _this.m_referenceAngleA = prismatic.m_referenceAngle; _this.m_localAxisC.Copy(prismatic.m_localXAxisA); var pC = _this.m_localAnchorC; var pA = b2Rot.MulTRV(xfC.q, b2Vec2.AddVV(b2Rot.MulRV(xfA.q, _this.m_localAnchorA, b2Vec2.s_t0), b2Vec2.SubVV(xfA.p, xfC.p, b2Vec2.s_t1), b2Vec2.s_t0), b2Vec2.s_t0); coordinateA = b2Vec2.DotVV(b2Vec2.SubVV(pA, pC, b2Vec2.s_t0), _this.m_localAxisC); } _this.m_bodyD = _this.m_joint2.GetBodyA(); _this.m_bodyB = _this.m_joint2.GetBodyB(); var xfB = _this.m_bodyB.m_xf; var aB = _this.m_bodyB.m_sweep.a; var xfD = _this.m_bodyD.m_xf; var aD = _this.m_bodyD.m_sweep.a; if (_this.m_typeB === exports.b2JointType.e_revoluteJoint) { var revolute = def.joint2; _this.m_localAnchorD.Copy(revolute.m_localAnchorA); _this.m_localAnchorB.Copy(revolute.m_localAnchorB); _this.m_referenceAngleB = revolute.m_referenceAngle; _this.m_localAxisD.SetZero(); coordinateB = aB - aD - _this.m_referenceAngleB; } else { var prismatic = def.joint2; _this.m_localAnchorD.Copy(prismatic.m_localAnchorA); _this.m_localAnchorB.Copy(prismatic.m_localAnchorB); _this.m_referenceAngleB = prismatic.m_referenceAngle; _this.m_localAxisD.Copy(prismatic.m_localXAxisA); var pD = _this.m_localAnchorD; var pB = b2Rot.MulTRV(xfD.q, b2Vec2.AddVV(b2Rot.MulRV(xfB.q, _this.m_localAnchorB, b2Vec2.s_t0), b2Vec2.SubVV(xfB.p, xfD.p, b2Vec2.s_t1), b2Vec2.s_t0), b2Vec2.s_t0); coordinateB = b2Vec2.DotVV(b2Vec2.SubVV(pB, pD, b2Vec2.s_t0), _this.m_localAxisD); } _this.m_ratio = b2Maybe(def.ratio, 1); _this.m_constant = coordinateA + _this.m_ratio * coordinateB; _this.m_impulse = 0; return _this; } b2GearJoint.prototype.InitVelocityConstraints = function(data) { this.m_indexA = this.m_bodyA.m_islandIndex; this.m_indexB = this.m_bodyB.m_islandIndex; this.m_indexC = this.m_bodyC.m_islandIndex; this.m_indexD = this.m_bodyD.m_islandIndex; this.m_lcA.Copy(this.m_bodyA.m_sweep.localCenter); this.m_lcB.Copy(this.m_bodyB.m_sweep.localCenter); this.m_lcC.Copy(this.m_bodyC.m_sweep.localCenter); this.m_lcD.Copy(this.m_bodyD.m_sweep.localCenter); this.m_mA = this.m_bodyA.m_invMass; this.m_mB = this.m_bodyB.m_invMass; this.m_mC = this.m_bodyC.m_invMass; this.m_mD = this.m_bodyD.m_invMass; this.m_iA = this.m_bodyA.m_invI; this.m_iB = this.m_bodyB.m_invI; this.m_iC = this.m_bodyC.m_invI; this.m_iD = this.m_bodyD.m_invI; var aA = data.positions[this.m_indexA].a; var vA = data.velocities[this.m_indexA].v; var wA = data.velocities[this.m_indexA].w; var aB = data.positions[this.m_indexB].a; var vB = data.velocities[this.m_indexB].v; var wB = data.velocities[this.m_indexB].w; var aC = data.positions[this.m_indexC].a; var vC = data.velocities[this.m_indexC].v; var wC = data.velocities[this.m_indexC].w; var aD = data.positions[this.m_indexD].a; var vD = data.velocities[this.m_indexD].v; var wD = data.velocities[this.m_indexD].w; var qA = this.m_qA.SetAngle(aA), qB = this.m_qB.SetAngle(aB), qC = this.m_qC.SetAngle(aC), qD = this.m_qD.SetAngle(aD); this.m_mass = 0; if (this.m_typeA === exports.b2JointType.e_revoluteJoint) { this.m_JvAC.SetZero(); this.m_JwA = 1; this.m_JwC = 1; this.m_mass += this.m_iA + this.m_iC; } else { var u = b2Rot.MulRV(qC, this.m_localAxisC, b2GearJoint.InitVelocityConstraints_s_u); b2Vec2.SubVV(this.m_localAnchorC, this.m_lcC, this.m_lalcC); var rC = b2Rot.MulRV(qC, this.m_lalcC, b2GearJoint.InitVelocityConstraints_s_rC); b2Vec2.SubVV(this.m_localAnchorA, this.m_lcA, this.m_lalcA); var rA = b2Rot.MulRV(qA, this.m_lalcA, b2GearJoint.InitVelocityConstraints_s_rA); this.m_JvAC.Copy(u); this.m_JwC = b2Vec2.CrossVV(rC, u); this.m_JwA = b2Vec2.CrossVV(rA, u); this.m_mass += this.m_mC + this.m_mA + this.m_iC * this.m_JwC * this.m_JwC + this.m_iA * this.m_JwA * this.m_JwA; } if (this.m_typeB === exports.b2JointType.e_revoluteJoint) { this.m_JvBD.SetZero(); this.m_JwB = this.m_ratio; this.m_JwD = this.m_ratio; this.m_mass += this.m_ratio * this.m_ratio * (this.m_iB + this.m_iD); } else { var u = b2Rot.MulRV(qD, this.m_localAxisD, b2GearJoint.InitVelocityConstraints_s_u); b2Vec2.SubVV(this.m_localAnchorD, this.m_lcD, this.m_lalcD); var rD = b2Rot.MulRV(qD, this.m_lalcD, b2GearJoint.InitVelocityConstraints_s_rD); b2Vec2.SubVV(this.m_localAnchorB, this.m_lcB, this.m_lalcB); var rB = b2Rot.MulRV(qB, this.m_lalcB, b2GearJoint.InitVelocityConstraints_s_rB); b2Vec2.MulSV(this.m_ratio, u, this.m_JvBD); this.m_JwD = this.m_ratio * b2Vec2.CrossVV(rD, u); this.m_JwB = this.m_ratio * b2Vec2.CrossVV(rB, u); this.m_mass += this.m_ratio * this.m_ratio * (this.m_mD + this.m_mB) + this.m_iD * this.m_JwD * this.m_JwD + this.m_iB * this.m_JwB * this.m_JwB; } this.m_mass = this.m_mass > 0 ? 1 / this.m_mass : 0; if (data.step.warmStarting) { vA.SelfMulAdd(this.m_mA * this.m_impulse, this.m_JvAC); wA += this.m_iA * this.m_impulse * this.m_JwA; vB.SelfMulAdd(this.m_mB * this.m_impulse, this.m_JvBD); wB += this.m_iB * this.m_impulse * this.m_JwB; vC.SelfMulSub(this.m_mC * this.m_impulse, this.m_JvAC); wC -= this.m_iC * this.m_impulse * this.m_JwC; vD.SelfMulSub(this.m_mD * this.m_impulse, this.m_JvBD); wD -= this.m_iD * this.m_impulse * this.m_JwD; } else this.m_impulse = 0; data.velocities[this.m_indexA].w = wA; data.velocities[this.m_indexB].w = wB; data.velocities[this.m_indexC].w = wC; data.velocities[this.m_indexD].w = wD; }; b2GearJoint.prototype.SolveVelocityConstraints = function(data) { var vA = data.velocities[this.m_indexA].v; var wA = data.velocities[this.m_indexA].w; var vB = data.velocities[this.m_indexB].v; var wB = data.velocities[this.m_indexB].w; var vC = data.velocities[this.m_indexC].v; var wC = data.velocities[this.m_indexC].w; var vD = data.velocities[this.m_indexD].v; var wD = data.velocities[this.m_indexD].w; var Cdot = b2Vec2.DotVV(this.m_JvAC, b2Vec2.SubVV(vA, vC, b2Vec2.s_t0)) + b2Vec2.DotVV(this.m_JvBD, b2Vec2.SubVV(vB, vD, b2Vec2.s_t0)); Cdot += this.m_JwA * wA - this.m_JwC * wC + (this.m_JwB * wB - this.m_JwD * wD); var impulse = -this.m_mass * Cdot; this.m_impulse += impulse; vA.SelfMulAdd(this.m_mA * impulse, this.m_JvAC); wA += this.m_iA * impulse * this.m_JwA; vB.SelfMulAdd(this.m_mB * impulse, this.m_JvBD); wB += this.m_iB * impulse * this.m_JwB; vC.SelfMulSub(this.m_mC * impulse, this.m_JvAC); wC -= this.m_iC * impulse * this.m_JwC; vD.SelfMulSub(this.m_mD * impulse, this.m_JvBD); wD -= this.m_iD * impulse * this.m_JwD; data.velocities[this.m_indexA].w = wA; data.velocities[this.m_indexB].w = wB; data.velocities[this.m_indexC].w = wC; data.velocities[this.m_indexD].w = wD; }; b2GearJoint.prototype.SolvePositionConstraints = function(data) { var cA = data.positions[this.m_indexA].c; var aA = data.positions[this.m_indexA].a; var cB = data.positions[this.m_indexB].c; var aB = data.positions[this.m_indexB].a; var cC = data.positions[this.m_indexC].c; var aC = data.positions[this.m_indexC].a; var cD = data.positions[this.m_indexD].c; var aD = data.positions[this.m_indexD].a; var qA = this.m_qA.SetAngle(aA), qB = this.m_qB.SetAngle(aB), qC = this.m_qC.SetAngle(aC), qD = this.m_qD.SetAngle(aD); var linearError = 0; var coordinateA, coordinateB; var JvAC = this.m_JvAC, JvBD = this.m_JvBD; var JwA, JwB, JwC, JwD; var mass = 0; if (this.m_typeA === exports.b2JointType.e_revoluteJoint) { JvAC.SetZero(); JwA = 1; JwC = 1; mass += this.m_iA + this.m_iC; coordinateA = aA - aC - this.m_referenceAngleA; } else { var u = b2Rot.MulRV(qC, this.m_localAxisC, b2GearJoint.SolvePositionConstraints_s_u); var rC = b2Rot.MulRV(qC, this.m_lalcC, b2GearJoint.SolvePositionConstraints_s_rC); var rA = b2Rot.MulRV(qA, this.m_lalcA, b2GearJoint.SolvePositionConstraints_s_rA); JvAC.Copy(u); JwC = b2Vec2.CrossVV(rC, u); JwA = b2Vec2.CrossVV(rA, u); mass += this.m_mC + this.m_mA + this.m_iC * JwC * JwC + this.m_iA * JwA * JwA; var pC = this.m_lalcC; var pA = b2Rot.MulTRV(qC, b2Vec2.AddVV(rA, b2Vec2.SubVV(cA, cC, b2Vec2.s_t0), b2Vec2.s_t0), b2Vec2.s_t0); coordinateA = b2Vec2.DotVV(b2Vec2.SubVV(pA, pC, b2Vec2.s_t0), this.m_localAxisC); } if (this.m_typeB === exports.b2JointType.e_revoluteJoint) { JvBD.SetZero(); JwB = this.m_ratio; JwD = this.m_ratio; mass += this.m_ratio * this.m_ratio * (this.m_iB + this.m_iD); coordinateB = aB - aD - this.m_referenceAngleB; } else { var u = b2Rot.MulRV(qD, this.m_localAxisD, b2GearJoint.SolvePositionConstraints_s_u); var rD = b2Rot.MulRV(qD, this.m_lalcD, b2GearJoint.SolvePositionConstraints_s_rD); var rB = b2Rot.MulRV(qB, this.m_lalcB, b2GearJoint.SolvePositionConstraints_s_rB); b2Vec2.MulSV(this.m_ratio, u, JvBD); JwD = this.m_ratio * b2Vec2.CrossVV(rD, u); JwB = this.m_ratio * b2Vec2.CrossVV(rB, u); mass += this.m_ratio * this.m_ratio * (this.m_mD + this.m_mB) + this.m_iD * JwD * JwD + this.m_iB * JwB * JwB; var pD = this.m_lalcD; var pB = b2Rot.MulTRV(qD, b2Vec2.AddVV(rB, b2Vec2.SubVV(cB, cD, b2Vec2.s_t0), b2Vec2.s_t0), b2Vec2.s_t0); coordinateB = b2Vec2.DotVV(b2Vec2.SubVV(pB, pD, b2Vec2.s_t0), this.m_localAxisD); } var C = coordinateA + this.m_ratio * coordinateB - this.m_constant; var impulse = 0; mass > 0 && (impulse = -C / mass); cA.SelfMulAdd(this.m_mA * impulse, JvAC); aA += this.m_iA * impulse * JwA; cB.SelfMulAdd(this.m_mB * impulse, JvBD); aB += this.m_iB * impulse * JwB; cC.SelfMulSub(this.m_mC * impulse, JvAC); aC -= this.m_iC * impulse * JwC; cD.SelfMulSub(this.m_mD * impulse, JvBD); aD -= this.m_iD * impulse * JwD; data.positions[this.m_indexA].a = aA; data.positions[this.m_indexB].a = aB; data.positions[this.m_indexC].a = aC; data.positions[this.m_indexD].a = aD; return linearError < b2_linearSlop; }; b2GearJoint.prototype.GetAnchorA = function(out) { return this.m_bodyA.GetWorldPoint(this.m_localAnchorA, out); }; b2GearJoint.prototype.GetAnchorB = function(out) { return this.m_bodyB.GetWorldPoint(this.m_localAnchorB, out); }; b2GearJoint.prototype.GetReactionForce = function(inv_dt, out) { return b2Vec2.MulSV(inv_dt * this.m_impulse, this.m_JvAC, out); }; b2GearJoint.prototype.GetReactionTorque = function(inv_dt) { return inv_dt * this.m_impulse * this.m_JwA; }; b2GearJoint.prototype.GetJoint1 = function() { return this.m_joint1; }; b2GearJoint.prototype.GetJoint2 = function() { return this.m_joint2; }; b2GearJoint.prototype.GetRatio = function() { return this.m_ratio; }; b2GearJoint.prototype.SetRatio = function(ratio) { this.m_ratio = ratio; }; b2GearJoint.prototype.Dump = function(log) { var indexA = this.m_bodyA.m_islandIndex; var indexB = this.m_bodyB.m_islandIndex; var index1 = this.m_joint1.m_index; var index2 = this.m_joint2.m_index; log(" const jd: b2GearJointDef = new b2GearJointDef();\n"); log(" jd.bodyA = bodies[%d];\n", indexA); log(" jd.bodyB = bodies[%d];\n", indexB); log(" jd.collideConnected = %s;\n", this.m_collideConnected ? "true" : "false"); log(" jd.joint1 = joints[%d];\n", index1); log(" jd.joint2 = joints[%d];\n", index2); log(" jd.ratio = %.15f;\n", this.m_ratio); log(" joints[%d] = this.m_world.CreateJoint(jd);\n", this.m_index); }; b2GearJoint.InitVelocityConstraints_s_u = new b2Vec2(); b2GearJoint.InitVelocityConstraints_s_rA = new b2Vec2(); b2GearJoint.InitVelocityConstraints_s_rB = new b2Vec2(); b2GearJoint.InitVelocityConstraints_s_rC = new b2Vec2(); b2GearJoint.InitVelocityConstraints_s_rD = new b2Vec2(); b2GearJoint.SolvePositionConstraints_s_u = new b2Vec2(); b2GearJoint.SolvePositionConstraints_s_rA = new b2Vec2(); b2GearJoint.SolvePositionConstraints_s_rB = new b2Vec2(); b2GearJoint.SolvePositionConstraints_s_rC = new b2Vec2(); b2GearJoint.SolvePositionConstraints_s_rD = new b2Vec2(); return b2GearJoint; })(b2Joint); var b2MotorJointDef = (function(_super) { __extends(b2MotorJointDef, _super); function b2MotorJointDef() { var _this = _super.call(this, exports.b2JointType.e_motorJoint) || this; _this.linearOffset = new b2Vec2(0, 0); _this.angularOffset = 0; _this.maxForce = 1; _this.maxTorque = 1; _this.correctionFactor = .3; return _this; } b2MotorJointDef.prototype.Initialize = function(bA, bB) { this.bodyA = bA; this.bodyB = bB; this.bodyA.GetLocalPoint(this.bodyB.GetPosition(), this.linearOffset); var angleA = this.bodyA.GetAngle(); var angleB = this.bodyB.GetAngle(); this.angularOffset = angleB - angleA; }; return b2MotorJointDef; })(b2JointDef); var b2MotorJoint = (function(_super) { __extends(b2MotorJoint, _super); function b2MotorJoint(def) { var _this = _super.call(this, def) || this; _this.m_linearOffset = new b2Vec2(); _this.m_angularOffset = 0; _this.m_linearImpulse = new b2Vec2(); _this.m_angularImpulse = 0; _this.m_maxForce = 0; _this.m_maxTorque = 0; _this.m_correctionFactor = .3; _this.m_indexA = 0; _this.m_indexB = 0; _this.m_rA = new b2Vec2(); _this.m_rB = new b2Vec2(); _this.m_localCenterA = new b2Vec2(); _this.m_localCenterB = new b2Vec2(); _this.m_linearError = new b2Vec2(); _this.m_angularError = 0; _this.m_invMassA = 0; _this.m_invMassB = 0; _this.m_invIA = 0; _this.m_invIB = 0; _this.m_linearMass = new b2Mat22(); _this.m_angularMass = 0; _this.m_qA = new b2Rot(); _this.m_qB = new b2Rot(); _this.m_K = new b2Mat22(); _this.m_linearOffset.Copy(b2Maybe(def.linearOffset, b2Vec2.ZERO)); _this.m_linearImpulse.SetZero(); _this.m_maxForce = b2Maybe(def.maxForce, 0); _this.m_maxTorque = b2Maybe(def.maxTorque, 0); _this.m_correctionFactor = b2Maybe(def.correctionFactor, .3); return _this; } b2MotorJoint.prototype.GetAnchorA = function(out) { var pos = this.m_bodyA.GetPosition(); out.x = pos.x; out.y = pos.y; return out; }; b2MotorJoint.prototype.GetAnchorB = function(out) { var pos = this.m_bodyB.GetPosition(); out.x = pos.x; out.y = pos.y; return out; }; b2MotorJoint.prototype.GetReactionForce = function(inv_dt, out) { return b2Vec2.MulSV(inv_dt, this.m_linearImpulse, out); }; b2MotorJoint.prototype.GetReactionTorque = function(inv_dt) { return inv_dt * this.m_angularImpulse; }; b2MotorJoint.prototype.SetLinearOffset = function(linearOffset) { if (!b2Vec2.IsEqualToV(linearOffset, this.m_linearOffset)) { this.m_bodyA.SetAwake(true); this.m_bodyB.SetAwake(true); this.m_linearOffset.Copy(linearOffset); } }; b2MotorJoint.prototype.GetLinearOffset = function() { return this.m_linearOffset; }; b2MotorJoint.prototype.SetAngularOffset = function(angularOffset) { if (angularOffset !== this.m_angularOffset) { this.m_bodyA.SetAwake(true); this.m_bodyB.SetAwake(true); this.m_angularOffset = angularOffset; } }; b2MotorJoint.prototype.GetAngularOffset = function() { return this.m_angularOffset; }; b2MotorJoint.prototype.SetMaxForce = function(force) { this.m_maxForce = force; }; b2MotorJoint.prototype.GetMaxForce = function() { return this.m_maxForce; }; b2MotorJoint.prototype.SetMaxTorque = function(torque) { this.m_maxTorque = torque; }; b2MotorJoint.prototype.GetMaxTorque = function() { return this.m_maxTorque; }; b2MotorJoint.prototype.InitVelocityConstraints = function(data) { this.m_indexA = this.m_bodyA.m_islandIndex; this.m_indexB = this.m_bodyB.m_islandIndex; this.m_localCenterA.Copy(this.m_bodyA.m_sweep.localCenter); this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter); this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var cA = data.positions[this.m_indexA].c; var aA = data.positions[this.m_indexA].a; var vA = data.velocities[this.m_indexA].v; var wA = data.velocities[this.m_indexA].w; var cB = data.positions[this.m_indexB].c; var aB = data.positions[this.m_indexB].a; var vB = data.velocities[this.m_indexB].v; var wB = data.velocities[this.m_indexB].w; var qA = this.m_qA.SetAngle(aA), qB = this.m_qB.SetAngle(aB); var rA = b2Rot.MulRV(qA, b2Vec2.SubVV(this.m_linearOffset, this.m_localCenterA, b2Vec2.s_t0), this.m_rA); var rB = b2Rot.MulRV(qB, b2Vec2.NegV(this.m_localCenterB, b2Vec2.s_t0), this.m_rB); var mA = this.m_invMassA, mB = this.m_invMassB; var iA = this.m_invIA, iB = this.m_invIB; var K = this.m_K; K.ex.x = mA + mB + iA * rA.y * rA.y + iB * rB.y * rB.y; K.ex.y = -iA * rA.x * rA.y - iB * rB.x * rB.y; K.ey.x = K.ex.y; K.ey.y = mA + mB + iA * rA.x * rA.x + iB * rB.x * rB.x; K.GetInverse(this.m_linearMass); this.m_angularMass = iA + iB; this.m_angularMass > 0 && (this.m_angularMass = 1 / this.m_angularMass); b2Vec2.SubVV(b2Vec2.AddVV(cB, rB, b2Vec2.s_t0), b2Vec2.AddVV(cA, rA, b2Vec2.s_t1), this.m_linearError); this.m_angularError = aB - aA - this.m_angularOffset; if (data.step.warmStarting) { this.m_linearImpulse.SelfMul(data.step.dtRatio); this.m_angularImpulse *= data.step.dtRatio; var P = this.m_linearImpulse; vA.SelfMulSub(mA, P); wA -= iA * (b2Vec2.CrossVV(rA, P) + this.m_angularImpulse); vB.SelfMulAdd(mB, P); wB += iB * (b2Vec2.CrossVV(rB, P) + this.m_angularImpulse); } else { this.m_linearImpulse.SetZero(); this.m_angularImpulse = 0; } data.velocities[this.m_indexA].w = wA; data.velocities[this.m_indexB].w = wB; }; b2MotorJoint.prototype.SolveVelocityConstraints = function(data) { var vA = data.velocities[this.m_indexA].v; var wA = data.velocities[this.m_indexA].w; var vB = data.velocities[this.m_indexB].v; var wB = data.velocities[this.m_indexB].w; var mA = this.m_invMassA, mB = this.m_invMassB; var iA = this.m_invIA, iB = this.m_invIB; var h = data.step.dt; var inv_h = data.step.inv_dt; var Cdot = wB - wA + inv_h * this.m_correctionFactor * this.m_angularError; var impulse = -this.m_angularMass * Cdot; var oldImpulse = this.m_angularImpulse; var maxImpulse = h * this.m_maxTorque; this.m_angularImpulse = b2Clamp(this.m_angularImpulse + impulse, -maxImpulse, maxImpulse); impulse = this.m_angularImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; var rA = this.m_rA; var rB = this.m_rB; var Cdot_v2 = b2Vec2.AddVV(b2Vec2.SubVV(b2Vec2.AddVV(vB, b2Vec2.CrossSV(wB, rB, b2Vec2.s_t0), b2Vec2.s_t0), b2Vec2.AddVV(vA, b2Vec2.CrossSV(wA, rA, b2Vec2.s_t1), b2Vec2.s_t1), b2Vec2.s_t2), b2Vec2.MulSV(inv_h * this.m_correctionFactor, this.m_linearError, b2Vec2.s_t3), b2MotorJoint.SolveVelocityConstraints_s_Cdot_v2); var impulse_v2 = b2Mat22.MulMV(this.m_linearMass, Cdot_v2, b2MotorJoint.SolveVelocityConstraints_s_impulse_v2).SelfNeg(); var oldImpulse_v2 = b2MotorJoint.SolveVelocityConstraints_s_oldImpulse_v2.Copy(this.m_linearImpulse); this.m_linearImpulse.SelfAdd(impulse_v2); var maxImpulse = h * this.m_maxForce; if (this.m_linearImpulse.LengthSquared() > maxImpulse * maxImpulse) { this.m_linearImpulse.Normalize(); this.m_linearImpulse.SelfMul(maxImpulse); } b2Vec2.SubVV(this.m_linearImpulse, oldImpulse_v2, impulse_v2); vA.SelfMulSub(mA, impulse_v2); wA -= iA * b2Vec2.CrossVV(rA, impulse_v2); vB.SelfMulAdd(mB, impulse_v2); wB += iB * b2Vec2.CrossVV(rB, impulse_v2); data.velocities[this.m_indexA].w = wA; data.velocities[this.m_indexB].w = wB; }; b2MotorJoint.prototype.SolvePositionConstraints = function(data) { return true; }; b2MotorJoint.prototype.Dump = function(log) { var indexA = this.m_bodyA.m_islandIndex; var indexB = this.m_bodyB.m_islandIndex; log(" const jd: b2MotorJointDef = new b2MotorJointDef();\n"); log(" jd.bodyA = bodies[%d];\n", indexA); log(" jd.bodyB = bodies[%d];\n", indexB); log(" jd.collideConnected = %s;\n", this.m_collideConnected ? "true" : "false"); log(" jd.linearOffset.Set(%.15f, %.15f);\n", this.m_linearOffset.x, this.m_linearOffset.y); log(" jd.angularOffset = %.15f;\n", this.m_angularOffset); log(" jd.maxForce = %.15f;\n", this.m_maxForce); log(" jd.maxTorque = %.15f;\n", this.m_maxTorque); log(" jd.correctionFactor = %.15f;\n", this.m_correctionFactor); log(" joints[%d] = this.m_world.CreateJoint(jd);\n", this.m_index); }; b2MotorJoint.SolveVelocityConstraints_s_Cdot_v2 = new b2Vec2(); b2MotorJoint.SolveVelocityConstraints_s_impulse_v2 = new b2Vec2(); b2MotorJoint.SolveVelocityConstraints_s_oldImpulse_v2 = new b2Vec2(); return b2MotorJoint; })(b2Joint); var b2MouseJointDef = (function(_super) { __extends(b2MouseJointDef, _super); function b2MouseJointDef() { var _this = _super.call(this, exports.b2JointType.e_mouseJoint) || this; _this.target = new b2Vec2(); _this.maxForce = 0; _this.frequencyHz = 5; _this.dampingRatio = .7; return _this; } return b2MouseJointDef; })(b2JointDef); var b2MouseJoint = (function(_super) { __extends(b2MouseJoint, _super); function b2MouseJoint(def) { var _this = _super.call(this, def) || this; _this.m_localAnchorB = new b2Vec2(); _this.m_targetA = new b2Vec2(); _this.m_frequencyHz = 0; _this.m_dampingRatio = 0; _this.m_beta = 0; _this.m_impulse = new b2Vec2(); _this.m_maxForce = 0; _this.m_gamma = 0; _this.m_indexA = 0; _this.m_indexB = 0; _this.m_rB = new b2Vec2(); _this.m_localCenterB = new b2Vec2(); _this.m_invMassB = 0; _this.m_invIB = 0; _this.m_mass = new b2Mat22(); _this.m_C = new b2Vec2(); _this.m_qB = new b2Rot(); _this.m_lalcB = new b2Vec2(); _this.m_K = new b2Mat22(); _this.m_targetA.Copy(b2Maybe(def.target, b2Vec2.ZERO)); b2Transform.MulTXV(_this.m_bodyB.GetTransform(), _this.m_targetA, _this.m_localAnchorB); _this.m_maxForce = b2Maybe(def.maxForce, 0); _this.m_impulse.SetZero(); _this.m_frequencyHz = b2Maybe(def.frequencyHz, 0); _this.m_dampingRatio = b2Maybe(def.dampingRatio, 0); _this.m_beta = 0; _this.m_gamma = 0; return _this; } b2MouseJoint.prototype.SetTarget = function(target) { this.m_bodyB.IsAwake() || this.m_bodyB.SetAwake(true); this.m_targetA.Copy(target); }; b2MouseJoint.prototype.GetTarget = function() { return this.m_targetA; }; b2MouseJoint.prototype.SetMaxForce = function(maxForce) { this.m_maxForce = maxForce; }; b2MouseJoint.prototype.GetMaxForce = function() { return this.m_maxForce; }; b2MouseJoint.prototype.SetFrequency = function(hz) { this.m_frequencyHz = hz; }; b2MouseJoint.prototype.GetFrequency = function() { return this.m_frequencyHz; }; b2MouseJoint.prototype.SetDampingRatio = function(ratio) { this.m_dampingRatio = ratio; }; b2MouseJoint.prototype.GetDampingRatio = function() { return this.m_dampingRatio; }; b2MouseJoint.prototype.InitVelocityConstraints = function(data) { this.m_indexB = this.m_bodyB.m_islandIndex; this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter); this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIB = this.m_bodyB.m_invI; var cB = data.positions[this.m_indexB].c; var aB = data.positions[this.m_indexB].a; var vB = data.velocities[this.m_indexB].v; var wB = data.velocities[this.m_indexB].w; var qB = this.m_qB.SetAngle(aB); var mass = this.m_bodyB.GetMass(); var omega = 2 * b2_pi * this.m_frequencyHz; var d = 2 * mass * this.m_dampingRatio * omega; var k = mass * (omega * omega); var h = data.step.dt; this.m_gamma = h * (d + h * k); 0 !== this.m_gamma && (this.m_gamma = 1 / this.m_gamma); this.m_beta = h * k * this.m_gamma; b2Vec2.SubVV(this.m_localAnchorB, this.m_localCenterB, this.m_lalcB); b2Rot.MulRV(qB, this.m_lalcB, this.m_rB); var K = this.m_K; K.ex.x = this.m_invMassB + this.m_invIB * this.m_rB.y * this.m_rB.y + this.m_gamma; K.ex.y = -this.m_invIB * this.m_rB.x * this.m_rB.y; K.ey.x = K.ex.y; K.ey.y = this.m_invMassB + this.m_invIB * this.m_rB.x * this.m_rB.x + this.m_gamma; K.GetInverse(this.m_mass); this.m_C.x = cB.x + this.m_rB.x - this.m_targetA.x; this.m_C.y = cB.y + this.m_rB.y - this.m_targetA.y; this.m_C.SelfMul(this.m_beta); wB *= .98; if (data.step.warmStarting) { this.m_impulse.SelfMul(data.step.dtRatio); vB.x += this.m_invMassB * this.m_impulse.x; vB.y += this.m_invMassB * this.m_impulse.y; wB += this.m_invIB * b2Vec2.CrossVV(this.m_rB, this.m_impulse); } else this.m_impulse.SetZero(); data.velocities[this.m_indexB].w = wB; }; b2MouseJoint.prototype.SolveVelocityConstraints = function(data) { var vB = data.velocities[this.m_indexB].v; var wB = data.velocities[this.m_indexB].w; var Cdot = b2Vec2.AddVCrossSV(vB, wB, this.m_rB, b2MouseJoint.SolveVelocityConstraints_s_Cdot); var impulse = b2Mat22.MulMV(this.m_mass, b2Vec2.AddVV(Cdot, b2Vec2.AddVV(this.m_C, b2Vec2.MulSV(this.m_gamma, this.m_impulse, b2Vec2.s_t0), b2Vec2.s_t0), b2Vec2.s_t0).SelfNeg(), b2MouseJoint.SolveVelocityConstraints_s_impulse); var oldImpulse = b2MouseJoint.SolveVelocityConstraints_s_oldImpulse.Copy(this.m_impulse); this.m_impulse.SelfAdd(impulse); var maxImpulse = data.step.dt * this.m_maxForce; this.m_impulse.LengthSquared() > maxImpulse * maxImpulse && this.m_impulse.SelfMul(maxImpulse / this.m_impulse.Length()); b2Vec2.SubVV(this.m_impulse, oldImpulse, impulse); vB.SelfMulAdd(this.m_invMassB, impulse); wB += this.m_invIB * b2Vec2.CrossVV(this.m_rB, impulse); data.velocities[this.m_indexB].w = wB; }; b2MouseJoint.prototype.SolvePositionConstraints = function(data) { return true; }; b2MouseJoint.prototype.GetAnchorA = function(out) { out.x = this.m_targetA.x; out.y = this.m_targetA.y; return out; }; b2MouseJoint.prototype.GetAnchorB = function(out) { return this.m_bodyB.GetWorldPoint(this.m_localAnchorB, out); }; b2MouseJoint.prototype.GetReactionForce = function(inv_dt, out) { return b2Vec2.MulSV(inv_dt, this.m_impulse, out); }; b2MouseJoint.prototype.GetReactionTorque = function(inv_dt) { return 0; }; b2MouseJoint.prototype.Dump = function(log) { log("Mouse joint dumping is not supported.\n"); }; b2MouseJoint.prototype.ShiftOrigin = function(newOrigin) { this.m_targetA.SelfSub(newOrigin); }; b2MouseJoint.SolveVelocityConstraints_s_Cdot = new b2Vec2(); b2MouseJoint.SolveVelocityConstraints_s_impulse = new b2Vec2(); b2MouseJoint.SolveVelocityConstraints_s_oldImpulse = new b2Vec2(); return b2MouseJoint; })(b2Joint); var b2PrismaticJointDef = (function(_super) { __extends(b2PrismaticJointDef, _super); function b2PrismaticJointDef() { var _this = _super.call(this, exports.b2JointType.e_prismaticJoint) || this; _this.localAnchorA = new b2Vec2(); _this.localAnchorB = new b2Vec2(); _this.localAxisA = new b2Vec2(1, 0); _this.referenceAngle = 0; _this.enableLimit = false; _this.lowerTranslation = 0; _this.upperTranslation = 0; _this.enableMotor = false; _this.maxMotorForce = 0; _this.motorSpeed = 0; return _this; } b2PrismaticJointDef.prototype.Initialize = function(bA, bB, anchor, axis) { this.bodyA = bA; this.bodyB = bB; this.bodyA.GetLocalPoint(anchor, this.localAnchorA); this.bodyB.GetLocalPoint(anchor, this.localAnchorB); this.bodyA.GetLocalVector(axis, this.localAxisA); this.referenceAngle = this.bodyB.GetAngle() - this.bodyA.GetAngle(); }; return b2PrismaticJointDef; })(b2JointDef); var b2PrismaticJoint = (function(_super) { __extends(b2PrismaticJoint, _super); function b2PrismaticJoint(def) { var _this = _super.call(this, def) || this; _this.m_localAnchorA = new b2Vec2(); _this.m_localAnchorB = new b2Vec2(); _this.m_localXAxisA = new b2Vec2(); _this.m_localYAxisA = new b2Vec2(); _this.m_referenceAngle = 0; _this.m_impulse = new b2Vec3(0, 0, 0); _this.m_motorImpulse = 0; _this.m_lowerTranslation = 0; _this.m_upperTranslation = 0; _this.m_maxMotorForce = 0; _this.m_motorSpeed = 0; _this.m_enableLimit = false; _this.m_enableMotor = false; _this.m_limitState = exports.b2LimitState.e_inactiveLimit; _this.m_indexA = 0; _this.m_indexB = 0; _this.m_localCenterA = new b2Vec2(); _this.m_localCenterB = new b2Vec2(); _this.m_invMassA = 0; _this.m_invMassB = 0; _this.m_invIA = 0; _this.m_invIB = 0; _this.m_axis = new b2Vec2(0, 0); _this.m_perp = new b2Vec2(0, 0); _this.m_s1 = 0; _this.m_s2 = 0; _this.m_a1 = 0; _this.m_a2 = 0; _this.m_K = new b2Mat33(); _this.m_K3 = new b2Mat33(); _this.m_K2 = new b2Mat22(); _this.m_motorMass = 0; _this.m_qA = new b2Rot(); _this.m_qB = new b2Rot(); _this.m_lalcA = new b2Vec2(); _this.m_lalcB = new b2Vec2(); _this.m_rA = new b2Vec2(); _this.m_rB = new b2Vec2(); _this.m_localAnchorA.Copy(b2Maybe(def.localAnchorA, b2Vec2.ZERO)); _this.m_localAnchorB.Copy(b2Maybe(def.localAnchorB, b2Vec2.ZERO)); _this.m_localXAxisA.Copy(b2Maybe(def.localAxisA, new b2Vec2(1, 0))).SelfNormalize(); b2Vec2.CrossOneV(_this.m_localXAxisA, _this.m_localYAxisA); _this.m_referenceAngle = b2Maybe(def.referenceAngle, 0); _this.m_lowerTranslation = b2Maybe(def.lowerTranslation, 0); _this.m_upperTranslation = b2Maybe(def.upperTranslation, 0); _this.m_maxMotorForce = b2Maybe(def.maxMotorForce, 0); _this.m_motorSpeed = b2Maybe(def.motorSpeed, 0); _this.m_enableLimit = b2Maybe(def.enableLimit, false); _this.m_enableMotor = b2Maybe(def.enableMotor, false); return _this; } b2PrismaticJoint.prototype.InitVelocityConstraints = function(data) { this.m_indexA = this.m_bodyA.m_islandIndex; this.m_indexB = this.m_bodyB.m_islandIndex; this.m_localCenterA.Copy(this.m_bodyA.m_sweep.localCenter); this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter); this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var cA = data.positions[this.m_indexA].c; var aA = data.positions[this.m_indexA].a; var vA = data.velocities[this.m_indexA].v; var wA = data.velocities[this.m_indexA].w; var cB = data.positions[this.m_indexB].c; var aB = data.positions[this.m_indexB].a; var vB = data.velocities[this.m_indexB].v; var wB = data.velocities[this.m_indexB].w; var qA = this.m_qA.SetAngle(aA), qB = this.m_qB.SetAngle(aB); b2Vec2.SubVV(this.m_localAnchorA, this.m_localCenterA, this.m_lalcA); var rA = b2Rot.MulRV(qA, this.m_lalcA, this.m_rA); b2Vec2.SubVV(this.m_localAnchorB, this.m_localCenterB, this.m_lalcB); var rB = b2Rot.MulRV(qB, this.m_lalcB, this.m_rB); var d = b2Vec2.AddVV(b2Vec2.SubVV(cB, cA, b2Vec2.s_t0), b2Vec2.SubVV(rB, rA, b2Vec2.s_t1), b2PrismaticJoint.InitVelocityConstraints_s_d); var mA = this.m_invMassA, mB = this.m_invMassB; var iA = this.m_invIA, iB = this.m_invIB; b2Rot.MulRV(qA, this.m_localXAxisA, this.m_axis); this.m_a1 = b2Vec2.CrossVV(b2Vec2.AddVV(d, rA, b2Vec2.s_t0), this.m_axis); this.m_a2 = b2Vec2.CrossVV(rB, this.m_axis); this.m_motorMass = mA + mB + iA * this.m_a1 * this.m_a1 + iB * this.m_a2 * this.m_a2; this.m_motorMass > 0 && (this.m_motorMass = 1 / this.m_motorMass); b2Rot.MulRV(qA, this.m_localYAxisA, this.m_perp); this.m_s1 = b2Vec2.CrossVV(b2Vec2.AddVV(d, rA, b2Vec2.s_t0), this.m_perp); this.m_s2 = b2Vec2.CrossVV(rB, this.m_perp); this.m_K.ex.x = mA + mB + iA * this.m_s1 * this.m_s1 + iB * this.m_s2 * this.m_s2; this.m_K.ex.y = iA * this.m_s1 + iB * this.m_s2; this.m_K.ex.z = iA * this.m_s1 * this.m_a1 + iB * this.m_s2 * this.m_a2; this.m_K.ey.x = this.m_K.ex.y; this.m_K.ey.y = iA + iB; 0 === this.m_K.ey.y && (this.m_K.ey.y = 1); this.m_K.ey.z = iA * this.m_a1 + iB * this.m_a2; this.m_K.ez.x = this.m_K.ex.z; this.m_K.ez.y = this.m_K.ey.z; this.m_K.ez.z = mA + mB + iA * this.m_a1 * this.m_a1 + iB * this.m_a2 * this.m_a2; if (this.m_enableLimit) { var jointTranslation = b2Vec2.DotVV(this.m_axis, d); if (b2Abs(this.m_upperTranslation - this.m_lowerTranslation) < 2 * b2_linearSlop) this.m_limitState = exports.b2LimitState.e_equalLimits; else if (jointTranslation <= this.m_lowerTranslation) { if (this.m_limitState !== exports.b2LimitState.e_atLowerLimit) { this.m_limitState = exports.b2LimitState.e_atLowerLimit; this.m_impulse.z = 0; } } else if (jointTranslation >= this.m_upperTranslation) { if (this.m_limitState !== exports.b2LimitState.e_atUpperLimit) { this.m_limitState = exports.b2LimitState.e_atUpperLimit; this.m_impulse.z = 0; } } else { this.m_limitState = exports.b2LimitState.e_inactiveLimit; this.m_impulse.z = 0; } } else { this.m_limitState = exports.b2LimitState.e_inactiveLimit; this.m_impulse.z = 0; } this.m_enableMotor || (this.m_motorImpulse = 0); if (data.step.warmStarting) { this.m_impulse.SelfMul(data.step.dtRatio); this.m_motorImpulse *= data.step.dtRatio; var P = b2Vec2.AddVV(b2Vec2.MulSV(this.m_impulse.x, this.m_perp, b2Vec2.s_t0), b2Vec2.MulSV(this.m_motorImpulse + this.m_impulse.z, this.m_axis, b2Vec2.s_t1), b2PrismaticJoint.InitVelocityConstraints_s_P); var LA = this.m_impulse.x * this.m_s1 + this.m_impulse.y + (this.m_motorImpulse + this.m_impulse.z) * this.m_a1; var LB = this.m_impulse.x * this.m_s2 + this.m_impulse.y + (this.m_motorImpulse + this.m_impulse.z) * this.m_a2; vA.SelfMulSub(mA, P); wA -= iA * LA; vB.SelfMulAdd(mB, P); wB += iB * LB; } else { this.m_impulse.SetZero(); this.m_motorImpulse = 0; } data.velocities[this.m_indexA].w = wA; data.velocities[this.m_indexB].w = wB; }; b2PrismaticJoint.prototype.SolveVelocityConstraints = function(data) { var vA = data.velocities[this.m_indexA].v; var wA = data.velocities[this.m_indexA].w; var vB = data.velocities[this.m_indexB].v; var wB = data.velocities[this.m_indexB].w; var mA = this.m_invMassA, mB = this.m_invMassB; var iA = this.m_invIA, iB = this.m_invIB; if (this.m_enableMotor && this.m_limitState !== exports.b2LimitState.e_equalLimits) { var Cdot = b2Vec2.DotVV(this.m_axis, b2Vec2.SubVV(vB, vA, b2Vec2.s_t0)) + this.m_a2 * wB - this.m_a1 * wA; var impulse = this.m_motorMass * (this.m_motorSpeed - Cdot); var oldImpulse = this.m_motorImpulse; var maxImpulse = data.step.dt * this.m_maxMotorForce; this.m_motorImpulse = b2Clamp(this.m_motorImpulse + impulse, -maxImpulse, maxImpulse); impulse = this.m_motorImpulse - oldImpulse; var P = b2Vec2.MulSV(impulse, this.m_axis, b2PrismaticJoint.SolveVelocityConstraints_s_P); var LA = impulse * this.m_a1; var LB = impulse * this.m_a2; vA.SelfMulSub(mA, P); wA -= iA * LA; vB.SelfMulAdd(mB, P); wB += iB * LB; } var Cdot1_x = b2Vec2.DotVV(this.m_perp, b2Vec2.SubVV(vB, vA, b2Vec2.s_t0)) + this.m_s2 * wB - this.m_s1 * wA; var Cdot1_y = wB - wA; if (this.m_enableLimit && this.m_limitState !== exports.b2LimitState.e_inactiveLimit) { var Cdot2 = b2Vec2.DotVV(this.m_axis, b2Vec2.SubVV(vB, vA, b2Vec2.s_t0)) + this.m_a2 * wB - this.m_a1 * wA; var f1 = b2PrismaticJoint.SolveVelocityConstraints_s_f1.Copy(this.m_impulse); var df3 = this.m_K.Solve33(-Cdot1_x, -Cdot1_y, -Cdot2, b2PrismaticJoint.SolveVelocityConstraints_s_df3); this.m_impulse.SelfAdd(df3); this.m_limitState === exports.b2LimitState.e_atLowerLimit ? this.m_impulse.z = b2Max(this.m_impulse.z, 0) : this.m_limitState === exports.b2LimitState.e_atUpperLimit && (this.m_impulse.z = b2Min(this.m_impulse.z, 0)); var b_x = -Cdot1_x - (this.m_impulse.z - f1.z) * this.m_K.ez.x; var b_y = -Cdot1_y - (this.m_impulse.z - f1.z) * this.m_K.ez.y; var f2r = this.m_K.Solve22(b_x, b_y, b2PrismaticJoint.SolveVelocityConstraints_s_f2r); f2r.x += f1.x; f2r.y += f1.y; this.m_impulse.x = f2r.x; this.m_impulse.y = f2r.y; df3.x = this.m_impulse.x - f1.x; df3.y = this.m_impulse.y - f1.y; df3.z = this.m_impulse.z - f1.z; var P = b2Vec2.AddVV(b2Vec2.MulSV(df3.x, this.m_perp, b2Vec2.s_t0), b2Vec2.MulSV(df3.z, this.m_axis, b2Vec2.s_t1), b2PrismaticJoint.SolveVelocityConstraints_s_P); var LA = df3.x * this.m_s1 + df3.y + df3.z * this.m_a1; var LB = df3.x * this.m_s2 + df3.y + df3.z * this.m_a2; vA.SelfMulSub(mA, P); wA -= iA * LA; vB.SelfMulAdd(mB, P); wB += iB * LB; } else { var df2 = this.m_K.Solve22(-Cdot1_x, -Cdot1_y, b2PrismaticJoint.SolveVelocityConstraints_s_df2); this.m_impulse.x += df2.x; this.m_impulse.y += df2.y; var P = b2Vec2.MulSV(df2.x, this.m_perp, b2PrismaticJoint.SolveVelocityConstraints_s_P); var LA = df2.x * this.m_s1 + df2.y; var LB = df2.x * this.m_s2 + df2.y; vA.SelfMulSub(mA, P); wA -= iA * LA; vB.SelfMulAdd(mB, P); wB += iB * LB; } data.velocities[this.m_indexA].w = wA; data.velocities[this.m_indexB].w = wB; }; b2PrismaticJoint.prototype.SolvePositionConstraints = function(data) { var cA = data.positions[this.m_indexA].c; var aA = data.positions[this.m_indexA].a; var cB = data.positions[this.m_indexB].c; var aB = data.positions[this.m_indexB].a; var qA = this.m_qA.SetAngle(aA), qB = this.m_qB.SetAngle(aB); var mA = this.m_invMassA, mB = this.m_invMassB; var iA = this.m_invIA, iB = this.m_invIB; var rA = b2Rot.MulRV(qA, this.m_lalcA, this.m_rA); var rB = b2Rot.MulRV(qB, this.m_lalcB, this.m_rB); var d = b2Vec2.SubVV(b2Vec2.AddVV(cB, rB, b2Vec2.s_t0), b2Vec2.AddVV(cA, rA, b2Vec2.s_t1), b2PrismaticJoint.SolvePositionConstraints_s_d); var axis = b2Rot.MulRV(qA, this.m_localXAxisA, this.m_axis); var a1 = b2Vec2.CrossVV(b2Vec2.AddVV(d, rA, b2Vec2.s_t0), axis); var a2 = b2Vec2.CrossVV(rB, axis); var perp = b2Rot.MulRV(qA, this.m_localYAxisA, this.m_perp); var s1 = b2Vec2.CrossVV(b2Vec2.AddVV(d, rA, b2Vec2.s_t0), perp); var s2 = b2Vec2.CrossVV(rB, perp); var impulse = b2PrismaticJoint.SolvePositionConstraints_s_impulse; var C1_x = b2Vec2.DotVV(perp, d); var C1_y = aB - aA - this.m_referenceAngle; var linearError = b2Abs(C1_x); var angularError = b2Abs(C1_y); var active = false; var C2 = 0; if (this.m_enableLimit) { var translation = b2Vec2.DotVV(axis, d); if (b2Abs(this.m_upperTranslation - this.m_lowerTranslation) < 2 * b2_linearSlop) { C2 = b2Clamp(translation, -b2_maxLinearCorrection, b2_maxLinearCorrection); linearError = b2Max(linearError, b2Abs(translation)); active = true; } else if (translation <= this.m_lowerTranslation) { C2 = b2Clamp(translation - this.m_lowerTranslation + b2_linearSlop, -b2_maxLinearCorrection, 0); linearError = b2Max(linearError, this.m_lowerTranslation - translation); active = true; } else if (translation >= this.m_upperTranslation) { C2 = b2Clamp(translation - this.m_upperTranslation - b2_linearSlop, 0, b2_maxLinearCorrection); linearError = b2Max(linearError, translation - this.m_upperTranslation); active = true; } } if (active) { var k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2; var k12 = iA * s1 + iB * s2; var k13 = iA * s1 * a1 + iB * s2 * a2; var k22 = iA + iB; 0 === k22 && (k22 = 1); var k23 = iA * a1 + iB * a2; var k33 = mA + mB + iA * a1 * a1 + iB * a2 * a2; var K = this.m_K3; K.ex.SetXYZ(k11, k12, k13); K.ey.SetXYZ(k12, k22, k23); K.ez.SetXYZ(k13, k23, k33); impulse = K.Solve33(-C1_x, -C1_y, -C2, impulse); } else { var k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2; var k12 = iA * s1 + iB * s2; var k22 = iA + iB; 0 === k22 && (k22 = 1); var K2 = this.m_K2; K2.ex.Set(k11, k12); K2.ey.Set(k12, k22); var impulse1 = K2.Solve(-C1_x, -C1_y, b2PrismaticJoint.SolvePositionConstraints_s_impulse1); impulse.x = impulse1.x; impulse.y = impulse1.y; impulse.z = 0; } var P = b2Vec2.AddVV(b2Vec2.MulSV(impulse.x, perp, b2Vec2.s_t0), b2Vec2.MulSV(impulse.z, axis, b2Vec2.s_t1), b2PrismaticJoint.SolvePositionConstraints_s_P); var LA = impulse.x * s1 + impulse.y + impulse.z * a1; var LB = impulse.x * s2 + impulse.y + impulse.z * a2; cA.SelfMulSub(mA, P); aA -= iA * LA; cB.SelfMulAdd(mB, P); aB += iB * LB; data.positions[this.m_indexA].a = aA; data.positions[this.m_indexB].a = aB; return linearError <= b2_linearSlop && angularError <= b2_angularSlop; }; b2PrismaticJoint.prototype.GetAnchorA = function(out) { return this.m_bodyA.GetWorldPoint(this.m_localAnchorA, out); }; b2PrismaticJoint.prototype.GetAnchorB = function(out) { return this.m_bodyB.GetWorldPoint(this.m_localAnchorB, out); }; b2PrismaticJoint.prototype.GetReactionForce = function(inv_dt, out) { out.x = inv_dt * (this.m_impulse.x * this.m_perp.x + (this.m_motorImpulse + this.m_impulse.z) * this.m_axis.x); out.y = inv_dt * (this.m_impulse.x * this.m_perp.y + (this.m_motorImpulse + this.m_impulse.z) * this.m_axis.y); return out; }; b2PrismaticJoint.prototype.GetReactionTorque = function(inv_dt) { return inv_dt * this.m_impulse.y; }; b2PrismaticJoint.prototype.GetLocalAnchorA = function() { return this.m_localAnchorA; }; b2PrismaticJoint.prototype.GetLocalAnchorB = function() { return this.m_localAnchorB; }; b2PrismaticJoint.prototype.GetLocalAxisA = function() { return this.m_localXAxisA; }; b2PrismaticJoint.prototype.GetReferenceAngle = function() { return this.m_referenceAngle; }; b2PrismaticJoint.prototype.GetJointTranslation = function() { var pA = this.m_bodyA.GetWorldPoint(this.m_localAnchorA, b2PrismaticJoint.GetJointTranslation_s_pA); var pB = this.m_bodyB.GetWorldPoint(this.m_localAnchorB, b2PrismaticJoint.GetJointTranslation_s_pB); var d = b2Vec2.SubVV(pB, pA, b2PrismaticJoint.GetJointTranslation_s_d); var axis = this.m_bodyA.GetWorldVector(this.m_localXAxisA, b2PrismaticJoint.GetJointTranslation_s_axis); var translation = b2Vec2.DotVV(d, axis); return translation; }; b2PrismaticJoint.prototype.GetJointSpeed = function() { var bA = this.m_bodyA; var bB = this.m_bodyB; b2Vec2.SubVV(this.m_localAnchorA, bA.m_sweep.localCenter, this.m_lalcA); var rA = b2Rot.MulRV(bA.m_xf.q, this.m_lalcA, this.m_rA); b2Vec2.SubVV(this.m_localAnchorB, bB.m_sweep.localCenter, this.m_lalcB); var rB = b2Rot.MulRV(bB.m_xf.q, this.m_lalcB, this.m_rB); var pA = b2Vec2.AddVV(bA.m_sweep.c, rA, b2Vec2.s_t0); var pB = b2Vec2.AddVV(bB.m_sweep.c, rB, b2Vec2.s_t1); var d = b2Vec2.SubVV(pB, pA, b2Vec2.s_t2); var axis = bA.GetWorldVector(this.m_localXAxisA, this.m_axis); var vA = bA.m_linearVelocity; var vB = bB.m_linearVelocity; var wA = bA.m_angularVelocity; var wB = bB.m_angularVelocity; var speed = b2Vec2.DotVV(d, b2Vec2.CrossSV(wA, axis, b2Vec2.s_t0)) + b2Vec2.DotVV(axis, b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB, wB, rB, b2Vec2.s_t0), b2Vec2.AddVCrossSV(vA, wA, rA, b2Vec2.s_t1), b2Vec2.s_t0)); return speed; }; b2PrismaticJoint.prototype.IsLimitEnabled = function() { return this.m_enableLimit; }; b2PrismaticJoint.prototype.EnableLimit = function(flag) { if (flag !== this.m_enableLimit) { this.m_bodyA.SetAwake(true); this.m_bodyB.SetAwake(true); this.m_enableLimit = flag; this.m_impulse.z = 0; } }; b2PrismaticJoint.prototype.GetLowerLimit = function() { return this.m_lowerTranslation; }; b2PrismaticJoint.prototype.GetUpperLimit = function() { return this.m_upperTranslation; }; b2PrismaticJoint.prototype.SetLimits = function(lower, upper) { if (lower !== this.m_lowerTranslation || upper !== this.m_upperTranslation) { this.m_bodyA.SetAwake(true); this.m_bodyB.SetAwake(true); this.m_lowerTranslation = lower; this.m_upperTranslation = upper; this.m_impulse.z = 0; } }; b2PrismaticJoint.prototype.IsMotorEnabled = function() { return this.m_enableMotor; }; b2PrismaticJoint.prototype.EnableMotor = function(flag) { if (flag !== this.m_enableMotor) { this.m_bodyA.SetAwake(true); this.m_bodyB.SetAwake(true); this.m_enableMotor = flag; } }; b2PrismaticJoint.prototype.SetMotorSpeed = function(speed) { if (speed !== this.m_motorSpeed) { this.m_bodyA.SetAwake(true); this.m_bodyB.SetAwake(true); this.m_motorSpeed = speed; } }; b2PrismaticJoint.prototype.GetMotorSpeed = function() { return this.m_motorSpeed; }; b2PrismaticJoint.prototype.SetMaxMotorForce = function(force) { if (force !== this.m_maxMotorForce) { this.m_bodyA.SetAwake(true); this.m_bodyB.SetAwake(true); this.m_maxMotorForce = force; } }; b2PrismaticJoint.prototype.GetMaxMotorForce = function() { return this.m_maxMotorForce; }; b2PrismaticJoint.prototype.GetMotorForce = function(inv_dt) { return inv_dt * this.m_motorImpulse; }; b2PrismaticJoint.prototype.Dump = function(log) { var indexA = this.m_bodyA.m_islandIndex; var indexB = this.m_bodyB.m_islandIndex; log(" const jd: b2PrismaticJointDef = new b2PrismaticJointDef();\n"); log(" jd.bodyA = bodies[%d];\n", indexA); log(" jd.bodyB = bodies[%d];\n", indexB); log(" jd.collideConnected = %s;\n", this.m_collideConnected ? "true" : "false"); log(" jd.localAnchorA.Set(%.15f, %.15f);\n", this.m_localAnchorA.x, this.m_localAnchorA.y); log(" jd.localAnchorB.Set(%.15f, %.15f);\n", this.m_localAnchorB.x, this.m_localAnchorB.y); log(" jd.localAxisA.Set(%.15f, %.15f);\n", this.m_localXAxisA.x, this.m_localXAxisA.y); log(" jd.referenceAngle = %.15f;\n", this.m_referenceAngle); log(" jd.enableLimit = %s;\n", this.m_enableLimit ? "true" : "false"); log(" jd.lowerTranslation = %.15f;\n", this.m_lowerTranslation); log(" jd.upperTranslation = %.15f;\n", this.m_upperTranslation); log(" jd.enableMotor = %s;\n", this.m_enableMotor ? "true" : "false"); log(" jd.motorSpeed = %.15f;\n", this.m_motorSpeed); log(" jd.maxMotorForce = %.15f;\n", this.m_maxMotorForce); log(" joints[%d] = this.m_world.CreateJoint(jd);\n", this.m_index); }; b2PrismaticJoint.InitVelocityConstraints_s_d = new b2Vec2(); b2PrismaticJoint.InitVelocityConstraints_s_P = new b2Vec2(); b2PrismaticJoint.SolveVelocityConstraints_s_P = new b2Vec2(); b2PrismaticJoint.SolveVelocityConstraints_s_f2r = new b2Vec2(); b2PrismaticJoint.SolveVelocityConstraints_s_f1 = new b2Vec3(); b2PrismaticJoint.SolveVelocityConstraints_s_df3 = new b2Vec3(); b2PrismaticJoint.SolveVelocityConstraints_s_df2 = new b2Vec2(); b2PrismaticJoint.SolvePositionConstraints_s_d = new b2Vec2(); b2PrismaticJoint.SolvePositionConstraints_s_impulse = new b2Vec3(); b2PrismaticJoint.SolvePositionConstraints_s_impulse1 = new b2Vec2(); b2PrismaticJoint.SolvePositionConstraints_s_P = new b2Vec2(); b2PrismaticJoint.GetJointTranslation_s_pA = new b2Vec2(); b2PrismaticJoint.GetJointTranslation_s_pB = new b2Vec2(); b2PrismaticJoint.GetJointTranslation_s_d = new b2Vec2(); b2PrismaticJoint.GetJointTranslation_s_axis = new b2Vec2(); return b2PrismaticJoint; })(b2Joint); var b2_minPulleyLength = 2; var b2PulleyJointDef = (function(_super) { __extends(b2PulleyJointDef, _super); function b2PulleyJointDef() { var _this = _super.call(this, exports.b2JointType.e_pulleyJoint) || this; _this.groundAnchorA = new b2Vec2(-1, 1); _this.groundAnchorB = new b2Vec2(1, 1); _this.localAnchorA = new b2Vec2(-1, 0); _this.localAnchorB = new b2Vec2(1, 0); _this.lengthA = 0; _this.lengthB = 0; _this.ratio = 1; _this.collideConnected = true; return _this; } b2PulleyJointDef.prototype.Initialize = function(bA, bB, groundA, groundB, anchorA, anchorB, r) { this.bodyA = bA; this.bodyB = bB; this.groundAnchorA.Copy(groundA); this.groundAnchorB.Copy(groundB); this.bodyA.GetLocalPoint(anchorA, this.localAnchorA); this.bodyB.GetLocalPoint(anchorB, this.localAnchorB); this.lengthA = b2Vec2.DistanceVV(anchorA, groundA); this.lengthB = b2Vec2.DistanceVV(anchorB, groundB); this.ratio = r; }; return b2PulleyJointDef; })(b2JointDef); var b2PulleyJoint = (function(_super) { __extends(b2PulleyJoint, _super); function b2PulleyJoint(def) { var _this = _super.call(this, def) || this; _this.m_groundAnchorA = new b2Vec2(); _this.m_groundAnchorB = new b2Vec2(); _this.m_lengthA = 0; _this.m_lengthB = 0; _this.m_localAnchorA = new b2Vec2(); _this.m_localAnchorB = new b2Vec2(); _this.m_constant = 0; _this.m_ratio = 0; _this.m_impulse = 0; _this.m_indexA = 0; _this.m_indexB = 0; _this.m_uA = new b2Vec2(); _this.m_uB = new b2Vec2(); _this.m_rA = new b2Vec2(); _this.m_rB = new b2Vec2(); _this.m_localCenterA = new b2Vec2(); _this.m_localCenterB = new b2Vec2(); _this.m_invMassA = 0; _this.m_invMassB = 0; _this.m_invIA = 0; _this.m_invIB = 0; _this.m_mass = 0; _this.m_qA = new b2Rot(); _this.m_qB = new b2Rot(); _this.m_lalcA = new b2Vec2(); _this.m_lalcB = new b2Vec2(); _this.m_groundAnchorA.Copy(b2Maybe(def.groundAnchorA, new b2Vec2(-1, 1))); _this.m_groundAnchorB.Copy(b2Maybe(def.groundAnchorB, new b2Vec2(1, 0))); _this.m_localAnchorA.Copy(b2Maybe(def.localAnchorA, new b2Vec2(-1, 0))); _this.m_localAnchorB.Copy(b2Maybe(def.localAnchorB, new b2Vec2(1, 0))); _this.m_lengthA = b2Maybe(def.lengthA, 0); _this.m_lengthB = b2Maybe(def.lengthB, 0); _this.m_ratio = b2Maybe(def.ratio, 1); _this.m_constant = b2Maybe(def.lengthA, 0) + _this.m_ratio * b2Maybe(def.lengthB, 0); _this.m_impulse = 0; return _this; } b2PulleyJoint.prototype.InitVelocityConstraints = function(data) { this.m_indexA = this.m_bodyA.m_islandIndex; this.m_indexB = this.m_bodyB.m_islandIndex; this.m_localCenterA.Copy(this.m_bodyA.m_sweep.localCenter); this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter); this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var cA = data.positions[this.m_indexA].c; var aA = data.positions[this.m_indexA].a; var vA = data.velocities[this.m_indexA].v; var wA = data.velocities[this.m_indexA].w; var cB = data.positions[this.m_indexB].c; var aB = data.positions[this.m_indexB].a; var vB = data.velocities[this.m_indexB].v; var wB = data.velocities[this.m_indexB].w; var qA = this.m_qA.SetAngle(aA), qB = this.m_qB.SetAngle(aB); b2Vec2.SubVV(this.m_localAnchorA, this.m_localCenterA, this.m_lalcA); b2Rot.MulRV(qA, this.m_lalcA, this.m_rA); b2Vec2.SubVV(this.m_localAnchorB, this.m_localCenterB, this.m_lalcB); b2Rot.MulRV(qB, this.m_lalcB, this.m_rB); this.m_uA.Copy(cA).SelfAdd(this.m_rA).SelfSub(this.m_groundAnchorA); this.m_uB.Copy(cB).SelfAdd(this.m_rB).SelfSub(this.m_groundAnchorB); var lengthA = this.m_uA.Length(); var lengthB = this.m_uB.Length(); lengthA > 10 * b2_linearSlop ? this.m_uA.SelfMul(1 / lengthA) : this.m_uA.SetZero(); lengthB > 10 * b2_linearSlop ? this.m_uB.SelfMul(1 / lengthB) : this.m_uB.SetZero(); var ruA = b2Vec2.CrossVV(this.m_rA, this.m_uA); var ruB = b2Vec2.CrossVV(this.m_rB, this.m_uB); var mA = this.m_invMassA + this.m_invIA * ruA * ruA; var mB = this.m_invMassB + this.m_invIB * ruB * ruB; this.m_mass = mA + this.m_ratio * this.m_ratio * mB; this.m_mass > 0 && (this.m_mass = 1 / this.m_mass); if (data.step.warmStarting) { this.m_impulse *= data.step.dtRatio; var PA = b2Vec2.MulSV(-this.m_impulse, this.m_uA, b2PulleyJoint.InitVelocityConstraints_s_PA); var PB = b2Vec2.MulSV(-this.m_ratio * this.m_impulse, this.m_uB, b2PulleyJoint.InitVelocityConstraints_s_PB); vA.SelfMulAdd(this.m_invMassA, PA); wA += this.m_invIA * b2Vec2.CrossVV(this.m_rA, PA); vB.SelfMulAdd(this.m_invMassB, PB); wB += this.m_invIB * b2Vec2.CrossVV(this.m_rB, PB); } else this.m_impulse = 0; data.velocities[this.m_indexA].w = wA; data.velocities[this.m_indexB].w = wB; }; b2PulleyJoint.prototype.SolveVelocityConstraints = function(data) { var vA = data.velocities[this.m_indexA].v; var wA = data.velocities[this.m_indexA].w; var vB = data.velocities[this.m_indexB].v; var wB = data.velocities[this.m_indexB].w; var vpA = b2Vec2.AddVCrossSV(vA, wA, this.m_rA, b2PulleyJoint.SolveVelocityConstraints_s_vpA); var vpB = b2Vec2.AddVCrossSV(vB, wB, this.m_rB, b2PulleyJoint.SolveVelocityConstraints_s_vpB); var Cdot = -b2Vec2.DotVV(this.m_uA, vpA) - this.m_ratio * b2Vec2.DotVV(this.m_uB, vpB); var impulse = -this.m_mass * Cdot; this.m_impulse += impulse; var PA = b2Vec2.MulSV(-impulse, this.m_uA, b2PulleyJoint.SolveVelocityConstraints_s_PA); var PB = b2Vec2.MulSV(-this.m_ratio * impulse, this.m_uB, b2PulleyJoint.SolveVelocityConstraints_s_PB); vA.SelfMulAdd(this.m_invMassA, PA); wA += this.m_invIA * b2Vec2.CrossVV(this.m_rA, PA); vB.SelfMulAdd(this.m_invMassB, PB); wB += this.m_invIB * b2Vec2.CrossVV(this.m_rB, PB); data.velocities[this.m_indexA].w = wA; data.velocities[this.m_indexB].w = wB; }; b2PulleyJoint.prototype.SolvePositionConstraints = function(data) { var cA = data.positions[this.m_indexA].c; var aA = data.positions[this.m_indexA].a; var cB = data.positions[this.m_indexB].c; var aB = data.positions[this.m_indexB].a; var qA = this.m_qA.SetAngle(aA), qB = this.m_qB.SetAngle(aB); b2Vec2.SubVV(this.m_localAnchorA, this.m_localCenterA, this.m_lalcA); var rA = b2Rot.MulRV(qA, this.m_lalcA, this.m_rA); b2Vec2.SubVV(this.m_localAnchorB, this.m_localCenterB, this.m_lalcB); var rB = b2Rot.MulRV(qB, this.m_lalcB, this.m_rB); var uA = this.m_uA.Copy(cA).SelfAdd(rA).SelfSub(this.m_groundAnchorA); var uB = this.m_uB.Copy(cB).SelfAdd(rB).SelfSub(this.m_groundAnchorB); var lengthA = uA.Length(); var lengthB = uB.Length(); lengthA > 10 * b2_linearSlop ? uA.SelfMul(1 / lengthA) : uA.SetZero(); lengthB > 10 * b2_linearSlop ? uB.SelfMul(1 / lengthB) : uB.SetZero(); var ruA = b2Vec2.CrossVV(rA, uA); var ruB = b2Vec2.CrossVV(rB, uB); var mA = this.m_invMassA + this.m_invIA * ruA * ruA; var mB = this.m_invMassB + this.m_invIB * ruB * ruB; var mass = mA + this.m_ratio * this.m_ratio * mB; mass > 0 && (mass = 1 / mass); var C = this.m_constant - lengthA - this.m_ratio * lengthB; var linearError = b2Abs(C); var impulse = -mass * C; var PA = b2Vec2.MulSV(-impulse, uA, b2PulleyJoint.SolvePositionConstraints_s_PA); var PB = b2Vec2.MulSV(-this.m_ratio * impulse, uB, b2PulleyJoint.SolvePositionConstraints_s_PB); cA.SelfMulAdd(this.m_invMassA, PA); aA += this.m_invIA * b2Vec2.CrossVV(rA, PA); cB.SelfMulAdd(this.m_invMassB, PB); aB += this.m_invIB * b2Vec2.CrossVV(rB, PB); data.positions[this.m_indexA].a = aA; data.positions[this.m_indexB].a = aB; return linearError < b2_linearSlop; }; b2PulleyJoint.prototype.GetAnchorA = function(out) { return this.m_bodyA.GetWorldPoint(this.m_localAnchorA, out); }; b2PulleyJoint.prototype.GetAnchorB = function(out) { return this.m_bodyB.GetWorldPoint(this.m_localAnchorB, out); }; b2PulleyJoint.prototype.GetReactionForce = function(inv_dt, out) { out.x = inv_dt * this.m_impulse * this.m_uB.x; out.y = inv_dt * this.m_impulse * this.m_uB.y; return out; }; b2PulleyJoint.prototype.GetReactionTorque = function(inv_dt) { return 0; }; b2PulleyJoint.prototype.GetGroundAnchorA = function() { return this.m_groundAnchorA; }; b2PulleyJoint.prototype.GetGroundAnchorB = function() { return this.m_groundAnchorB; }; b2PulleyJoint.prototype.GetLengthA = function() { return this.m_lengthA; }; b2PulleyJoint.prototype.GetLengthB = function() { return this.m_lengthB; }; b2PulleyJoint.prototype.GetRatio = function() { return this.m_ratio; }; b2PulleyJoint.prototype.GetCurrentLengthA = function() { var p = this.m_bodyA.GetWorldPoint(this.m_localAnchorA, b2PulleyJoint.GetCurrentLengthA_s_p); var s = this.m_groundAnchorA; return b2Vec2.DistanceVV(p, s); }; b2PulleyJoint.prototype.GetCurrentLengthB = function() { var p = this.m_bodyB.GetWorldPoint(this.m_localAnchorB, b2PulleyJoint.GetCurrentLengthB_s_p); var s = this.m_groundAnchorB; return b2Vec2.DistanceVV(p, s); }; b2PulleyJoint.prototype.Dump = function(log) { var indexA = this.m_bodyA.m_islandIndex; var indexB = this.m_bodyB.m_islandIndex; log(" const jd: b2PulleyJointDef = new b2PulleyJointDef();\n"); log(" jd.bodyA = bodies[%d];\n", indexA); log(" jd.bodyB = bodies[%d];\n", indexB); log(" jd.collideConnected = %s;\n", this.m_collideConnected ? "true" : "false"); log(" jd.groundAnchorA.Set(%.15f, %.15f);\n", this.m_groundAnchorA.x, this.m_groundAnchorA.y); log(" jd.groundAnchorB.Set(%.15f, %.15f);\n", this.m_groundAnchorB.x, this.m_groundAnchorB.y); log(" jd.localAnchorA.Set(%.15f, %.15f);\n", this.m_localAnchorA.x, this.m_localAnchorA.y); log(" jd.localAnchorB.Set(%.15f, %.15f);\n", this.m_localAnchorB.x, this.m_localAnchorB.y); log(" jd.lengthA = %.15f;\n", this.m_lengthA); log(" jd.lengthB = %.15f;\n", this.m_lengthB); log(" jd.ratio = %.15f;\n", this.m_ratio); log(" joints[%d] = this.m_world.CreateJoint(jd);\n", this.m_index); }; b2PulleyJoint.prototype.ShiftOrigin = function(newOrigin) { this.m_groundAnchorA.SelfSub(newOrigin); this.m_groundAnchorB.SelfSub(newOrigin); }; b2PulleyJoint.InitVelocityConstraints_s_PA = new b2Vec2(); b2PulleyJoint.InitVelocityConstraints_s_PB = new b2Vec2(); b2PulleyJoint.SolveVelocityConstraints_s_vpA = new b2Vec2(); b2PulleyJoint.SolveVelocityConstraints_s_vpB = new b2Vec2(); b2PulleyJoint.SolveVelocityConstraints_s_PA = new b2Vec2(); b2PulleyJoint.SolveVelocityConstraints_s_PB = new b2Vec2(); b2PulleyJoint.SolvePositionConstraints_s_PA = new b2Vec2(); b2PulleyJoint.SolvePositionConstraints_s_PB = new b2Vec2(); b2PulleyJoint.GetCurrentLengthA_s_p = new b2Vec2(); b2PulleyJoint.GetCurrentLengthB_s_p = new b2Vec2(); return b2PulleyJoint; })(b2Joint); var b2RevoluteJointDef = (function(_super) { __extends(b2RevoluteJointDef, _super); function b2RevoluteJointDef() { var _this = _super.call(this, exports.b2JointType.e_revoluteJoint) || this; _this.localAnchorA = new b2Vec2(0, 0); _this.localAnchorB = new b2Vec2(0, 0); _this.referenceAngle = 0; _this.enableLimit = false; _this.lowerAngle = 0; _this.upperAngle = 0; _this.enableMotor = false; _this.motorSpeed = 0; _this.maxMotorTorque = 0; return _this; } b2RevoluteJointDef.prototype.Initialize = function(bA, bB, anchor) { this.bodyA = bA; this.bodyB = bB; this.bodyA.GetLocalPoint(anchor, this.localAnchorA); this.bodyB.GetLocalPoint(anchor, this.localAnchorB); this.referenceAngle = this.bodyB.GetAngle() - this.bodyA.GetAngle(); }; return b2RevoluteJointDef; })(b2JointDef); var b2RevoluteJoint = (function(_super) { __extends(b2RevoluteJoint, _super); function b2RevoluteJoint(def) { var _this = _super.call(this, def) || this; _this.m_localAnchorA = new b2Vec2(); _this.m_localAnchorB = new b2Vec2(); _this.m_impulse = new b2Vec3(); _this.m_motorImpulse = 0; _this.m_enableMotor = false; _this.m_maxMotorTorque = 0; _this.m_motorSpeed = 0; _this.m_enableLimit = false; _this.m_referenceAngle = 0; _this.m_lowerAngle = 0; _this.m_upperAngle = 0; _this.m_indexA = 0; _this.m_indexB = 0; _this.m_rA = new b2Vec2(); _this.m_rB = new b2Vec2(); _this.m_localCenterA = new b2Vec2(); _this.m_localCenterB = new b2Vec2(); _this.m_invMassA = 0; _this.m_invMassB = 0; _this.m_invIA = 0; _this.m_invIB = 0; _this.m_mass = new b2Mat33(); _this.m_motorMass = 0; _this.m_limitState = exports.b2LimitState.e_inactiveLimit; _this.m_qA = new b2Rot(); _this.m_qB = new b2Rot(); _this.m_lalcA = new b2Vec2(); _this.m_lalcB = new b2Vec2(); _this.m_K = new b2Mat22(); _this.m_localAnchorA.Copy(b2Maybe(def.localAnchorA, b2Vec2.ZERO)); _this.m_localAnchorB.Copy(b2Maybe(def.localAnchorB, b2Vec2.ZERO)); _this.m_referenceAngle = b2Maybe(def.referenceAngle, 0); _this.m_impulse.SetZero(); _this.m_motorImpulse = 0; _this.m_lowerAngle = b2Maybe(def.lowerAngle, 0); _this.m_upperAngle = b2Maybe(def.upperAngle, 0); _this.m_maxMotorTorque = b2Maybe(def.maxMotorTorque, 0); _this.m_motorSpeed = b2Maybe(def.motorSpeed, 0); _this.m_enableLimit = b2Maybe(def.enableLimit, false); _this.m_enableMotor = b2Maybe(def.enableMotor, false); _this.m_limitState = exports.b2LimitState.e_inactiveLimit; return _this; } b2RevoluteJoint.prototype.InitVelocityConstraints = function(data) { this.m_indexA = this.m_bodyA.m_islandIndex; this.m_indexB = this.m_bodyB.m_islandIndex; this.m_localCenterA.Copy(this.m_bodyA.m_sweep.localCenter); this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter); this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var aA = data.positions[this.m_indexA].a; var vA = data.velocities[this.m_indexA].v; var wA = data.velocities[this.m_indexA].w; var aB = data.positions[this.m_indexB].a; var vB = data.velocities[this.m_indexB].v; var wB = data.velocities[this.m_indexB].w; var qA = this.m_qA.SetAngle(aA), qB = this.m_qB.SetAngle(aB); b2Vec2.SubVV(this.m_localAnchorA, this.m_localCenterA, this.m_lalcA); b2Rot.MulRV(qA, this.m_lalcA, this.m_rA); b2Vec2.SubVV(this.m_localAnchorB, this.m_localCenterB, this.m_lalcB); b2Rot.MulRV(qB, this.m_lalcB, this.m_rB); var mA = this.m_invMassA, mB = this.m_invMassB; var iA = this.m_invIA, iB = this.m_invIB; var fixedRotation = iA + iB === 0; this.m_mass.ex.x = mA + mB + this.m_rA.y * this.m_rA.y * iA + this.m_rB.y * this.m_rB.y * iB; this.m_mass.ey.x = -this.m_rA.y * this.m_rA.x * iA - this.m_rB.y * this.m_rB.x * iB; this.m_mass.ez.x = -this.m_rA.y * iA - this.m_rB.y * iB; this.m_mass.ex.y = this.m_mass.ey.x; this.m_mass.ey.y = mA + mB + this.m_rA.x * this.m_rA.x * iA + this.m_rB.x * this.m_rB.x * iB; this.m_mass.ez.y = this.m_rA.x * iA + this.m_rB.x * iB; this.m_mass.ex.z = this.m_mass.ez.x; this.m_mass.ey.z = this.m_mass.ez.y; this.m_mass.ez.z = iA + iB; this.m_motorMass = iA + iB; this.m_motorMass > 0 && (this.m_motorMass = 1 / this.m_motorMass); this.m_enableMotor && !fixedRotation || (this.m_motorImpulse = 0); if (this.m_enableLimit && !fixedRotation) { var jointAngle = aB - aA - this.m_referenceAngle; if (b2Abs(this.m_upperAngle - this.m_lowerAngle) < 2 * b2_angularSlop) this.m_limitState = exports.b2LimitState.e_equalLimits; else if (jointAngle <= this.m_lowerAngle) { this.m_limitState !== exports.b2LimitState.e_atLowerLimit && (this.m_impulse.z = 0); this.m_limitState = exports.b2LimitState.e_atLowerLimit; } else if (jointAngle >= this.m_upperAngle) { this.m_limitState !== exports.b2LimitState.e_atUpperLimit && (this.m_impulse.z = 0); this.m_limitState = exports.b2LimitState.e_atUpperLimit; } else { this.m_limitState = exports.b2LimitState.e_inactiveLimit; this.m_impulse.z = 0; } } else this.m_limitState = exports.b2LimitState.e_inactiveLimit; if (data.step.warmStarting) { this.m_impulse.SelfMul(data.step.dtRatio); this.m_motorImpulse *= data.step.dtRatio; var P = b2RevoluteJoint.InitVelocityConstraints_s_P.Set(this.m_impulse.x, this.m_impulse.y); vA.SelfMulSub(mA, P); wA -= iA * (b2Vec2.CrossVV(this.m_rA, P) + this.m_motorImpulse + this.m_impulse.z); vB.SelfMulAdd(mB, P); wB += iB * (b2Vec2.CrossVV(this.m_rB, P) + this.m_motorImpulse + this.m_impulse.z); } else { this.m_impulse.SetZero(); this.m_motorImpulse = 0; } data.velocities[this.m_indexA].w = wA; data.velocities[this.m_indexB].w = wB; }; b2RevoluteJoint.prototype.SolveVelocityConstraints = function(data) { var vA = data.velocities[this.m_indexA].v; var wA = data.velocities[this.m_indexA].w; var vB = data.velocities[this.m_indexB].v; var wB = data.velocities[this.m_indexB].w; var mA = this.m_invMassA, mB = this.m_invMassB; var iA = this.m_invIA, iB = this.m_invIB; var fixedRotation = iA + iB === 0; if (this.m_enableMotor && this.m_limitState !== exports.b2LimitState.e_equalLimits && !fixedRotation) { var Cdot = wB - wA - this.m_motorSpeed; var impulse = -this.m_motorMass * Cdot; var oldImpulse = this.m_motorImpulse; var maxImpulse = data.step.dt * this.m_maxMotorTorque; this.m_motorImpulse = b2Clamp(this.m_motorImpulse + impulse, -maxImpulse, maxImpulse); impulse = this.m_motorImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } if (this.m_enableLimit && this.m_limitState !== exports.b2LimitState.e_inactiveLimit && !fixedRotation) { var Cdot1 = b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB, wB, this.m_rB, b2Vec2.s_t0), b2Vec2.AddVCrossSV(vA, wA, this.m_rA, b2Vec2.s_t1), b2RevoluteJoint.SolveVelocityConstraints_s_Cdot1); var Cdot2 = wB - wA; var impulse_v3 = this.m_mass.Solve33(Cdot1.x, Cdot1.y, Cdot2, b2RevoluteJoint.SolveVelocityConstraints_s_impulse_v3).SelfNeg(); if (this.m_limitState === exports.b2LimitState.e_equalLimits) this.m_impulse.SelfAdd(impulse_v3); else if (this.m_limitState === exports.b2LimitState.e_atLowerLimit) { var newImpulse = this.m_impulse.z + impulse_v3.z; if (newImpulse < 0) { var rhs_x = -Cdot1.x + this.m_impulse.z * this.m_mass.ez.x; var rhs_y = -Cdot1.y + this.m_impulse.z * this.m_mass.ez.y; var reduced_v2 = this.m_mass.Solve22(rhs_x, rhs_y, b2RevoluteJoint.SolveVelocityConstraints_s_reduced_v2); impulse_v3.x = reduced_v2.x; impulse_v3.y = reduced_v2.y; impulse_v3.z = -this.m_impulse.z; this.m_impulse.x += reduced_v2.x; this.m_impulse.y += reduced_v2.y; this.m_impulse.z = 0; } else this.m_impulse.SelfAdd(impulse_v3); } else if (this.m_limitState === exports.b2LimitState.e_atUpperLimit) { var newImpulse = this.m_impulse.z + impulse_v3.z; if (newImpulse > 0) { var rhs_x = -Cdot1.x + this.m_impulse.z * this.m_mass.ez.x; var rhs_y = -Cdot1.y + this.m_impulse.z * this.m_mass.ez.y; var reduced_v2 = this.m_mass.Solve22(rhs_x, rhs_y, b2RevoluteJoint.SolveVelocityConstraints_s_reduced_v2); impulse_v3.x = reduced_v2.x; impulse_v3.y = reduced_v2.y; impulse_v3.z = -this.m_impulse.z; this.m_impulse.x += reduced_v2.x; this.m_impulse.y += reduced_v2.y; this.m_impulse.z = 0; } else this.m_impulse.SelfAdd(impulse_v3); } var P = b2RevoluteJoint.SolveVelocityConstraints_s_P.Set(impulse_v3.x, impulse_v3.y); vA.SelfMulSub(mA, P); wA -= iA * (b2Vec2.CrossVV(this.m_rA, P) + impulse_v3.z); vB.SelfMulAdd(mB, P); wB += iB * (b2Vec2.CrossVV(this.m_rB, P) + impulse_v3.z); } else { var Cdot_v2 = b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB, wB, this.m_rB, b2Vec2.s_t0), b2Vec2.AddVCrossSV(vA, wA, this.m_rA, b2Vec2.s_t1), b2RevoluteJoint.SolveVelocityConstraints_s_Cdot_v2); var impulse_v2 = this.m_mass.Solve22(-Cdot_v2.x, -Cdot_v2.y, b2RevoluteJoint.SolveVelocityConstraints_s_impulse_v2); this.m_impulse.x += impulse_v2.x; this.m_impulse.y += impulse_v2.y; vA.SelfMulSub(mA, impulse_v2); wA -= iA * b2Vec2.CrossVV(this.m_rA, impulse_v2); vB.SelfMulAdd(mB, impulse_v2); wB += iB * b2Vec2.CrossVV(this.m_rB, impulse_v2); } data.velocities[this.m_indexA].w = wA; data.velocities[this.m_indexB].w = wB; }; b2RevoluteJoint.prototype.SolvePositionConstraints = function(data) { var cA = data.positions[this.m_indexA].c; var aA = data.positions[this.m_indexA].a; var cB = data.positions[this.m_indexB].c; var aB = data.positions[this.m_indexB].a; var qA = this.m_qA.SetAngle(aA), qB = this.m_qB.SetAngle(aB); var angularError = 0; var positionError = 0; var fixedRotation = this.m_invIA + this.m_invIB === 0; if (this.m_enableLimit && this.m_limitState !== exports.b2LimitState.e_inactiveLimit && !fixedRotation) { var angle = aB - aA - this.m_referenceAngle; var limitImpulse = 0; if (this.m_limitState === exports.b2LimitState.e_equalLimits) { var C = b2Clamp(angle - this.m_lowerAngle, -b2_maxAngularCorrection, b2_maxAngularCorrection); limitImpulse = -this.m_motorMass * C; angularError = b2Abs(C); } else if (this.m_limitState === exports.b2LimitState.e_atLowerLimit) { var C = angle - this.m_lowerAngle; angularError = -C; C = b2Clamp(C + b2_angularSlop, -b2_maxAngularCorrection, 0); limitImpulse = -this.m_motorMass * C; } else if (this.m_limitState === exports.b2LimitState.e_atUpperLimit) { var C = angle - this.m_upperAngle; angularError = C; C = b2Clamp(C - b2_angularSlop, 0, b2_maxAngularCorrection); limitImpulse = -this.m_motorMass * C; } aA -= this.m_invIA * limitImpulse; aB += this.m_invIB * limitImpulse; } qA.SetAngle(aA); qB.SetAngle(aB); b2Vec2.SubVV(this.m_localAnchorA, this.m_localCenterA, this.m_lalcA); var rA = b2Rot.MulRV(qA, this.m_lalcA, this.m_rA); b2Vec2.SubVV(this.m_localAnchorB, this.m_localCenterB, this.m_lalcB); var rB = b2Rot.MulRV(qB, this.m_lalcB, this.m_rB); var C_v2 = b2Vec2.SubVV(b2Vec2.AddVV(cB, rB, b2Vec2.s_t0), b2Vec2.AddVV(cA, rA, b2Vec2.s_t1), b2RevoluteJoint.SolvePositionConstraints_s_C_v2); positionError = C_v2.Length(); var mA = this.m_invMassA, mB = this.m_invMassB; var iA = this.m_invIA, iB = this.m_invIB; var K = this.m_K; K.ex.x = mA + mB + iA * rA.y * rA.y + iB * rB.y * rB.y; K.ex.y = -iA * rA.x * rA.y - iB * rB.x * rB.y; K.ey.x = K.ex.y; K.ey.y = mA + mB + iA * rA.x * rA.x + iB * rB.x * rB.x; var impulse = K.Solve(C_v2.x, C_v2.y, b2RevoluteJoint.SolvePositionConstraints_s_impulse).SelfNeg(); cA.SelfMulSub(mA, impulse); aA -= iA * b2Vec2.CrossVV(rA, impulse); cB.SelfMulAdd(mB, impulse); aB += iB * b2Vec2.CrossVV(rB, impulse); data.positions[this.m_indexA].a = aA; data.positions[this.m_indexB].a = aB; return positionError <= b2_linearSlop && angularError <= b2_angularSlop; }; b2RevoluteJoint.prototype.GetAnchorA = function(out) { return this.m_bodyA.GetWorldPoint(this.m_localAnchorA, out); }; b2RevoluteJoint.prototype.GetAnchorB = function(out) { return this.m_bodyB.GetWorldPoint(this.m_localAnchorB, out); }; b2RevoluteJoint.prototype.GetReactionForce = function(inv_dt, out) { out.x = inv_dt * this.m_impulse.x; out.y = inv_dt * this.m_impulse.y; return out; }; b2RevoluteJoint.prototype.GetReactionTorque = function(inv_dt) { return inv_dt * this.m_impulse.z; }; b2RevoluteJoint.prototype.GetLocalAnchorA = function() { return this.m_localAnchorA; }; b2RevoluteJoint.prototype.GetLocalAnchorB = function() { return this.m_localAnchorB; }; b2RevoluteJoint.prototype.GetReferenceAngle = function() { return this.m_referenceAngle; }; b2RevoluteJoint.prototype.GetJointAngle = function() { return this.m_bodyB.m_sweep.a - this.m_bodyA.m_sweep.a - this.m_referenceAngle; }; b2RevoluteJoint.prototype.GetJointSpeed = function() { return this.m_bodyB.m_angularVelocity - this.m_bodyA.m_angularVelocity; }; b2RevoluteJoint.prototype.IsMotorEnabled = function() { return this.m_enableMotor; }; b2RevoluteJoint.prototype.EnableMotor = function(flag) { if (flag !== this.m_enableMotor) { this.m_bodyA.SetAwake(true); this.m_bodyB.SetAwake(true); this.m_enableMotor = flag; } }; b2RevoluteJoint.prototype.GetMotorTorque = function(inv_dt) { return inv_dt * this.m_motorImpulse; }; b2RevoluteJoint.prototype.GetMotorSpeed = function() { return this.m_motorSpeed; }; b2RevoluteJoint.prototype.SetMaxMotorTorque = function(torque) { if (torque !== this.m_maxMotorTorque) { this.m_bodyA.SetAwake(true); this.m_bodyB.SetAwake(true); this.m_maxMotorTorque = torque; } }; b2RevoluteJoint.prototype.GetMaxMotorTorque = function() { return this.m_maxMotorTorque; }; b2RevoluteJoint.prototype.IsLimitEnabled = function() { return this.m_enableLimit; }; b2RevoluteJoint.prototype.EnableLimit = function(flag) { if (flag !== this.m_enableLimit) { this.m_bodyA.SetAwake(true); this.m_bodyB.SetAwake(true); this.m_enableLimit = flag; this.m_impulse.z = 0; } }; b2RevoluteJoint.prototype.GetLowerLimit = function() { return this.m_lowerAngle; }; b2RevoluteJoint.prototype.GetUpperLimit = function() { return this.m_upperAngle; }; b2RevoluteJoint.prototype.SetLimits = function(lower, upper) { if (lower !== this.m_lowerAngle || upper !== this.m_upperAngle) { this.m_bodyA.SetAwake(true); this.m_bodyB.SetAwake(true); this.m_impulse.z = 0; this.m_lowerAngle = lower; this.m_upperAngle = upper; } }; b2RevoluteJoint.prototype.SetMotorSpeed = function(speed) { if (speed !== this.m_motorSpeed) { this.m_bodyA.SetAwake(true); this.m_bodyB.SetAwake(true); this.m_motorSpeed = speed; } }; b2RevoluteJoint.prototype.Dump = function(log) { var indexA = this.m_bodyA.m_islandIndex; var indexB = this.m_bodyB.m_islandIndex; log(" const jd: b2RevoluteJointDef = new b2RevoluteJointDef();\n"); log(" jd.bodyA = bodies[%d];\n", indexA); log(" jd.bodyB = bodies[%d];\n", indexB); log(" jd.collideConnected = %s;\n", this.m_collideConnected ? "true" : "false"); log(" jd.localAnchorA.Set(%.15f, %.15f);\n", this.m_localAnchorA.x, this.m_localAnchorA.y); log(" jd.localAnchorB.Set(%.15f, %.15f);\n", this.m_localAnchorB.x, this.m_localAnchorB.y); log(" jd.referenceAngle = %.15f;\n", this.m_referenceAngle); log(" jd.enableLimit = %s;\n", this.m_enableLimit ? "true" : "false"); log(" jd.lowerAngle = %.15f;\n", this.m_lowerAngle); log(" jd.upperAngle = %.15f;\n", this.m_upperAngle); log(" jd.enableMotor = %s;\n", this.m_enableMotor ? "true" : "false"); log(" jd.motorSpeed = %.15f;\n", this.m_motorSpeed); log(" jd.maxMotorTorque = %.15f;\n", this.m_maxMotorTorque); log(" joints[%d] = this.m_world.CreateJoint(jd);\n", this.m_index); }; b2RevoluteJoint.InitVelocityConstraints_s_P = new b2Vec2(); b2RevoluteJoint.SolveVelocityConstraints_s_P = new b2Vec2(); b2RevoluteJoint.SolveVelocityConstraints_s_Cdot_v2 = new b2Vec2(); b2RevoluteJoint.SolveVelocityConstraints_s_Cdot1 = new b2Vec2(); b2RevoluteJoint.SolveVelocityConstraints_s_impulse_v3 = new b2Vec3(); b2RevoluteJoint.SolveVelocityConstraints_s_reduced_v2 = new b2Vec2(); b2RevoluteJoint.SolveVelocityConstraints_s_impulse_v2 = new b2Vec2(); b2RevoluteJoint.SolvePositionConstraints_s_C_v2 = new b2Vec2(); b2RevoluteJoint.SolvePositionConstraints_s_impulse = new b2Vec2(); return b2RevoluteJoint; })(b2Joint); var b2RopeJointDef = (function(_super) { __extends(b2RopeJointDef, _super); function b2RopeJointDef() { var _this = _super.call(this, exports.b2JointType.e_ropeJoint) || this; _this.localAnchorA = new b2Vec2(-1, 0); _this.localAnchorB = new b2Vec2(1, 0); _this.maxLength = 0; return _this; } return b2RopeJointDef; })(b2JointDef); var b2RopeJoint = (function(_super) { __extends(b2RopeJoint, _super); function b2RopeJoint(def) { var _this = _super.call(this, def) || this; _this.m_localAnchorA = new b2Vec2(); _this.m_localAnchorB = new b2Vec2(); _this.m_maxLength = 0; _this.m_length = 0; _this.m_impulse = 0; _this.m_indexA = 0; _this.m_indexB = 0; _this.m_u = new b2Vec2(); _this.m_rA = new b2Vec2(); _this.m_rB = new b2Vec2(); _this.m_localCenterA = new b2Vec2(); _this.m_localCenterB = new b2Vec2(); _this.m_invMassA = 0; _this.m_invMassB = 0; _this.m_invIA = 0; _this.m_invIB = 0; _this.m_mass = 0; _this.m_state = exports.b2LimitState.e_inactiveLimit; _this.m_qA = new b2Rot(); _this.m_qB = new b2Rot(); _this.m_lalcA = new b2Vec2(); _this.m_lalcB = new b2Vec2(); _this.m_localAnchorA.Copy(b2Maybe(def.localAnchorA, new b2Vec2(-1, 0))); _this.m_localAnchorB.Copy(b2Maybe(def.localAnchorB, new b2Vec2(1, 0))); _this.m_maxLength = b2Maybe(def.maxLength, 0); return _this; } b2RopeJoint.prototype.InitVelocityConstraints = function(data) { this.m_indexA = this.m_bodyA.m_islandIndex; this.m_indexB = this.m_bodyB.m_islandIndex; this.m_localCenterA.Copy(this.m_bodyA.m_sweep.localCenter); this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter); this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var cA = data.positions[this.m_indexA].c; var aA = data.positions[this.m_indexA].a; var vA = data.velocities[this.m_indexA].v; var wA = data.velocities[this.m_indexA].w; var cB = data.positions[this.m_indexB].c; var aB = data.positions[this.m_indexB].a; var vB = data.velocities[this.m_indexB].v; var wB = data.velocities[this.m_indexB].w; var qA = this.m_qA.SetAngle(aA), qB = this.m_qB.SetAngle(aB); b2Vec2.SubVV(this.m_localAnchorA, this.m_localCenterA, this.m_lalcA); b2Rot.MulRV(qA, this.m_lalcA, this.m_rA); b2Vec2.SubVV(this.m_localAnchorB, this.m_localCenterB, this.m_lalcB); b2Rot.MulRV(qB, this.m_lalcB, this.m_rB); this.m_u.Copy(cB).SelfAdd(this.m_rB).SelfSub(cA).SelfSub(this.m_rA); this.m_length = this.m_u.Length(); var C = this.m_length - this.m_maxLength; this.m_state = C > 0 ? exports.b2LimitState.e_atUpperLimit : exports.b2LimitState.e_inactiveLimit; if (!(this.m_length > b2_linearSlop)) { this.m_u.SetZero(); this.m_mass = 0; this.m_impulse = 0; return; } this.m_u.SelfMul(1 / this.m_length); var crA = b2Vec2.CrossVV(this.m_rA, this.m_u); var crB = b2Vec2.CrossVV(this.m_rB, this.m_u); var invMass = this.m_invMassA + this.m_invIA * crA * crA + this.m_invMassB + this.m_invIB * crB * crB; this.m_mass = 0 !== invMass ? 1 / invMass : 0; if (data.step.warmStarting) { this.m_impulse *= data.step.dtRatio; var P = b2Vec2.MulSV(this.m_impulse, this.m_u, b2RopeJoint.InitVelocityConstraints_s_P); vA.SelfMulSub(this.m_invMassA, P); wA -= this.m_invIA * b2Vec2.CrossVV(this.m_rA, P); vB.SelfMulAdd(this.m_invMassB, P); wB += this.m_invIB * b2Vec2.CrossVV(this.m_rB, P); } else this.m_impulse = 0; data.velocities[this.m_indexA].w = wA; data.velocities[this.m_indexB].w = wB; }; b2RopeJoint.prototype.SolveVelocityConstraints = function(data) { var vA = data.velocities[this.m_indexA].v; var wA = data.velocities[this.m_indexA].w; var vB = data.velocities[this.m_indexB].v; var wB = data.velocities[this.m_indexB].w; var vpA = b2Vec2.AddVCrossSV(vA, wA, this.m_rA, b2RopeJoint.SolveVelocityConstraints_s_vpA); var vpB = b2Vec2.AddVCrossSV(vB, wB, this.m_rB, b2RopeJoint.SolveVelocityConstraints_s_vpB); var C = this.m_length - this.m_maxLength; var Cdot = b2Vec2.DotVV(this.m_u, b2Vec2.SubVV(vpB, vpA, b2Vec2.s_t0)); C < 0 && (Cdot += data.step.inv_dt * C); var impulse = -this.m_mass * Cdot; var oldImpulse = this.m_impulse; this.m_impulse = b2Min(0, this.m_impulse + impulse); impulse = this.m_impulse - oldImpulse; var P = b2Vec2.MulSV(impulse, this.m_u, b2RopeJoint.SolveVelocityConstraints_s_P); vA.SelfMulSub(this.m_invMassA, P); wA -= this.m_invIA * b2Vec2.CrossVV(this.m_rA, P); vB.SelfMulAdd(this.m_invMassB, P); wB += this.m_invIB * b2Vec2.CrossVV(this.m_rB, P); data.velocities[this.m_indexA].w = wA; data.velocities[this.m_indexB].w = wB; }; b2RopeJoint.prototype.SolvePositionConstraints = function(data) { var cA = data.positions[this.m_indexA].c; var aA = data.positions[this.m_indexA].a; var cB = data.positions[this.m_indexB].c; var aB = data.positions[this.m_indexB].a; var qA = this.m_qA.SetAngle(aA), qB = this.m_qB.SetAngle(aB); b2Vec2.SubVV(this.m_localAnchorA, this.m_localCenterA, this.m_lalcA); var rA = b2Rot.MulRV(qA, this.m_lalcA, this.m_rA); b2Vec2.SubVV(this.m_localAnchorB, this.m_localCenterB, this.m_lalcB); var rB = b2Rot.MulRV(qB, this.m_lalcB, this.m_rB); var u = this.m_u.Copy(cB).SelfAdd(rB).SelfSub(cA).SelfSub(rA); var length = u.Normalize(); var C = length - this.m_maxLength; C = b2Clamp(C, 0, b2_maxLinearCorrection); var impulse = -this.m_mass * C; var P = b2Vec2.MulSV(impulse, u, b2RopeJoint.SolvePositionConstraints_s_P); cA.SelfMulSub(this.m_invMassA, P); aA -= this.m_invIA * b2Vec2.CrossVV(rA, P); cB.SelfMulAdd(this.m_invMassB, P); aB += this.m_invIB * b2Vec2.CrossVV(rB, P); data.positions[this.m_indexA].a = aA; data.positions[this.m_indexB].a = aB; return length - this.m_maxLength < b2_linearSlop; }; b2RopeJoint.prototype.GetAnchorA = function(out) { return this.m_bodyA.GetWorldPoint(this.m_localAnchorA, out); }; b2RopeJoint.prototype.GetAnchorB = function(out) { return this.m_bodyB.GetWorldPoint(this.m_localAnchorB, out); }; b2RopeJoint.prototype.GetReactionForce = function(inv_dt, out) { return b2Vec2.MulSV(inv_dt * this.m_impulse, this.m_u, out); }; b2RopeJoint.prototype.GetReactionTorque = function(inv_dt) { return 0; }; b2RopeJoint.prototype.GetLocalAnchorA = function() { return this.m_localAnchorA; }; b2RopeJoint.prototype.GetLocalAnchorB = function() { return this.m_localAnchorB; }; b2RopeJoint.prototype.SetMaxLength = function(length) { this.m_maxLength = length; }; b2RopeJoint.prototype.GetMaxLength = function() { return this.m_maxLength; }; b2RopeJoint.prototype.GetLimitState = function() { return this.m_state; }; b2RopeJoint.prototype.Dump = function(log) { var indexA = this.m_bodyA.m_islandIndex; var indexB = this.m_bodyB.m_islandIndex; log(" const jd: b2RopeJointDef = new b2RopeJointDef();\n"); log(" jd.bodyA = bodies[%d];\n", indexA); log(" jd.bodyB = bodies[%d];\n", indexB); log(" jd.collideConnected = %s;\n", this.m_collideConnected ? "true" : "false"); log(" jd.localAnchorA.Set(%.15f, %.15f);\n", this.m_localAnchorA.x, this.m_localAnchorA.y); log(" jd.localAnchorB.Set(%.15f, %.15f);\n", this.m_localAnchorB.x, this.m_localAnchorB.y); log(" jd.maxLength = %.15f;\n", this.m_maxLength); log(" joints[%d] = this.m_world.CreateJoint(jd);\n", this.m_index); }; b2RopeJoint.InitVelocityConstraints_s_P = new b2Vec2(); b2RopeJoint.SolveVelocityConstraints_s_vpA = new b2Vec2(); b2RopeJoint.SolveVelocityConstraints_s_vpB = new b2Vec2(); b2RopeJoint.SolveVelocityConstraints_s_P = new b2Vec2(); b2RopeJoint.SolvePositionConstraints_s_P = new b2Vec2(); return b2RopeJoint; })(b2Joint); var b2WeldJointDef = (function(_super) { __extends(b2WeldJointDef, _super); function b2WeldJointDef() { var _this = _super.call(this, exports.b2JointType.e_weldJoint) || this; _this.localAnchorA = new b2Vec2(); _this.localAnchorB = new b2Vec2(); _this.referenceAngle = 0; _this.frequencyHz = 0; _this.dampingRatio = 0; return _this; } b2WeldJointDef.prototype.Initialize = function(bA, bB, anchor) { this.bodyA = bA; this.bodyB = bB; this.bodyA.GetLocalPoint(anchor, this.localAnchorA); this.bodyB.GetLocalPoint(anchor, this.localAnchorB); this.referenceAngle = this.bodyB.GetAngle() - this.bodyA.GetAngle(); }; return b2WeldJointDef; })(b2JointDef); var b2WeldJoint = (function(_super) { __extends(b2WeldJoint, _super); function b2WeldJoint(def) { var _this = _super.call(this, def) || this; _this.m_frequencyHz = 0; _this.m_dampingRatio = 0; _this.m_bias = 0; _this.m_localAnchorA = new b2Vec2(); _this.m_localAnchorB = new b2Vec2(); _this.m_referenceAngle = 0; _this.m_gamma = 0; _this.m_impulse = new b2Vec3(0, 0, 0); _this.m_indexA = 0; _this.m_indexB = 0; _this.m_rA = new b2Vec2(); _this.m_rB = new b2Vec2(); _this.m_localCenterA = new b2Vec2(); _this.m_localCenterB = new b2Vec2(); _this.m_invMassA = 0; _this.m_invMassB = 0; _this.m_invIA = 0; _this.m_invIB = 0; _this.m_mass = new b2Mat33(); _this.m_qA = new b2Rot(); _this.m_qB = new b2Rot(); _this.m_lalcA = new b2Vec2(); _this.m_lalcB = new b2Vec2(); _this.m_K = new b2Mat33(); _this.m_frequencyHz = b2Maybe(def.frequencyHz, 0); _this.m_dampingRatio = b2Maybe(def.dampingRatio, 0); _this.m_localAnchorA.Copy(b2Maybe(def.localAnchorA, b2Vec2.ZERO)); _this.m_localAnchorB.Copy(b2Maybe(def.localAnchorB, b2Vec2.ZERO)); _this.m_referenceAngle = b2Maybe(def.referenceAngle, 0); _this.m_impulse.SetZero(); return _this; } b2WeldJoint.prototype.InitVelocityConstraints = function(data) { this.m_indexA = this.m_bodyA.m_islandIndex; this.m_indexB = this.m_bodyB.m_islandIndex; this.m_localCenterA.Copy(this.m_bodyA.m_sweep.localCenter); this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter); this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var aA = data.positions[this.m_indexA].a; var vA = data.velocities[this.m_indexA].v; var wA = data.velocities[this.m_indexA].w; var aB = data.positions[this.m_indexB].a; var vB = data.velocities[this.m_indexB].v; var wB = data.velocities[this.m_indexB].w; var qA = this.m_qA.SetAngle(aA), qB = this.m_qB.SetAngle(aB); b2Vec2.SubVV(this.m_localAnchorA, this.m_localCenterA, this.m_lalcA); b2Rot.MulRV(qA, this.m_lalcA, this.m_rA); b2Vec2.SubVV(this.m_localAnchorB, this.m_localCenterB, this.m_lalcB); b2Rot.MulRV(qB, this.m_lalcB, this.m_rB); var mA = this.m_invMassA, mB = this.m_invMassB; var iA = this.m_invIA, iB = this.m_invIB; var K = this.m_K; K.ex.x = mA + mB + this.m_rA.y * this.m_rA.y * iA + this.m_rB.y * this.m_rB.y * iB; K.ey.x = -this.m_rA.y * this.m_rA.x * iA - this.m_rB.y * this.m_rB.x * iB; K.ez.x = -this.m_rA.y * iA - this.m_rB.y * iB; K.ex.y = K.ey.x; K.ey.y = mA + mB + this.m_rA.x * this.m_rA.x * iA + this.m_rB.x * this.m_rB.x * iB; K.ez.y = this.m_rA.x * iA + this.m_rB.x * iB; K.ex.z = K.ez.x; K.ey.z = K.ez.y; K.ez.z = iA + iB; if (this.m_frequencyHz > 0) { K.GetInverse22(this.m_mass); var invM = iA + iB; var m = invM > 0 ? 1 / invM : 0; var C = aB - aA - this.m_referenceAngle; var omega = 2 * b2_pi * this.m_frequencyHz; var d = 2 * m * this.m_dampingRatio * omega; var k = m * omega * omega; var h = data.step.dt; this.m_gamma = h * (d + h * k); this.m_gamma = 0 !== this.m_gamma ? 1 / this.m_gamma : 0; this.m_bias = C * h * k * this.m_gamma; invM += this.m_gamma; this.m_mass.ez.z = 0 !== invM ? 1 / invM : 0; } else { K.GetSymInverse33(this.m_mass); this.m_gamma = 0; this.m_bias = 0; } if (data.step.warmStarting) { this.m_impulse.SelfMul(data.step.dtRatio); var P = b2WeldJoint.InitVelocityConstraints_s_P.Set(this.m_impulse.x, this.m_impulse.y); vA.SelfMulSub(mA, P); wA -= iA * (b2Vec2.CrossVV(this.m_rA, P) + this.m_impulse.z); vB.SelfMulAdd(mB, P); wB += iB * (b2Vec2.CrossVV(this.m_rB, P) + this.m_impulse.z); } else this.m_impulse.SetZero(); data.velocities[this.m_indexA].w = wA; data.velocities[this.m_indexB].w = wB; }; b2WeldJoint.prototype.SolveVelocityConstraints = function(data) { var vA = data.velocities[this.m_indexA].v; var wA = data.velocities[this.m_indexA].w; var vB = data.velocities[this.m_indexB].v; var wB = data.velocities[this.m_indexB].w; var mA = this.m_invMassA, mB = this.m_invMassB; var iA = this.m_invIA, iB = this.m_invIB; if (this.m_frequencyHz > 0) { var Cdot2 = wB - wA; var impulse2 = -this.m_mass.ez.z * (Cdot2 + this.m_bias + this.m_gamma * this.m_impulse.z); this.m_impulse.z += impulse2; wA -= iA * impulse2; wB += iB * impulse2; var Cdot1 = b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB, wB, this.m_rB, b2Vec2.s_t0), b2Vec2.AddVCrossSV(vA, wA, this.m_rA, b2Vec2.s_t1), b2WeldJoint.SolveVelocityConstraints_s_Cdot1); var impulse1 = b2Mat33.MulM33XY(this.m_mass, Cdot1.x, Cdot1.y, b2WeldJoint.SolveVelocityConstraints_s_impulse1).SelfNeg(); this.m_impulse.x += impulse1.x; this.m_impulse.y += impulse1.y; var P = impulse1; vA.SelfMulSub(mA, P); wA -= iA * b2Vec2.CrossVV(this.m_rA, P); vB.SelfMulAdd(mB, P); wB += iB * b2Vec2.CrossVV(this.m_rB, P); } else { var Cdot1 = b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB, wB, this.m_rB, b2Vec2.s_t0), b2Vec2.AddVCrossSV(vA, wA, this.m_rA, b2Vec2.s_t1), b2WeldJoint.SolveVelocityConstraints_s_Cdot1); var Cdot2 = wB - wA; var impulse = b2Mat33.MulM33XYZ(this.m_mass, Cdot1.x, Cdot1.y, Cdot2, b2WeldJoint.SolveVelocityConstraints_s_impulse).SelfNeg(); this.m_impulse.SelfAdd(impulse); var P = b2WeldJoint.SolveVelocityConstraints_s_P.Set(impulse.x, impulse.y); vA.SelfMulSub(mA, P); wA -= iA * (b2Vec2.CrossVV(this.m_rA, P) + impulse.z); vB.SelfMulAdd(mB, P); wB += iB * (b2Vec2.CrossVV(this.m_rB, P) + impulse.z); } data.velocities[this.m_indexA].w = wA; data.velocities[this.m_indexB].w = wB; }; b2WeldJoint.prototype.SolvePositionConstraints = function(data) { var cA = data.positions[this.m_indexA].c; var aA = data.positions[this.m_indexA].a; var cB = data.positions[this.m_indexB].c; var aB = data.positions[this.m_indexB].a; var qA = this.m_qA.SetAngle(aA), qB = this.m_qB.SetAngle(aB); var mA = this.m_invMassA, mB = this.m_invMassB; var iA = this.m_invIA, iB = this.m_invIB; b2Vec2.SubVV(this.m_localAnchorA, this.m_localCenterA, this.m_lalcA); var rA = b2Rot.MulRV(qA, this.m_lalcA, this.m_rA); b2Vec2.SubVV(this.m_localAnchorB, this.m_localCenterB, this.m_lalcB); var rB = b2Rot.MulRV(qB, this.m_lalcB, this.m_rB); var positionError, angularError; var K = this.m_K; K.ex.x = mA + mB + rA.y * rA.y * iA + rB.y * rB.y * iB; K.ey.x = -rA.y * rA.x * iA - rB.y * rB.x * iB; K.ez.x = -rA.y * iA - rB.y * iB; K.ex.y = K.ey.x; K.ey.y = mA + mB + rA.x * rA.x * iA + rB.x * rB.x * iB; K.ez.y = rA.x * iA + rB.x * iB; K.ex.z = K.ez.x; K.ey.z = K.ez.y; K.ez.z = iA + iB; if (this.m_frequencyHz > 0) { var C1 = b2Vec2.SubVV(b2Vec2.AddVV(cB, rB, b2Vec2.s_t0), b2Vec2.AddVV(cA, rA, b2Vec2.s_t1), b2WeldJoint.SolvePositionConstraints_s_C1); positionError = C1.Length(); angularError = 0; var P = K.Solve22(C1.x, C1.y, b2WeldJoint.SolvePositionConstraints_s_P).SelfNeg(); cA.SelfMulSub(mA, P); aA -= iA * b2Vec2.CrossVV(rA, P); cB.SelfMulAdd(mB, P); aB += iB * b2Vec2.CrossVV(rB, P); } else { var C1 = b2Vec2.SubVV(b2Vec2.AddVV(cB, rB, b2Vec2.s_t0), b2Vec2.AddVV(cA, rA, b2Vec2.s_t1), b2WeldJoint.SolvePositionConstraints_s_C1); var C2 = aB - aA - this.m_referenceAngle; positionError = C1.Length(); angularError = b2Abs(C2); var impulse = K.Solve33(C1.x, C1.y, C2, b2WeldJoint.SolvePositionConstraints_s_impulse).SelfNeg(); var P = b2WeldJoint.SolvePositionConstraints_s_P.Set(impulse.x, impulse.y); cA.SelfMulSub(mA, P); aA -= iA * (b2Vec2.CrossVV(this.m_rA, P) + impulse.z); cB.SelfMulAdd(mB, P); aB += iB * (b2Vec2.CrossVV(this.m_rB, P) + impulse.z); } data.positions[this.m_indexA].a = aA; data.positions[this.m_indexB].a = aB; return positionError <= b2_linearSlop && angularError <= b2_angularSlop; }; b2WeldJoint.prototype.GetAnchorA = function(out) { return this.m_bodyA.GetWorldPoint(this.m_localAnchorA, out); }; b2WeldJoint.prototype.GetAnchorB = function(out) { return this.m_bodyB.GetWorldPoint(this.m_localAnchorB, out); }; b2WeldJoint.prototype.GetReactionForce = function(inv_dt, out) { out.x = inv_dt * this.m_impulse.x; out.y = inv_dt * this.m_impulse.y; return out; }; b2WeldJoint.prototype.GetReactionTorque = function(inv_dt) { return inv_dt * this.m_impulse.z; }; b2WeldJoint.prototype.GetLocalAnchorA = function() { return this.m_localAnchorA; }; b2WeldJoint.prototype.GetLocalAnchorB = function() { return this.m_localAnchorB; }; b2WeldJoint.prototype.GetReferenceAngle = function() { return this.m_referenceAngle; }; b2WeldJoint.prototype.SetFrequency = function(hz) { this.m_frequencyHz = hz; }; b2WeldJoint.prototype.GetFrequency = function() { return this.m_frequencyHz; }; b2WeldJoint.prototype.SetDampingRatio = function(ratio) { this.m_dampingRatio = ratio; }; b2WeldJoint.prototype.GetDampingRatio = function() { return this.m_dampingRatio; }; b2WeldJoint.prototype.Dump = function(log) { var indexA = this.m_bodyA.m_islandIndex; var indexB = this.m_bodyB.m_islandIndex; log(" const jd: b2WeldJointDef = new b2WeldJointDef();\n"); log(" jd.bodyA = bodies[%d];\n", indexA); log(" jd.bodyB = bodies[%d];\n", indexB); log(" jd.collideConnected = %s;\n", this.m_collideConnected ? "true" : "false"); log(" jd.localAnchorA.Set(%.15f, %.15f);\n", this.m_localAnchorA.x, this.m_localAnchorA.y); log(" jd.localAnchorB.Set(%.15f, %.15f);\n", this.m_localAnchorB.x, this.m_localAnchorB.y); log(" jd.referenceAngle = %.15f;\n", this.m_referenceAngle); log(" jd.frequencyHz = %.15f;\n", this.m_frequencyHz); log(" jd.dampingRatio = %.15f;\n", this.m_dampingRatio); log(" joints[%d] = this.m_world.CreateJoint(jd);\n", this.m_index); }; b2WeldJoint.InitVelocityConstraints_s_P = new b2Vec2(); b2WeldJoint.SolveVelocityConstraints_s_Cdot1 = new b2Vec2(); b2WeldJoint.SolveVelocityConstraints_s_impulse1 = new b2Vec2(); b2WeldJoint.SolveVelocityConstraints_s_impulse = new b2Vec3(); b2WeldJoint.SolveVelocityConstraints_s_P = new b2Vec2(); b2WeldJoint.SolvePositionConstraints_s_C1 = new b2Vec2(); b2WeldJoint.SolvePositionConstraints_s_P = new b2Vec2(); b2WeldJoint.SolvePositionConstraints_s_impulse = new b2Vec3(); return b2WeldJoint; })(b2Joint); var b2WheelJointDef = (function(_super) { __extends(b2WheelJointDef, _super); function b2WheelJointDef() { var _this = _super.call(this, exports.b2JointType.e_wheelJoint) || this; _this.localAnchorA = new b2Vec2(0, 0); _this.localAnchorB = new b2Vec2(0, 0); _this.localAxisA = new b2Vec2(1, 0); _this.enableMotor = false; _this.maxMotorTorque = 0; _this.motorSpeed = 0; _this.frequencyHz = 2; _this.dampingRatio = .7; return _this; } b2WheelJointDef.prototype.Initialize = function(bA, bB, anchor, axis) { this.bodyA = bA; this.bodyB = bB; this.bodyA.GetLocalPoint(anchor, this.localAnchorA); this.bodyB.GetLocalPoint(anchor, this.localAnchorB); this.bodyA.GetLocalVector(axis, this.localAxisA); }; return b2WheelJointDef; })(b2JointDef); var b2WheelJoint = (function(_super) { __extends(b2WheelJoint, _super); function b2WheelJoint(def) { var _this = _super.call(this, def) || this; _this.m_frequencyHz = 0; _this.m_dampingRatio = 0; _this.m_localAnchorA = new b2Vec2(); _this.m_localAnchorB = new b2Vec2(); _this.m_localXAxisA = new b2Vec2(); _this.m_localYAxisA = new b2Vec2(); _this.m_impulse = 0; _this.m_motorImpulse = 0; _this.m_springImpulse = 0; _this.m_maxMotorTorque = 0; _this.m_motorSpeed = 0; _this.m_enableMotor = false; _this.m_indexA = 0; _this.m_indexB = 0; _this.m_localCenterA = new b2Vec2(); _this.m_localCenterB = new b2Vec2(); _this.m_invMassA = 0; _this.m_invMassB = 0; _this.m_invIA = 0; _this.m_invIB = 0; _this.m_ax = new b2Vec2(); _this.m_ay = new b2Vec2(); _this.m_sAx = 0; _this.m_sBx = 0; _this.m_sAy = 0; _this.m_sBy = 0; _this.m_mass = 0; _this.m_motorMass = 0; _this.m_springMass = 0; _this.m_bias = 0; _this.m_gamma = 0; _this.m_qA = new b2Rot(); _this.m_qB = new b2Rot(); _this.m_lalcA = new b2Vec2(); _this.m_lalcB = new b2Vec2(); _this.m_rA = new b2Vec2(); _this.m_rB = new b2Vec2(); _this.m_frequencyHz = b2Maybe(def.frequencyHz, 2); _this.m_dampingRatio = b2Maybe(def.dampingRatio, .7); _this.m_localAnchorA.Copy(b2Maybe(def.localAnchorA, b2Vec2.ZERO)); _this.m_localAnchorB.Copy(b2Maybe(def.localAnchorB, b2Vec2.ZERO)); _this.m_localXAxisA.Copy(b2Maybe(def.localAxisA, b2Vec2.UNITX)); b2Vec2.CrossOneV(_this.m_localXAxisA, _this.m_localYAxisA); _this.m_maxMotorTorque = b2Maybe(def.maxMotorTorque, 0); _this.m_motorSpeed = b2Maybe(def.motorSpeed, 0); _this.m_enableMotor = b2Maybe(def.enableMotor, false); _this.m_ax.SetZero(); _this.m_ay.SetZero(); return _this; } b2WheelJoint.prototype.GetMotorSpeed = function() { return this.m_motorSpeed; }; b2WheelJoint.prototype.GetMaxMotorTorque = function() { return this.m_maxMotorTorque; }; b2WheelJoint.prototype.SetSpringFrequencyHz = function(hz) { this.m_frequencyHz = hz; }; b2WheelJoint.prototype.GetSpringFrequencyHz = function() { return this.m_frequencyHz; }; b2WheelJoint.prototype.SetSpringDampingRatio = function(ratio) { this.m_dampingRatio = ratio; }; b2WheelJoint.prototype.GetSpringDampingRatio = function() { return this.m_dampingRatio; }; b2WheelJoint.prototype.InitVelocityConstraints = function(data) { this.m_indexA = this.m_bodyA.m_islandIndex; this.m_indexB = this.m_bodyB.m_islandIndex; this.m_localCenterA.Copy(this.m_bodyA.m_sweep.localCenter); this.m_localCenterB.Copy(this.m_bodyB.m_sweep.localCenter); this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var mA = this.m_invMassA, mB = this.m_invMassB; var iA = this.m_invIA, iB = this.m_invIB; var cA = data.positions[this.m_indexA].c; var aA = data.positions[this.m_indexA].a; var vA = data.velocities[this.m_indexA].v; var wA = data.velocities[this.m_indexA].w; var cB = data.positions[this.m_indexB].c; var aB = data.positions[this.m_indexB].a; var vB = data.velocities[this.m_indexB].v; var wB = data.velocities[this.m_indexB].w; var qA = this.m_qA.SetAngle(aA), qB = this.m_qB.SetAngle(aB); b2Vec2.SubVV(this.m_localAnchorA, this.m_localCenterA, this.m_lalcA); var rA = b2Rot.MulRV(qA, this.m_lalcA, this.m_rA); b2Vec2.SubVV(this.m_localAnchorB, this.m_localCenterB, this.m_lalcB); var rB = b2Rot.MulRV(qB, this.m_lalcB, this.m_rB); var d = b2Vec2.SubVV(b2Vec2.AddVV(cB, rB, b2Vec2.s_t0), b2Vec2.AddVV(cA, rA, b2Vec2.s_t1), b2WheelJoint.InitVelocityConstraints_s_d); b2Rot.MulRV(qA, this.m_localYAxisA, this.m_ay); this.m_sAy = b2Vec2.CrossVV(b2Vec2.AddVV(d, rA, b2Vec2.s_t0), this.m_ay); this.m_sBy = b2Vec2.CrossVV(rB, this.m_ay); this.m_mass = mA + mB + iA * this.m_sAy * this.m_sAy + iB * this.m_sBy * this.m_sBy; this.m_mass > 0 && (this.m_mass = 1 / this.m_mass); this.m_springMass = 0; this.m_bias = 0; this.m_gamma = 0; if (this.m_frequencyHz > 0) { b2Rot.MulRV(qA, this.m_localXAxisA, this.m_ax); this.m_sAx = b2Vec2.CrossVV(b2Vec2.AddVV(d, rA, b2Vec2.s_t0), this.m_ax); this.m_sBx = b2Vec2.CrossVV(rB, this.m_ax); var invMass = mA + mB + iA * this.m_sAx * this.m_sAx + iB * this.m_sBx * this.m_sBx; if (invMass > 0) { this.m_springMass = 1 / invMass; var C = b2Vec2.DotVV(d, this.m_ax); var omega = 2 * b2_pi * this.m_frequencyHz; var damp = 2 * this.m_springMass * this.m_dampingRatio * omega; var k = this.m_springMass * omega * omega; var h = data.step.dt; this.m_gamma = h * (damp + h * k); this.m_gamma > 0 && (this.m_gamma = 1 / this.m_gamma); this.m_bias = C * h * k * this.m_gamma; this.m_springMass = invMass + this.m_gamma; this.m_springMass > 0 && (this.m_springMass = 1 / this.m_springMass); } } else this.m_springImpulse = 0; if (this.m_enableMotor) { this.m_motorMass = iA + iB; this.m_motorMass > 0 && (this.m_motorMass = 1 / this.m_motorMass); } else { this.m_motorMass = 0; this.m_motorImpulse = 0; } if (data.step.warmStarting) { this.m_impulse *= data.step.dtRatio; this.m_springImpulse *= data.step.dtRatio; this.m_motorImpulse *= data.step.dtRatio; var P = b2Vec2.AddVV(b2Vec2.MulSV(this.m_impulse, this.m_ay, b2Vec2.s_t0), b2Vec2.MulSV(this.m_springImpulse, this.m_ax, b2Vec2.s_t1), b2WheelJoint.InitVelocityConstraints_s_P); var LA = this.m_impulse * this.m_sAy + this.m_springImpulse * this.m_sAx + this.m_motorImpulse; var LB = this.m_impulse * this.m_sBy + this.m_springImpulse * this.m_sBx + this.m_motorImpulse; vA.SelfMulSub(this.m_invMassA, P); wA -= this.m_invIA * LA; vB.SelfMulAdd(this.m_invMassB, P); wB += this.m_invIB * LB; } else { this.m_impulse = 0; this.m_springImpulse = 0; this.m_motorImpulse = 0; } data.velocities[this.m_indexA].w = wA; data.velocities[this.m_indexB].w = wB; }; b2WheelJoint.prototype.SolveVelocityConstraints = function(data) { var mA = this.m_invMassA, mB = this.m_invMassB; var iA = this.m_invIA, iB = this.m_invIB; var vA = data.velocities[this.m_indexA].v; var wA = data.velocities[this.m_indexA].w; var vB = data.velocities[this.m_indexB].v; var wB = data.velocities[this.m_indexB].w; var Cdot = b2Vec2.DotVV(this.m_ax, b2Vec2.SubVV(vB, vA, b2Vec2.s_t0)) + this.m_sBx * wB - this.m_sAx * wA; var impulse = -this.m_springMass * (Cdot + this.m_bias + this.m_gamma * this.m_springImpulse); this.m_springImpulse += impulse; var P = b2Vec2.MulSV(impulse, this.m_ax, b2WheelJoint.SolveVelocityConstraints_s_P); var LA = impulse * this.m_sAx; var LB = impulse * this.m_sBx; vA.SelfMulSub(mA, P); wA -= iA * LA; vB.SelfMulAdd(mB, P); wB += iB * LB; var Cdot = wB - wA - this.m_motorSpeed; var impulse = -this.m_motorMass * Cdot; var oldImpulse = this.m_motorImpulse; var maxImpulse = data.step.dt * this.m_maxMotorTorque; this.m_motorImpulse = b2Clamp(this.m_motorImpulse + impulse, -maxImpulse, maxImpulse); impulse = this.m_motorImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; var Cdot = b2Vec2.DotVV(this.m_ay, b2Vec2.SubVV(vB, vA, b2Vec2.s_t0)) + this.m_sBy * wB - this.m_sAy * wA; var impulse = -this.m_mass * Cdot; this.m_impulse += impulse; var P = b2Vec2.MulSV(impulse, this.m_ay, b2WheelJoint.SolveVelocityConstraints_s_P); var LA = impulse * this.m_sAy; var LB = impulse * this.m_sBy; vA.SelfMulSub(mA, P); wA -= iA * LA; vB.SelfMulAdd(mB, P); wB += iB * LB; data.velocities[this.m_indexA].w = wA; data.velocities[this.m_indexB].w = wB; }; b2WheelJoint.prototype.SolvePositionConstraints = function(data) { var cA = data.positions[this.m_indexA].c; var aA = data.positions[this.m_indexA].a; var cB = data.positions[this.m_indexB].c; var aB = data.positions[this.m_indexB].a; var qA = this.m_qA.SetAngle(aA), qB = this.m_qB.SetAngle(aB); b2Vec2.SubVV(this.m_localAnchorA, this.m_localCenterA, this.m_lalcA); var rA = b2Rot.MulRV(qA, this.m_lalcA, this.m_rA); b2Vec2.SubVV(this.m_localAnchorB, this.m_localCenterB, this.m_lalcB); var rB = b2Rot.MulRV(qB, this.m_lalcB, this.m_rB); var d = b2Vec2.AddVV(b2Vec2.SubVV(cB, cA, b2Vec2.s_t0), b2Vec2.SubVV(rB, rA, b2Vec2.s_t1), b2WheelJoint.SolvePositionConstraints_s_d); var ay = b2Rot.MulRV(qA, this.m_localYAxisA, this.m_ay); var sAy = b2Vec2.CrossVV(b2Vec2.AddVV(d, rA, b2Vec2.s_t0), ay); var sBy = b2Vec2.CrossVV(rB, ay); var C = b2Vec2.DotVV(d, this.m_ay); var k = this.m_invMassA + this.m_invMassB + this.m_invIA * this.m_sAy * this.m_sAy + this.m_invIB * this.m_sBy * this.m_sBy; var impulse; impulse = 0 !== k ? -C / k : 0; var P = b2Vec2.MulSV(impulse, ay, b2WheelJoint.SolvePositionConstraints_s_P); var LA = impulse * sAy; var LB = impulse * sBy; cA.SelfMulSub(this.m_invMassA, P); aA -= this.m_invIA * LA; cB.SelfMulAdd(this.m_invMassB, P); aB += this.m_invIB * LB; data.positions[this.m_indexA].a = aA; data.positions[this.m_indexB].a = aB; return b2Abs(C) <= b2_linearSlop; }; b2WheelJoint.prototype.GetDefinition = function(def) { return def; }; b2WheelJoint.prototype.GetAnchorA = function(out) { return this.m_bodyA.GetWorldPoint(this.m_localAnchorA, out); }; b2WheelJoint.prototype.GetAnchorB = function(out) { return this.m_bodyB.GetWorldPoint(this.m_localAnchorB, out); }; b2WheelJoint.prototype.GetReactionForce = function(inv_dt, out) { out.x = inv_dt * (this.m_impulse * this.m_ay.x + this.m_springImpulse * this.m_ax.x); out.y = inv_dt * (this.m_impulse * this.m_ay.y + this.m_springImpulse * this.m_ax.y); return out; }; b2WheelJoint.prototype.GetReactionTorque = function(inv_dt) { return inv_dt * this.m_motorImpulse; }; b2WheelJoint.prototype.GetLocalAnchorA = function() { return this.m_localAnchorA; }; b2WheelJoint.prototype.GetLocalAnchorB = function() { return this.m_localAnchorB; }; b2WheelJoint.prototype.GetLocalAxisA = function() { return this.m_localXAxisA; }; b2WheelJoint.prototype.GetJointTranslation = function() { return this.GetPrismaticJointTranslation(); }; b2WheelJoint.prototype.GetJointLinearSpeed = function() { return this.GetPrismaticJointSpeed(); }; b2WheelJoint.prototype.GetJointAngle = function() { return this.GetRevoluteJointAngle(); }; b2WheelJoint.prototype.GetJointAngularSpeed = function() { return this.GetRevoluteJointSpeed(); }; b2WheelJoint.prototype.GetPrismaticJointTranslation = function() { var bA = this.m_bodyA; var bB = this.m_bodyB; var pA = bA.GetWorldPoint(this.m_localAnchorA, new b2Vec2()); var pB = bB.GetWorldPoint(this.m_localAnchorB, new b2Vec2()); var d = b2Vec2.SubVV(pB, pA, new b2Vec2()); var axis = bA.GetWorldVector(this.m_localXAxisA, new b2Vec2()); var translation = b2Vec2.DotVV(d, axis); return translation; }; b2WheelJoint.prototype.GetPrismaticJointSpeed = function() { var bA = this.m_bodyA; var bB = this.m_bodyB; b2Vec2.SubVV(this.m_localAnchorA, bA.m_sweep.localCenter, this.m_lalcA); var rA = b2Rot.MulRV(bA.m_xf.q, this.m_lalcA, this.m_rA); b2Vec2.SubVV(this.m_localAnchorB, bB.m_sweep.localCenter, this.m_lalcB); var rB = b2Rot.MulRV(bB.m_xf.q, this.m_lalcB, this.m_rB); var pA = b2Vec2.AddVV(bA.m_sweep.c, rA, b2Vec2.s_t0); var pB = b2Vec2.AddVV(bB.m_sweep.c, rB, b2Vec2.s_t1); var d = b2Vec2.SubVV(pB, pA, b2Vec2.s_t2); var axis = bA.GetWorldVector(this.m_localXAxisA, new b2Vec2()); var vA = bA.m_linearVelocity; var vB = bB.m_linearVelocity; var wA = bA.m_angularVelocity; var wB = bB.m_angularVelocity; var speed = b2Vec2.DotVV(d, b2Vec2.CrossSV(wA, axis, b2Vec2.s_t0)) + b2Vec2.DotVV(axis, b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB, wB, rB, b2Vec2.s_t0), b2Vec2.AddVCrossSV(vA, wA, rA, b2Vec2.s_t1), b2Vec2.s_t0)); return speed; }; b2WheelJoint.prototype.GetRevoluteJointAngle = function() { return this.m_bodyB.m_sweep.a - this.m_bodyA.m_sweep.a; }; b2WheelJoint.prototype.GetRevoluteJointSpeed = function() { var wA = this.m_bodyA.m_angularVelocity; var wB = this.m_bodyB.m_angularVelocity; return wB - wA; }; b2WheelJoint.prototype.IsMotorEnabled = function() { return this.m_enableMotor; }; b2WheelJoint.prototype.EnableMotor = function(flag) { if (flag !== this.m_enableMotor) { this.m_bodyA.SetAwake(true); this.m_bodyB.SetAwake(true); this.m_enableMotor = flag; } }; b2WheelJoint.prototype.SetMotorSpeed = function(speed) { if (speed !== this.m_motorSpeed) { this.m_bodyA.SetAwake(true); this.m_bodyB.SetAwake(true); this.m_motorSpeed = speed; } }; b2WheelJoint.prototype.SetMaxMotorTorque = function(force) { if (force !== this.m_maxMotorTorque) { this.m_bodyA.SetAwake(true); this.m_bodyB.SetAwake(true); this.m_maxMotorTorque = force; } }; b2WheelJoint.prototype.GetMotorTorque = function(inv_dt) { return inv_dt * this.m_motorImpulse; }; b2WheelJoint.prototype.Dump = function(log) { var indexA = this.m_bodyA.m_islandIndex; var indexB = this.m_bodyB.m_islandIndex; log(" const jd: b2WheelJointDef = new b2WheelJointDef();\n"); log(" jd.bodyA = bodies[%d];\n", indexA); log(" jd.bodyB = bodies[%d];\n", indexB); log(" jd.collideConnected = %s;\n", this.m_collideConnected ? "true" : "false"); log(" jd.localAnchorA.Set(%.15f, %.15f);\n", this.m_localAnchorA.x, this.m_localAnchorA.y); log(" jd.localAnchorB.Set(%.15f, %.15f);\n", this.m_localAnchorB.x, this.m_localAnchorB.y); log(" jd.localAxisA.Set(%.15f, %.15f);\n", this.m_localXAxisA.x, this.m_localXAxisA.y); log(" jd.enableMotor = %s;\n", this.m_enableMotor ? "true" : "false"); log(" jd.motorSpeed = %.15f;\n", this.m_motorSpeed); log(" jd.maxMotorTorque = %.15f;\n", this.m_maxMotorTorque); log(" jd.frequencyHz = %.15f;\n", this.m_frequencyHz); log(" jd.dampingRatio = %.15f;\n", this.m_dampingRatio); log(" joints[%d] = this.m_world.CreateJoint(jd);\n", this.m_index); }; b2WheelJoint.InitVelocityConstraints_s_d = new b2Vec2(); b2WheelJoint.InitVelocityConstraints_s_P = new b2Vec2(); b2WheelJoint.SolveVelocityConstraints_s_P = new b2Vec2(); b2WheelJoint.SolvePositionConstraints_s_d = new b2Vec2(); b2WheelJoint.SolvePositionConstraints_s_P = new b2Vec2(); return b2WheelJoint; })(b2Joint); function b2MixFriction(friction1, friction2) { return b2Sqrt(friction1 * friction2); } function b2MixRestitution(restitution1, restitution2) { return restitution1 > restitution2 ? restitution1 : restitution2; } var b2ContactEdge = (function() { function b2ContactEdge(contact) { this.prev = null; this.next = null; this.contact = contact; } return b2ContactEdge; })(); var b2Contact = (function() { function b2Contact() { this.m_islandFlag = false; this.m_touchingFlag = false; this.m_enabledFlag = false; this.m_filterFlag = false; this.m_bulletHitFlag = false; this.m_toiFlag = false; this.m_prev = null; this.m_next = null; this.m_indexA = 0; this.m_indexB = 0; this.m_manifold = new b2Manifold(); this.m_toiCount = 0; this.m_toi = 0; this.m_friction = 0; this.m_restitution = 0; this.m_tangentSpeed = 0; this.m_oldManifold = new b2Manifold(); this.m_nodeA = new b2ContactEdge(this); this.m_nodeB = new b2ContactEdge(this); } b2Contact.prototype.GetManifold = function() { return this.m_manifold; }; b2Contact.prototype.GetWorldManifold = function(worldManifold) { var bodyA = this.m_fixtureA.GetBody(); var bodyB = this.m_fixtureB.GetBody(); var shapeA = this.m_fixtureA.GetShape(); var shapeB = this.m_fixtureB.GetShape(); worldManifold.Initialize(this.m_manifold, bodyA.GetTransform(), shapeA.m_radius, bodyB.GetTransform(), shapeB.m_radius); }; b2Contact.prototype.IsTouching = function() { return this.m_touchingFlag; }; b2Contact.prototype.SetEnabled = function(flag) { this.m_enabledFlag = flag; }; b2Contact.prototype.IsEnabled = function() { return this.m_enabledFlag; }; b2Contact.prototype.GetNext = function() { return this.m_next; }; b2Contact.prototype.GetFixtureA = function() { return this.m_fixtureA; }; b2Contact.prototype.GetChildIndexA = function() { return this.m_indexA; }; b2Contact.prototype.GetFixtureB = function() { return this.m_fixtureB; }; b2Contact.prototype.GetChildIndexB = function() { return this.m_indexB; }; b2Contact.prototype.FlagForFiltering = function() { this.m_filterFlag = true; }; b2Contact.prototype.SetFriction = function(friction) { this.m_friction = friction; }; b2Contact.prototype.GetFriction = function() { return this.m_friction; }; b2Contact.prototype.ResetFriction = function() { this.m_friction = b2MixFriction(this.m_fixtureA.m_friction, this.m_fixtureB.m_friction); }; b2Contact.prototype.SetRestitution = function(restitution) { this.m_restitution = restitution; }; b2Contact.prototype.GetRestitution = function() { return this.m_restitution; }; b2Contact.prototype.ResetRestitution = function() { this.m_restitution = b2MixRestitution(this.m_fixtureA.m_restitution, this.m_fixtureB.m_restitution); }; b2Contact.prototype.SetTangentSpeed = function(speed) { this.m_tangentSpeed = speed; }; b2Contact.prototype.GetTangentSpeed = function() { return this.m_tangentSpeed; }; b2Contact.prototype.Reset = function(fixtureA, indexA, fixtureB, indexB) { this.m_islandFlag = false; this.m_touchingFlag = false; this.m_enabledFlag = true; this.m_filterFlag = false; this.m_bulletHitFlag = false; this.m_toiFlag = false; this.m_fixtureA = fixtureA; this.m_fixtureB = fixtureB; this.m_indexA = indexA; this.m_indexB = indexB; this.m_manifold.pointCount = 0; this.m_prev = null; this.m_next = null; delete this.m_nodeA.contact; this.m_nodeA.prev = null; this.m_nodeA.next = null; delete this.m_nodeA.other; delete this.m_nodeB.contact; this.m_nodeB.prev = null; this.m_nodeB.next = null; delete this.m_nodeB.other; this.m_toiCount = 0; this.m_friction = b2MixFriction(this.m_fixtureA.m_friction, this.m_fixtureB.m_friction); this.m_restitution = b2MixRestitution(this.m_fixtureA.m_restitution, this.m_fixtureB.m_restitution); }; b2Contact.prototype.Update = function(listener) { var tManifold = this.m_oldManifold; this.m_oldManifold = this.m_manifold; this.m_manifold = tManifold; this.m_enabledFlag = true; var touching = false; var wasTouching = this.m_touchingFlag; var sensorA = this.m_fixtureA.IsSensor(); var sensorB = this.m_fixtureB.IsSensor(); var sensor = sensorA || sensorB; var bodyA = this.m_fixtureA.GetBody(); var bodyB = this.m_fixtureB.GetBody(); var xfA = bodyA.GetTransform(); var xfB = bodyB.GetTransform(); if (sensor) { var shapeA = this.m_fixtureA.GetShape(); var shapeB = this.m_fixtureB.GetShape(); touching = b2TestOverlapShape(shapeA, this.m_indexA, shapeB, this.m_indexB, xfA, xfB); this.m_manifold.pointCount = 0; } else { this.Evaluate(this.m_manifold, xfA, xfB); touching = this.m_manifold.pointCount > 0; for (var i = 0; i < this.m_manifold.pointCount; ++i) { var mp2 = this.m_manifold.points[i]; mp2.normalImpulse = 0; mp2.tangentImpulse = 0; var id2 = mp2.id; for (var j = 0; j < this.m_oldManifold.pointCount; ++j) { var mp1 = this.m_oldManifold.points[j]; if (mp1.id.key === id2.key) { mp2.normalImpulse = mp1.normalImpulse; mp2.tangentImpulse = mp1.tangentImpulse; break; } } } if (touching !== wasTouching) { bodyA.SetAwake(true); bodyB.SetAwake(true); } } this.m_touchingFlag = touching; !wasTouching && touching && listener && listener.BeginContact(this); wasTouching && !touching && listener && listener.EndContact(this); !sensor && touching && listener && listener.PreSolve(this, this.m_oldManifold); }; b2Contact.prototype.ComputeTOI = function(sweepA, sweepB) { var input = b2Contact.ComputeTOI_s_input; input.proxyA.SetShape(this.m_fixtureA.GetShape(), this.m_indexA); input.proxyB.SetShape(this.m_fixtureB.GetShape(), this.m_indexB); input.sweepA.Copy(sweepA); input.sweepB.Copy(sweepB); input.tMax = b2_linearSlop; var output = b2Contact.ComputeTOI_s_output; b2TimeOfImpact(output, input); return output.t; }; b2Contact.ComputeTOI_s_input = new b2TOIInput(); b2Contact.ComputeTOI_s_output = new b2TOIOutput(); return b2Contact; })(); var b2CircleContact = (function(_super) { __extends(b2CircleContact, _super); function b2CircleContact() { return _super.call(this) || this; } b2CircleContact.Create = function(allocator) { return new b2CircleContact(); }; b2CircleContact.Destroy = function(contact, allocator) {}; b2CircleContact.prototype.Reset = function(fixtureA, indexA, fixtureB, indexB) { _super.prototype.Reset.call(this, fixtureA, indexA, fixtureB, indexB); }; b2CircleContact.prototype.Evaluate = function(manifold, xfA, xfB) { var shapeA = this.m_fixtureA.GetShape(); var shapeB = this.m_fixtureB.GetShape(); b2CollideCircles(manifold, shapeA, xfA, shapeB, xfB); }; return b2CircleContact; })(b2Contact); var b2PolygonContact = (function(_super) { __extends(b2PolygonContact, _super); function b2PolygonContact() { return _super.call(this) || this; } b2PolygonContact.Create = function(allocator) { return new b2PolygonContact(); }; b2PolygonContact.Destroy = function(contact, allocator) {}; b2PolygonContact.prototype.Reset = function(fixtureA, indexA, fixtureB, indexB) { _super.prototype.Reset.call(this, fixtureA, indexA, fixtureB, indexB); }; b2PolygonContact.prototype.Evaluate = function(manifold, xfA, xfB) { var shapeA = this.m_fixtureA.GetShape(); var shapeB = this.m_fixtureB.GetShape(); b2CollidePolygons(manifold, shapeA, xfA, shapeB, xfB); }; return b2PolygonContact; })(b2Contact); var b2PolygonAndCircleContact = (function(_super) { __extends(b2PolygonAndCircleContact, _super); function b2PolygonAndCircleContact() { return _super.call(this) || this; } b2PolygonAndCircleContact.Create = function(allocator) { return new b2PolygonAndCircleContact(); }; b2PolygonAndCircleContact.Destroy = function(contact, allocator) {}; b2PolygonAndCircleContact.prototype.Reset = function(fixtureA, indexA, fixtureB, indexB) { _super.prototype.Reset.call(this, fixtureA, indexA, fixtureB, indexB); }; b2PolygonAndCircleContact.prototype.Evaluate = function(manifold, xfA, xfB) { var shapeA = this.m_fixtureA.GetShape(); var shapeB = this.m_fixtureB.GetShape(); b2CollidePolygonAndCircle(manifold, shapeA, xfA, shapeB, xfB); }; return b2PolygonAndCircleContact; })(b2Contact); var b2EdgeAndCircleContact = (function(_super) { __extends(b2EdgeAndCircleContact, _super); function b2EdgeAndCircleContact() { return _super.call(this) || this; } b2EdgeAndCircleContact.Create = function(allocator) { return new b2EdgeAndCircleContact(); }; b2EdgeAndCircleContact.Destroy = function(contact, allocator) {}; b2EdgeAndCircleContact.prototype.Reset = function(fixtureA, indexA, fixtureB, indexB) { _super.prototype.Reset.call(this, fixtureA, indexA, fixtureB, indexB); }; b2EdgeAndCircleContact.prototype.Evaluate = function(manifold, xfA, xfB) { var shapeA = this.m_fixtureA.GetShape(); var shapeB = this.m_fixtureB.GetShape(); b2CollideEdgeAndCircle(manifold, shapeA, xfA, shapeB, xfB); }; return b2EdgeAndCircleContact; })(b2Contact); var b2EdgeAndPolygonContact = (function(_super) { __extends(b2EdgeAndPolygonContact, _super); function b2EdgeAndPolygonContact() { return _super.call(this) || this; } b2EdgeAndPolygonContact.Create = function(allocator) { return new b2EdgeAndPolygonContact(); }; b2EdgeAndPolygonContact.Destroy = function(contact, allocator) {}; b2EdgeAndPolygonContact.prototype.Reset = function(fixtureA, indexA, fixtureB, indexB) { _super.prototype.Reset.call(this, fixtureA, indexA, fixtureB, indexB); }; b2EdgeAndPolygonContact.prototype.Evaluate = function(manifold, xfA, xfB) { var shapeA = this.m_fixtureA.GetShape(); var shapeB = this.m_fixtureB.GetShape(); b2CollideEdgeAndPolygon(manifold, shapeA, xfA, shapeB, xfB); }; return b2EdgeAndPolygonContact; })(b2Contact); var b2ChainAndCircleContact = (function(_super) { __extends(b2ChainAndCircleContact, _super); function b2ChainAndCircleContact() { return _super.call(this) || this; } b2ChainAndCircleContact.Create = function(allocator) { return new b2ChainAndCircleContact(); }; b2ChainAndCircleContact.Destroy = function(contact, allocator) {}; b2ChainAndCircleContact.prototype.Reset = function(fixtureA, indexA, fixtureB, indexB) { _super.prototype.Reset.call(this, fixtureA, indexA, fixtureB, indexB); }; b2ChainAndCircleContact.prototype.Evaluate = function(manifold, xfA, xfB) { var shapeA = this.m_fixtureA.GetShape(); var shapeB = this.m_fixtureB.GetShape(); var chain = shapeA; var edge = b2ChainAndCircleContact.Evaluate_s_edge; chain.GetChildEdge(edge, this.m_indexA); b2CollideEdgeAndCircle(manifold, edge, xfA, shapeB, xfB); }; b2ChainAndCircleContact.Evaluate_s_edge = new b2EdgeShape(); return b2ChainAndCircleContact; })(b2Contact); var b2ChainAndPolygonContact = (function(_super) { __extends(b2ChainAndPolygonContact, _super); function b2ChainAndPolygonContact() { return _super.call(this) || this; } b2ChainAndPolygonContact.Create = function(allocator) { return new b2ChainAndPolygonContact(); }; b2ChainAndPolygonContact.Destroy = function(contact, allocator) {}; b2ChainAndPolygonContact.prototype.Reset = function(fixtureA, indexA, fixtureB, indexB) { _super.prototype.Reset.call(this, fixtureA, indexA, fixtureB, indexB); }; b2ChainAndPolygonContact.prototype.Evaluate = function(manifold, xfA, xfB) { var shapeA = this.m_fixtureA.GetShape(); var shapeB = this.m_fixtureB.GetShape(); var chain = shapeA; var edge = b2ChainAndPolygonContact.Evaluate_s_edge; chain.GetChildEdge(edge, this.m_indexA); b2CollideEdgeAndPolygon(manifold, edge, xfA, shapeB, xfB); }; b2ChainAndPolygonContact.Evaluate_s_edge = new b2EdgeShape(); return b2ChainAndPolygonContact; })(b2Contact); var b2ContactRegister = (function() { function b2ContactRegister() { this.createFcn = null; this.destroyFcn = null; this.primary = false; } return b2ContactRegister; })(); var b2ContactFactory = (function() { function b2ContactFactory(allocator) { this.m_allocator = null; this.m_allocator = allocator; this.InitializeRegisters(); } b2ContactFactory.prototype.AddType = function(createFcn, destroyFcn, type1, type2) { var _this = this; var pool = b2MakeArray(256, (function(i) { return createFcn(_this.m_allocator); })); function poolCreateFcn(allocator) { return pool.pop() || createFcn(allocator); } function poolDestroyFcn(contact, allocator) { pool.push(contact); } this.m_registers[type1][type2].createFcn = poolCreateFcn; this.m_registers[type1][type2].destroyFcn = poolDestroyFcn; this.m_registers[type1][type2].primary = true; if (type1 !== type2) { this.m_registers[type2][type1].createFcn = poolCreateFcn; this.m_registers[type2][type1].destroyFcn = poolDestroyFcn; this.m_registers[type2][type1].primary = false; } }; b2ContactFactory.prototype.InitializeRegisters = function() { this.m_registers = []; for (var i = 0; i < exports.b2ShapeType.e_shapeTypeCount; i++) { this.m_registers[i] = []; for (var j = 0; j < exports.b2ShapeType.e_shapeTypeCount; j++) this.m_registers[i][j] = new b2ContactRegister(); } this.AddType(b2CircleContact.Create, b2CircleContact.Destroy, exports.b2ShapeType.e_circleShape, exports.b2ShapeType.e_circleShape); this.AddType(b2PolygonAndCircleContact.Create, b2PolygonAndCircleContact.Destroy, exports.b2ShapeType.e_polygonShape, exports.b2ShapeType.e_circleShape); this.AddType(b2PolygonContact.Create, b2PolygonContact.Destroy, exports.b2ShapeType.e_polygonShape, exports.b2ShapeType.e_polygonShape); this.AddType(b2EdgeAndCircleContact.Create, b2EdgeAndCircleContact.Destroy, exports.b2ShapeType.e_edgeShape, exports.b2ShapeType.e_circleShape); this.AddType(b2EdgeAndPolygonContact.Create, b2EdgeAndPolygonContact.Destroy, exports.b2ShapeType.e_edgeShape, exports.b2ShapeType.e_polygonShape); this.AddType(b2ChainAndCircleContact.Create, b2ChainAndCircleContact.Destroy, exports.b2ShapeType.e_chainShape, exports.b2ShapeType.e_circleShape); this.AddType(b2ChainAndPolygonContact.Create, b2ChainAndPolygonContact.Destroy, exports.b2ShapeType.e_chainShape, exports.b2ShapeType.e_polygonShape); }; b2ContactFactory.prototype.Create = function(fixtureA, indexA, fixtureB, indexB) { var type1 = fixtureA.GetType(); var type2 = fixtureB.GetType(); var reg = this.m_registers[type1][type2]; if (reg.createFcn) { var c = reg.createFcn(this.m_allocator); reg.primary ? c.Reset(fixtureA, indexA, fixtureB, indexB) : c.Reset(fixtureB, indexB, fixtureA, indexA); return c; } return null; }; b2ContactFactory.prototype.Destroy = function(contact) { var fixtureA = contact.m_fixtureA; var fixtureB = contact.m_fixtureB; if (contact.m_manifold.pointCount > 0 && !fixtureA.IsSensor() && !fixtureB.IsSensor()) { fixtureA.GetBody().SetAwake(true); fixtureB.GetBody().SetAwake(true); } var typeA = fixtureA.GetType(); var typeB = fixtureB.GetType(); var reg = this.m_registers[typeA][typeB]; reg.destroyFcn && reg.destroyFcn(contact, this.m_allocator); }; return b2ContactFactory; })(); var b2DestructionListener = (function() { function b2DestructionListener() {} b2DestructionListener.prototype.SayGoodbyeJoint = function(joint) {}; b2DestructionListener.prototype.SayGoodbyeFixture = function(fixture) {}; b2DestructionListener.prototype.SayGoodbyeParticleGroup = function(group) {}; b2DestructionListener.prototype.SayGoodbyeParticle = function(system, index) {}; return b2DestructionListener; })(); var b2ContactFilter = (function() { function b2ContactFilter() {} b2ContactFilter.prototype.ShouldCollide = function(fixtureA, fixtureB) { var bodyA = fixtureA.GetBody(); var bodyB = fixtureB.GetBody(); if (bodyB.GetType() === exports.b2BodyType.b2_staticBody && bodyA.GetType() === exports.b2BodyType.b2_staticBody) return false; if (!bodyB.ShouldCollideConnected(bodyA)) return false; var filter1 = fixtureA.GetFilterData(); var filter2 = fixtureB.GetFilterData(); if (filter1.groupIndex === filter2.groupIndex && 0 !== filter1.groupIndex) return filter1.groupIndex > 0; var collide = 0 !== (filter1.maskBits & filter2.categoryBits) && 0 !== (filter1.categoryBits & filter2.maskBits); return collide; }; b2ContactFilter.prototype.ShouldCollideFixtureParticle = function(fixture, system, index) { return true; }; b2ContactFilter.prototype.ShouldCollideParticleParticle = function(system, indexA, indexB) { return true; }; b2ContactFilter.b2_defaultFilter = new b2ContactFilter(); return b2ContactFilter; })(); var b2ContactImpulse = (function() { function b2ContactImpulse() { this.normalImpulses = b2MakeNumberArray(b2_maxManifoldPoints); this.tangentImpulses = b2MakeNumberArray(b2_maxManifoldPoints); this.count = 0; } return b2ContactImpulse; })(); var b2ContactListener = (function() { function b2ContactListener() {} b2ContactListener.prototype.BeginContact = function(contact) {}; b2ContactListener.prototype.EndContact = function(contact) {}; b2ContactListener.prototype.BeginContactFixtureParticle = function(system, contact) {}; b2ContactListener.prototype.EndContactFixtureParticle = function(system, contact) {}; b2ContactListener.prototype.BeginContactParticleParticle = function(system, contact) {}; b2ContactListener.prototype.EndContactParticleParticle = function(system, contact) {}; b2ContactListener.prototype.PreSolve = function(contact, oldManifold) {}; b2ContactListener.prototype.PostSolve = function(contact, impulse) {}; b2ContactListener.b2_defaultListener = new b2ContactListener(); return b2ContactListener; })(); var b2QueryCallback = (function() { function b2QueryCallback() {} b2QueryCallback.prototype.ReportFixture = function(fixture) { return true; }; b2QueryCallback.prototype.ReportParticle = function(system, index) { return false; }; b2QueryCallback.prototype.ShouldQueryParticleSystem = function(system) { return true; }; return b2QueryCallback; })(); var b2RayCastCallback = (function() { function b2RayCastCallback() {} b2RayCastCallback.prototype.ReportFixture = function(fixture, point, normal, fraction) { return fraction; }; b2RayCastCallback.prototype.ReportParticle = function(system, index, point, normal, fraction) { return 0; }; b2RayCastCallback.prototype.ShouldQueryParticleSystem = function(system) { return true; }; return b2RayCastCallback; })(); var b2ContactManager = (function() { function b2ContactManager() { this.m_broadPhase = new b2BroadPhase(); this.m_contactList = null; this.m_contactCount = 0; this.m_contactFilter = b2ContactFilter.b2_defaultFilter; this.m_contactListener = b2ContactListener.b2_defaultListener; this.m_allocator = null; this.m_contactFactory = new b2ContactFactory(this.m_allocator); } b2ContactManager.prototype.AddPair = function(proxyA, proxyB) { var fixtureA = proxyA.fixture; var fixtureB = proxyB.fixture; var indexA = proxyA.childIndex; var indexB = proxyB.childIndex; var bodyA = fixtureA.GetBody(); var bodyB = fixtureB.GetBody(); if (bodyA === bodyB) return; var edge = bodyB.GetContactList(); while (edge) { if (edge.other === bodyA) { var fA = edge.contact.GetFixtureA(); var fB = edge.contact.GetFixtureB(); var iA = edge.contact.GetChildIndexA(); var iB = edge.contact.GetChildIndexB(); if (fA === fixtureA && fB === fixtureB && iA === indexA && iB === indexB) return; if (fA === fixtureB && fB === fixtureA && iA === indexB && iB === indexA) return; } edge = edge.next; } if (this.m_contactFilter && !this.m_contactFilter.ShouldCollide(fixtureA, fixtureB)) return; var c = this.m_contactFactory.Create(fixtureA, indexA, fixtureB, indexB); if (null === c) return; fixtureA = c.GetFixtureA(); fixtureB = c.GetFixtureB(); indexA = c.GetChildIndexA(); indexB = c.GetChildIndexB(); bodyA = fixtureA.m_body; bodyB = fixtureB.m_body; c.m_prev = null; c.m_next = this.m_contactList; null !== this.m_contactList && (this.m_contactList.m_prev = c); this.m_contactList = c; c.m_nodeA.contact = c; c.m_nodeA.other = bodyB; c.m_nodeA.prev = null; c.m_nodeA.next = bodyA.m_contactList; null !== bodyA.m_contactList && (bodyA.m_contactList.prev = c.m_nodeA); bodyA.m_contactList = c.m_nodeA; c.m_nodeB.contact = c; c.m_nodeB.other = bodyA; c.m_nodeB.prev = null; c.m_nodeB.next = bodyB.m_contactList; null !== bodyB.m_contactList && (bodyB.m_contactList.prev = c.m_nodeB); bodyB.m_contactList = c.m_nodeB; if (!fixtureA.IsSensor() && !fixtureB.IsSensor()) { bodyA.SetAwake(true); bodyB.SetAwake(true); } ++this.m_contactCount; }; b2ContactManager.prototype.FindNewContacts = function() { var _this = this; this.m_broadPhase.UpdatePairs((function(proxyA, proxyB) { _this.AddPair(proxyA, proxyB); })); }; b2ContactManager.prototype.Destroy = function(c) { var fixtureA = c.GetFixtureA(); var fixtureB = c.GetFixtureB(); var bodyA = fixtureA.GetBody(); var bodyB = fixtureB.GetBody(); this.m_contactListener && c.IsTouching() && this.m_contactListener.EndContact(c); c.m_prev && (c.m_prev.m_next = c.m_next); c.m_next && (c.m_next.m_prev = c.m_prev); c === this.m_contactList && (this.m_contactList = c.m_next); c.m_nodeA.prev && (c.m_nodeA.prev.next = c.m_nodeA.next); c.m_nodeA.next && (c.m_nodeA.next.prev = c.m_nodeA.prev); c.m_nodeA === bodyA.m_contactList && (bodyA.m_contactList = c.m_nodeA.next); c.m_nodeB.prev && (c.m_nodeB.prev.next = c.m_nodeB.next); c.m_nodeB.next && (c.m_nodeB.next.prev = c.m_nodeB.prev); c.m_nodeB === bodyB.m_contactList && (bodyB.m_contactList = c.m_nodeB.next); this.m_contactFactory.Destroy(c); --this.m_contactCount; }; b2ContactManager.prototype.Collide = function() { var c = this.m_contactList; while (c) { var fixtureA = c.GetFixtureA(); var fixtureB = c.GetFixtureB(); var indexA = c.GetChildIndexA(); var indexB = c.GetChildIndexB(); var bodyA = fixtureA.GetBody(); var bodyB = fixtureB.GetBody(); if (c.m_filterFlag) { if (this.m_contactFilter && !this.m_contactFilter.ShouldCollide(fixtureA, fixtureB)) { var cNuke = c; c = cNuke.m_next; this.Destroy(cNuke); continue; } c.m_filterFlag = false; } var activeA = bodyA.IsAwake() && bodyA.m_type !== exports.b2BodyType.b2_staticBody; var activeB = bodyB.IsAwake() && bodyB.m_type !== exports.b2BodyType.b2_staticBody; if (!activeA && !activeB) { c = c.m_next; continue; } var proxyA = fixtureA.m_proxies[indexA].treeNode; var proxyB = fixtureB.m_proxies[indexB].treeNode; var overlap = b2TestOverlapAABB(proxyA.aabb, proxyB.aabb); if (!overlap) { var cNuke = c; c = cNuke.m_next; this.Destroy(cNuke); continue; } c.Update(this.m_contactListener); c = c.m_next; } }; return b2ContactManager; })(); var b2Profile = (function() { function b2Profile() { this.step = 0; this.collide = 0; this.solve = 0; this.solveInit = 0; this.solveVelocity = 0; this.solvePosition = 0; this.broadphase = 0; this.solveTOI = 0; } b2Profile.prototype.Reset = function() { this.step = 0; this.collide = 0; this.solve = 0; this.solveInit = 0; this.solveVelocity = 0; this.solvePosition = 0; this.broadphase = 0; this.solveTOI = 0; return this; }; return b2Profile; })(); var b2TimeStep = (function() { function b2TimeStep() { this.dt = 0; this.inv_dt = 0; this.dtRatio = 0; this.velocityIterations = 0; this.positionIterations = 0; this.particleIterations = 0; this.warmStarting = false; } b2TimeStep.prototype.Copy = function(step) { this.dt = step.dt; this.inv_dt = step.inv_dt; this.dtRatio = step.dtRatio; this.positionIterations = step.positionIterations; this.velocityIterations = step.velocityIterations; this.particleIterations = step.particleIterations; this.warmStarting = step.warmStarting; return this; }; return b2TimeStep; })(); var b2Position = (function() { function b2Position() { this.c = new b2Vec2(); this.a = 0; } b2Position.MakeArray = function(length) { return b2MakeArray(length, (function(i) { return new b2Position(); })); }; return b2Position; })(); var b2Velocity = (function() { function b2Velocity() { this.v = new b2Vec2(); this.w = 0; } b2Velocity.MakeArray = function(length) { return b2MakeArray(length, (function(i) { return new b2Velocity(); })); }; return b2Velocity; })(); var b2SolverData = (function() { function b2SolverData() { this.step = new b2TimeStep(); } return b2SolverData; })(); var g_blockSolve = false; var b2VelocityConstraintPoint = (function() { function b2VelocityConstraintPoint() { this.rA = new b2Vec2(); this.rB = new b2Vec2(); this.normalImpulse = 0; this.tangentImpulse = 0; this.normalMass = 0; this.tangentMass = 0; this.velocityBias = 0; } b2VelocityConstraintPoint.MakeArray = function(length) { return b2MakeArray(length, (function(i) { return new b2VelocityConstraintPoint(); })); }; return b2VelocityConstraintPoint; })(); var b2ContactVelocityConstraint = (function() { function b2ContactVelocityConstraint() { this.points = b2VelocityConstraintPoint.MakeArray(b2_maxManifoldPoints); this.normal = new b2Vec2(); this.tangent = new b2Vec2(); this.normalMass = new b2Mat22(); this.K = new b2Mat22(); this.indexA = 0; this.indexB = 0; this.invMassA = 0; this.invMassB = 0; this.invIA = 0; this.invIB = 0; this.friction = 0; this.restitution = 0; this.tangentSpeed = 0; this.pointCount = 0; this.contactIndex = 0; } b2ContactVelocityConstraint.MakeArray = function(length) { return b2MakeArray(length, (function(i) { return new b2ContactVelocityConstraint(); })); }; return b2ContactVelocityConstraint; })(); var b2ContactPositionConstraint = (function() { function b2ContactPositionConstraint() { this.localPoints = b2Vec2.MakeArray(b2_maxManifoldPoints); this.localNormal = new b2Vec2(); this.localPoint = new b2Vec2(); this.indexA = 0; this.indexB = 0; this.invMassA = 0; this.invMassB = 0; this.localCenterA = new b2Vec2(); this.localCenterB = new b2Vec2(); this.invIA = 0; this.invIB = 0; this.type = exports.b2ManifoldType.e_unknown; this.radiusA = 0; this.radiusB = 0; this.pointCount = 0; } b2ContactPositionConstraint.MakeArray = function(length) { return b2MakeArray(length, (function(i) { return new b2ContactPositionConstraint(); })); }; return b2ContactPositionConstraint; })(); var b2ContactSolverDef = (function() { function b2ContactSolverDef() { this.step = new b2TimeStep(); this.count = 0; this.allocator = null; } return b2ContactSolverDef; })(); var b2PositionSolverManifold = (function() { function b2PositionSolverManifold() { this.normal = new b2Vec2(); this.point = new b2Vec2(); this.separation = 0; } b2PositionSolverManifold.prototype.Initialize = function(pc, xfA, xfB, index) { var pointA = b2PositionSolverManifold.Initialize_s_pointA; var pointB = b2PositionSolverManifold.Initialize_s_pointB; var planePoint = b2PositionSolverManifold.Initialize_s_planePoint; var clipPoint = b2PositionSolverManifold.Initialize_s_clipPoint; switch (pc.type) { case exports.b2ManifoldType.e_circles: b2Transform.MulXV(xfA, pc.localPoint, pointA); b2Transform.MulXV(xfB, pc.localPoints[0], pointB); b2Vec2.SubVV(pointB, pointA, this.normal).SelfNormalize(); b2Vec2.MidVV(pointA, pointB, this.point); this.separation = b2Vec2.DotVV(b2Vec2.SubVV(pointB, pointA, b2Vec2.s_t0), this.normal) - pc.radiusA - pc.radiusB; break; case exports.b2ManifoldType.e_faceA: b2Rot.MulRV(xfA.q, pc.localNormal, this.normal); b2Transform.MulXV(xfA, pc.localPoint, planePoint); b2Transform.MulXV(xfB, pc.localPoints[index], clipPoint); this.separation = b2Vec2.DotVV(b2Vec2.SubVV(clipPoint, planePoint, b2Vec2.s_t0), this.normal) - pc.radiusA - pc.radiusB; this.point.Copy(clipPoint); break; case exports.b2ManifoldType.e_faceB: b2Rot.MulRV(xfB.q, pc.localNormal, this.normal); b2Transform.MulXV(xfB, pc.localPoint, planePoint); b2Transform.MulXV(xfA, pc.localPoints[index], clipPoint); this.separation = b2Vec2.DotVV(b2Vec2.SubVV(clipPoint, planePoint, b2Vec2.s_t0), this.normal) - pc.radiusA - pc.radiusB; this.point.Copy(clipPoint); this.normal.SelfNeg(); } }; b2PositionSolverManifold.Initialize_s_pointA = new b2Vec2(); b2PositionSolverManifold.Initialize_s_pointB = new b2Vec2(); b2PositionSolverManifold.Initialize_s_planePoint = new b2Vec2(); b2PositionSolverManifold.Initialize_s_clipPoint = new b2Vec2(); return b2PositionSolverManifold; })(); var b2ContactSolver = (function() { function b2ContactSolver() { this.m_step = new b2TimeStep(); this.m_allocator = null; this.m_positionConstraints = b2ContactPositionConstraint.MakeArray(1024); this.m_velocityConstraints = b2ContactVelocityConstraint.MakeArray(1024); this.m_count = 0; } b2ContactSolver.prototype.Initialize = function(def) { this.m_step.Copy(def.step); this.m_allocator = def.allocator; this.m_count = def.count; if (this.m_positionConstraints.length < this.m_count) { var new_length = b2Max(2 * this.m_positionConstraints.length, this.m_count); while (this.m_positionConstraints.length < new_length) this.m_positionConstraints[this.m_positionConstraints.length] = new b2ContactPositionConstraint(); } if (this.m_velocityConstraints.length < this.m_count) { var new_length = b2Max(2 * this.m_velocityConstraints.length, this.m_count); while (this.m_velocityConstraints.length < new_length) this.m_velocityConstraints[this.m_velocityConstraints.length] = new b2ContactVelocityConstraint(); } this.m_positions = def.positions; this.m_velocities = def.velocities; this.m_contacts = def.contacts; for (var i = 0; i < this.m_count; ++i) { var contact = this.m_contacts[i]; var fixtureA = contact.m_fixtureA; var fixtureB = contact.m_fixtureB; var shapeA = fixtureA.GetShape(); var shapeB = fixtureB.GetShape(); var radiusA = shapeA.m_radius; var radiusB = shapeB.m_radius; var bodyA = fixtureA.GetBody(); var bodyB = fixtureB.GetBody(); var manifold = contact.GetManifold(); var pointCount = manifold.pointCount; var vc = this.m_velocityConstraints[i]; vc.friction = contact.m_friction; vc.restitution = contact.m_restitution; vc.tangentSpeed = contact.m_tangentSpeed; vc.indexA = bodyA.m_islandIndex; vc.indexB = bodyB.m_islandIndex; vc.invMassA = bodyA.m_invMass; vc.invMassB = bodyB.m_invMass; vc.invIA = bodyA.m_invI; vc.invIB = bodyB.m_invI; vc.contactIndex = i; vc.pointCount = pointCount; vc.K.SetZero(); vc.normalMass.SetZero(); var pc = this.m_positionConstraints[i]; pc.indexA = bodyA.m_islandIndex; pc.indexB = bodyB.m_islandIndex; pc.invMassA = bodyA.m_invMass; pc.invMassB = bodyB.m_invMass; pc.localCenterA.Copy(bodyA.m_sweep.localCenter); pc.localCenterB.Copy(bodyB.m_sweep.localCenter); pc.invIA = bodyA.m_invI; pc.invIB = bodyB.m_invI; pc.localNormal.Copy(manifold.localNormal); pc.localPoint.Copy(manifold.localPoint); pc.pointCount = pointCount; pc.radiusA = radiusA; pc.radiusB = radiusB; pc.type = manifold.type; for (var j = 0; j < pointCount; ++j) { var cp = manifold.points[j]; var vcp = vc.points[j]; if (this.m_step.warmStarting) { vcp.normalImpulse = this.m_step.dtRatio * cp.normalImpulse; vcp.tangentImpulse = this.m_step.dtRatio * cp.tangentImpulse; } else { vcp.normalImpulse = 0; vcp.tangentImpulse = 0; } vcp.rA.SetZero(); vcp.rB.SetZero(); vcp.normalMass = 0; vcp.tangentMass = 0; vcp.velocityBias = 0; pc.localPoints[j].Copy(cp.localPoint); } } return this; }; b2ContactSolver.prototype.InitializeVelocityConstraints = function() { var xfA = b2ContactSolver.InitializeVelocityConstraints_s_xfA; var xfB = b2ContactSolver.InitializeVelocityConstraints_s_xfB; var worldManifold = b2ContactSolver.InitializeVelocityConstraints_s_worldManifold; var k_maxConditionNumber = 1e3; for (var i = 0; i < this.m_count; ++i) { var vc = this.m_velocityConstraints[i]; var pc = this.m_positionConstraints[i]; var radiusA = pc.radiusA; var radiusB = pc.radiusB; var manifold = this.m_contacts[vc.contactIndex].GetManifold(); var indexA = vc.indexA; var indexB = vc.indexB; var mA = vc.invMassA; var mB = vc.invMassB; var iA = vc.invIA; var iB = vc.invIB; var localCenterA = pc.localCenterA; var localCenterB = pc.localCenterB; var cA = this.m_positions[indexA].c; var aA = this.m_positions[indexA].a; var vA = this.m_velocities[indexA].v; var wA = this.m_velocities[indexA].w; var cB = this.m_positions[indexB].c; var aB = this.m_positions[indexB].a; var vB = this.m_velocities[indexB].v; var wB = this.m_velocities[indexB].w; xfA.q.SetAngle(aA); xfB.q.SetAngle(aB); b2Vec2.SubVV(cA, b2Rot.MulRV(xfA.q, localCenterA, b2Vec2.s_t0), xfA.p); b2Vec2.SubVV(cB, b2Rot.MulRV(xfB.q, localCenterB, b2Vec2.s_t0), xfB.p); worldManifold.Initialize(manifold, xfA, radiusA, xfB, radiusB); vc.normal.Copy(worldManifold.normal); b2Vec2.CrossVOne(vc.normal, vc.tangent); var pointCount = vc.pointCount; for (var j = 0; j < pointCount; ++j) { var vcp = vc.points[j]; b2Vec2.SubVV(worldManifold.points[j], cA, vcp.rA); b2Vec2.SubVV(worldManifold.points[j], cB, vcp.rB); var rnA = b2Vec2.CrossVV(vcp.rA, vc.normal); var rnB = b2Vec2.CrossVV(vcp.rB, vc.normal); var kNormal = mA + mB + iA * rnA * rnA + iB * rnB * rnB; vcp.normalMass = kNormal > 0 ? 1 / kNormal : 0; var tangent = vc.tangent; var rtA = b2Vec2.CrossVV(vcp.rA, tangent); var rtB = b2Vec2.CrossVV(vcp.rB, tangent); var kTangent = mA + mB + iA * rtA * rtA + iB * rtB * rtB; vcp.tangentMass = kTangent > 0 ? 1 / kTangent : 0; vcp.velocityBias = 0; var vRel = b2Vec2.DotVV(vc.normal, b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB, wB, vcp.rB, b2Vec2.s_t0), b2Vec2.AddVCrossSV(vA, wA, vcp.rA, b2Vec2.s_t1), b2Vec2.s_t0)); vRel < -b2_velocityThreshold && (vcp.velocityBias += -vc.restitution * vRel); } if (2 === vc.pointCount && g_blockSolve) { var vcp1 = vc.points[0]; var vcp2 = vc.points[1]; var rn1A = b2Vec2.CrossVV(vcp1.rA, vc.normal); var rn1B = b2Vec2.CrossVV(vcp1.rB, vc.normal); var rn2A = b2Vec2.CrossVV(vcp2.rA, vc.normal); var rn2B = b2Vec2.CrossVV(vcp2.rB, vc.normal); var k11 = mA + mB + iA * rn1A * rn1A + iB * rn1B * rn1B; var k22 = mA + mB + iA * rn2A * rn2A + iB * rn2B * rn2B; var k12 = mA + mB + iA * rn1A * rn2A + iB * rn1B * rn2B; if (k11 * k11 < k_maxConditionNumber * (k11 * k22 - k12 * k12)) { vc.K.ex.Set(k11, k12); vc.K.ey.Set(k12, k22); vc.K.GetInverse(vc.normalMass); } else vc.pointCount = 1; } } }; b2ContactSolver.prototype.WarmStart = function() { var P = b2ContactSolver.WarmStart_s_P; for (var i = 0; i < this.m_count; ++i) { var vc = this.m_velocityConstraints[i]; var indexA = vc.indexA; var indexB = vc.indexB; var mA = vc.invMassA; var iA = vc.invIA; var mB = vc.invMassB; var iB = vc.invIB; var pointCount = vc.pointCount; var vA = this.m_velocities[indexA].v; var wA = this.m_velocities[indexA].w; var vB = this.m_velocities[indexB].v; var wB = this.m_velocities[indexB].w; var normal = vc.normal; var tangent = vc.tangent; for (var j = 0; j < pointCount; ++j) { var vcp = vc.points[j]; b2Vec2.AddVV(b2Vec2.MulSV(vcp.normalImpulse, normal, b2Vec2.s_t0), b2Vec2.MulSV(vcp.tangentImpulse, tangent, b2Vec2.s_t1), P); wA -= iA * b2Vec2.CrossVV(vcp.rA, P); vA.SelfMulSub(mA, P); wB += iB * b2Vec2.CrossVV(vcp.rB, P); vB.SelfMulAdd(mB, P); } this.m_velocities[indexA].w = wA; this.m_velocities[indexB].w = wB; } }; b2ContactSolver.prototype.SolveVelocityConstraints = function() { var dv = b2ContactSolver.SolveVelocityConstraints_s_dv; var dv1 = b2ContactSolver.SolveVelocityConstraints_s_dv1; var dv2 = b2ContactSolver.SolveVelocityConstraints_s_dv2; var P = b2ContactSolver.SolveVelocityConstraints_s_P; var a = b2ContactSolver.SolveVelocityConstraints_s_a; var b = b2ContactSolver.SolveVelocityConstraints_s_b; var x = b2ContactSolver.SolveVelocityConstraints_s_x; var d = b2ContactSolver.SolveVelocityConstraints_s_d; var P1 = b2ContactSolver.SolveVelocityConstraints_s_P1; var P2 = b2ContactSolver.SolveVelocityConstraints_s_P2; var P1P2 = b2ContactSolver.SolveVelocityConstraints_s_P1P2; for (var i = 0; i < this.m_count; ++i) { var vc = this.m_velocityConstraints[i]; var indexA = vc.indexA; var indexB = vc.indexB; var mA = vc.invMassA; var iA = vc.invIA; var mB = vc.invMassB; var iB = vc.invIB; var pointCount = vc.pointCount; var vA = this.m_velocities[indexA].v; var wA = this.m_velocities[indexA].w; var vB = this.m_velocities[indexB].v; var wB = this.m_velocities[indexB].w; var normal = vc.normal; var tangent = vc.tangent; var friction = vc.friction; for (var j = 0; j < pointCount; ++j) { var vcp = vc.points[j]; b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB, wB, vcp.rB, b2Vec2.s_t0), b2Vec2.AddVCrossSV(vA, wA, vcp.rA, b2Vec2.s_t1), dv); var vt = b2Vec2.DotVV(dv, tangent) - vc.tangentSpeed; var lambda = vcp.tangentMass * -vt; var maxFriction = friction * vcp.normalImpulse; var newImpulse = b2Clamp(vcp.tangentImpulse + lambda, -maxFriction, maxFriction); lambda = newImpulse - vcp.tangentImpulse; vcp.tangentImpulse = newImpulse; b2Vec2.MulSV(lambda, tangent, P); vA.SelfMulSub(mA, P); wA -= iA * b2Vec2.CrossVV(vcp.rA, P); vB.SelfMulAdd(mB, P); wB += iB * b2Vec2.CrossVV(vcp.rB, P); } if (1 === vc.pointCount || false === g_blockSolve) for (var j = 0; j < pointCount; ++j) { var vcp = vc.points[j]; b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB, wB, vcp.rB, b2Vec2.s_t0), b2Vec2.AddVCrossSV(vA, wA, vcp.rA, b2Vec2.s_t1), dv); var vn = b2Vec2.DotVV(dv, normal); var lambda = -vcp.normalMass * (vn - vcp.velocityBias); var newImpulse = b2Max(vcp.normalImpulse + lambda, 0); lambda = newImpulse - vcp.normalImpulse; vcp.normalImpulse = newImpulse; b2Vec2.MulSV(lambda, normal, P); vA.SelfMulSub(mA, P); wA -= iA * b2Vec2.CrossVV(vcp.rA, P); vB.SelfMulAdd(mB, P); wB += iB * b2Vec2.CrossVV(vcp.rB, P); } else { var cp1 = vc.points[0]; var cp2 = vc.points[1]; a.Set(cp1.normalImpulse, cp2.normalImpulse); b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB, wB, cp1.rB, b2Vec2.s_t0), b2Vec2.AddVCrossSV(vA, wA, cp1.rA, b2Vec2.s_t1), dv1); b2Vec2.SubVV(b2Vec2.AddVCrossSV(vB, wB, cp2.rB, b2Vec2.s_t0), b2Vec2.AddVCrossSV(vA, wA, cp2.rA, b2Vec2.s_t1), dv2); var vn1 = b2Vec2.DotVV(dv1, normal); var vn2 = b2Vec2.DotVV(dv2, normal); b.x = vn1 - cp1.velocityBias; b.y = vn2 - cp2.velocityBias; b.SelfSub(b2Mat22.MulMV(vc.K, a, b2Vec2.s_t0)); for (;;) { b2Mat22.MulMV(vc.normalMass, b, x).SelfNeg(); if (x.x >= 0 && x.y >= 0) { b2Vec2.SubVV(x, a, d); b2Vec2.MulSV(d.x, normal, P1); b2Vec2.MulSV(d.y, normal, P2); b2Vec2.AddVV(P1, P2, P1P2); vA.SelfMulSub(mA, P1P2); wA -= iA * (b2Vec2.CrossVV(cp1.rA, P1) + b2Vec2.CrossVV(cp2.rA, P2)); vB.SelfMulAdd(mB, P1P2); wB += iB * (b2Vec2.CrossVV(cp1.rB, P1) + b2Vec2.CrossVV(cp2.rB, P2)); cp1.normalImpulse = x.x; cp2.normalImpulse = x.y; break; } x.x = -cp1.normalMass * b.x; x.y = 0; vn1 = 0; vn2 = vc.K.ex.y * x.x + b.y; if (x.x >= 0 && vn2 >= 0) { b2Vec2.SubVV(x, a, d); b2Vec2.MulSV(d.x, normal, P1); b2Vec2.MulSV(d.y, normal, P2); b2Vec2.AddVV(P1, P2, P1P2); vA.SelfMulSub(mA, P1P2); wA -= iA * (b2Vec2.CrossVV(cp1.rA, P1) + b2Vec2.CrossVV(cp2.rA, P2)); vB.SelfMulAdd(mB, P1P2); wB += iB * (b2Vec2.CrossVV(cp1.rB, P1) + b2Vec2.CrossVV(cp2.rB, P2)); cp1.normalImpulse = x.x; cp2.normalImpulse = x.y; break; } x.x = 0; x.y = -cp2.normalMass * b.y; vn1 = vc.K.ey.x * x.y + b.x; vn2 = 0; if (x.y >= 0 && vn1 >= 0) { b2Vec2.SubVV(x, a, d); b2Vec2.MulSV(d.x, normal, P1); b2Vec2.MulSV(d.y, normal, P2); b2Vec2.AddVV(P1, P2, P1P2); vA.SelfMulSub(mA, P1P2); wA -= iA * (b2Vec2.CrossVV(cp1.rA, P1) + b2Vec2.CrossVV(cp2.rA, P2)); vB.SelfMulAdd(mB, P1P2); wB += iB * (b2Vec2.CrossVV(cp1.rB, P1) + b2Vec2.CrossVV(cp2.rB, P2)); cp1.normalImpulse = x.x; cp2.normalImpulse = x.y; break; } x.x = 0; x.y = 0; vn1 = b.x; vn2 = b.y; if (vn1 >= 0 && vn2 >= 0) { b2Vec2.SubVV(x, a, d); b2Vec2.MulSV(d.x, normal, P1); b2Vec2.MulSV(d.y, normal, P2); b2Vec2.AddVV(P1, P2, P1P2); vA.SelfMulSub(mA, P1P2); wA -= iA * (b2Vec2.CrossVV(cp1.rA, P1) + b2Vec2.CrossVV(cp2.rA, P2)); vB.SelfMulAdd(mB, P1P2); wB += iB * (b2Vec2.CrossVV(cp1.rB, P1) + b2Vec2.CrossVV(cp2.rB, P2)); cp1.normalImpulse = x.x; cp2.normalImpulse = x.y; break; } break; } } this.m_velocities[indexA].w = wA; this.m_velocities[indexB].w = wB; } }; b2ContactSolver.prototype.StoreImpulses = function() { for (var i = 0; i < this.m_count; ++i) { var vc = this.m_velocityConstraints[i]; var manifold = this.m_contacts[vc.contactIndex].GetManifold(); for (var j = 0; j < vc.pointCount; ++j) { manifold.points[j].normalImpulse = vc.points[j].normalImpulse; manifold.points[j].tangentImpulse = vc.points[j].tangentImpulse; } } }; b2ContactSolver.prototype.SolvePositionConstraints = function() { var xfA = b2ContactSolver.SolvePositionConstraints_s_xfA; var xfB = b2ContactSolver.SolvePositionConstraints_s_xfB; var psm = b2ContactSolver.SolvePositionConstraints_s_psm; var rA = b2ContactSolver.SolvePositionConstraints_s_rA; var rB = b2ContactSolver.SolvePositionConstraints_s_rB; var P = b2ContactSolver.SolvePositionConstraints_s_P; var minSeparation = 0; for (var i = 0; i < this.m_count; ++i) { var pc = this.m_positionConstraints[i]; var indexA = pc.indexA; var indexB = pc.indexB; var localCenterA = pc.localCenterA; var mA = pc.invMassA; var iA = pc.invIA; var localCenterB = pc.localCenterB; var mB = pc.invMassB; var iB = pc.invIB; var pointCount = pc.pointCount; var cA = this.m_positions[indexA].c; var aA = this.m_positions[indexA].a; var cB = this.m_positions[indexB].c; var aB = this.m_positions[indexB].a; for (var j = 0; j < pointCount; ++j) { xfA.q.SetAngle(aA); xfB.q.SetAngle(aB); b2Vec2.SubVV(cA, b2Rot.MulRV(xfA.q, localCenterA, b2Vec2.s_t0), xfA.p); b2Vec2.SubVV(cB, b2Rot.MulRV(xfB.q, localCenterB, b2Vec2.s_t0), xfB.p); psm.Initialize(pc, xfA, xfB, j); var normal = psm.normal; var point = psm.point; var separation = psm.separation; b2Vec2.SubVV(point, cA, rA); b2Vec2.SubVV(point, cB, rB); minSeparation = b2Min(minSeparation, separation); var C = b2Clamp(b2_baumgarte * (separation + b2_linearSlop), -b2_maxLinearCorrection, 0); var rnA = b2Vec2.CrossVV(rA, normal); var rnB = b2Vec2.CrossVV(rB, normal); var K = mA + mB + iA * rnA * rnA + iB * rnB * rnB; var impulse = K > 0 ? -C / K : 0; b2Vec2.MulSV(impulse, normal, P); cA.SelfMulSub(mA, P); aA -= iA * b2Vec2.CrossVV(rA, P); cB.SelfMulAdd(mB, P); aB += iB * b2Vec2.CrossVV(rB, P); } this.m_positions[indexA].a = aA; this.m_positions[indexB].a = aB; } return minSeparation > -3 * b2_linearSlop; }; b2ContactSolver.prototype.SolveTOIPositionConstraints = function(toiIndexA, toiIndexB) { var xfA = b2ContactSolver.SolveTOIPositionConstraints_s_xfA; var xfB = b2ContactSolver.SolveTOIPositionConstraints_s_xfB; var psm = b2ContactSolver.SolveTOIPositionConstraints_s_psm; var rA = b2ContactSolver.SolveTOIPositionConstraints_s_rA; var rB = b2ContactSolver.SolveTOIPositionConstraints_s_rB; var P = b2ContactSolver.SolveTOIPositionConstraints_s_P; var minSeparation = 0; for (var i = 0; i < this.m_count; ++i) { var pc = this.m_positionConstraints[i]; var indexA = pc.indexA; var indexB = pc.indexB; var localCenterA = pc.localCenterA; var localCenterB = pc.localCenterB; var pointCount = pc.pointCount; var mA = 0; var iA = 0; if (indexA === toiIndexA || indexA === toiIndexB) { mA = pc.invMassA; iA = pc.invIA; } var mB = 0; var iB = 0; if (indexB === toiIndexA || indexB === toiIndexB) { mB = pc.invMassB; iB = pc.invIB; } var cA = this.m_positions[indexA].c; var aA = this.m_positions[indexA].a; var cB = this.m_positions[indexB].c; var aB = this.m_positions[indexB].a; for (var j = 0; j < pointCount; ++j) { xfA.q.SetAngle(aA); xfB.q.SetAngle(aB); b2Vec2.SubVV(cA, b2Rot.MulRV(xfA.q, localCenterA, b2Vec2.s_t0), xfA.p); b2Vec2.SubVV(cB, b2Rot.MulRV(xfB.q, localCenterB, b2Vec2.s_t0), xfB.p); psm.Initialize(pc, xfA, xfB, j); var normal = psm.normal; var point = psm.point; var separation = psm.separation; b2Vec2.SubVV(point, cA, rA); b2Vec2.SubVV(point, cB, rB); minSeparation = b2Min(minSeparation, separation); var C = b2Clamp(b2_toiBaumgarte * (separation + b2_linearSlop), -b2_maxLinearCorrection, 0); var rnA = b2Vec2.CrossVV(rA, normal); var rnB = b2Vec2.CrossVV(rB, normal); var K = mA + mB + iA * rnA * rnA + iB * rnB * rnB; var impulse = K > 0 ? -C / K : 0; b2Vec2.MulSV(impulse, normal, P); cA.SelfMulSub(mA, P); aA -= iA * b2Vec2.CrossVV(rA, P); cB.SelfMulAdd(mB, P); aB += iB * b2Vec2.CrossVV(rB, P); } this.m_positions[indexA].a = aA; this.m_positions[indexB].a = aB; } return minSeparation >= -1.5 * b2_linearSlop; }; b2ContactSolver.InitializeVelocityConstraints_s_xfA = new b2Transform(); b2ContactSolver.InitializeVelocityConstraints_s_xfB = new b2Transform(); b2ContactSolver.InitializeVelocityConstraints_s_worldManifold = new b2WorldManifold(); b2ContactSolver.WarmStart_s_P = new b2Vec2(); b2ContactSolver.SolveVelocityConstraints_s_dv = new b2Vec2(); b2ContactSolver.SolveVelocityConstraints_s_dv1 = new b2Vec2(); b2ContactSolver.SolveVelocityConstraints_s_dv2 = new b2Vec2(); b2ContactSolver.SolveVelocityConstraints_s_P = new b2Vec2(); b2ContactSolver.SolveVelocityConstraints_s_a = new b2Vec2(); b2ContactSolver.SolveVelocityConstraints_s_b = new b2Vec2(); b2ContactSolver.SolveVelocityConstraints_s_x = new b2Vec2(); b2ContactSolver.SolveVelocityConstraints_s_d = new b2Vec2(); b2ContactSolver.SolveVelocityConstraints_s_P1 = new b2Vec2(); b2ContactSolver.SolveVelocityConstraints_s_P2 = new b2Vec2(); b2ContactSolver.SolveVelocityConstraints_s_P1P2 = new b2Vec2(); b2ContactSolver.SolvePositionConstraints_s_xfA = new b2Transform(); b2ContactSolver.SolvePositionConstraints_s_xfB = new b2Transform(); b2ContactSolver.SolvePositionConstraints_s_psm = new b2PositionSolverManifold(); b2ContactSolver.SolvePositionConstraints_s_rA = new b2Vec2(); b2ContactSolver.SolvePositionConstraints_s_rB = new b2Vec2(); b2ContactSolver.SolvePositionConstraints_s_P = new b2Vec2(); b2ContactSolver.SolveTOIPositionConstraints_s_xfA = new b2Transform(); b2ContactSolver.SolveTOIPositionConstraints_s_xfB = new b2Transform(); b2ContactSolver.SolveTOIPositionConstraints_s_psm = new b2PositionSolverManifold(); b2ContactSolver.SolveTOIPositionConstraints_s_rA = new b2Vec2(); b2ContactSolver.SolveTOIPositionConstraints_s_rB = new b2Vec2(); b2ContactSolver.SolveTOIPositionConstraints_s_P = new b2Vec2(); return b2ContactSolver; })(); var b2Island = (function() { function b2Island() { this.m_allocator = null; this.m_bodies = []; this.m_contacts = []; this.m_joints = []; this.m_positions = b2Position.MakeArray(1024); this.m_velocities = b2Velocity.MakeArray(1024); this.m_bodyCount = 0; this.m_jointCount = 0; this.m_contactCount = 0; this.m_bodyCapacity = 0; this.m_contactCapacity = 0; this.m_jointCapacity = 0; } b2Island.prototype.Initialize = function(bodyCapacity, contactCapacity, jointCapacity, allocator, listener) { this.m_bodyCapacity = bodyCapacity; this.m_contactCapacity = contactCapacity; this.m_jointCapacity = jointCapacity; this.m_bodyCount = 0; this.m_contactCount = 0; this.m_jointCount = 0; this.m_allocator = allocator; this.m_listener = listener; if (this.m_positions.length < bodyCapacity) { var new_length = b2Max(2 * this.m_positions.length, bodyCapacity); while (this.m_positions.length < new_length) this.m_positions[this.m_positions.length] = new b2Position(); } if (this.m_velocities.length < bodyCapacity) { var new_length = b2Max(2 * this.m_velocities.length, bodyCapacity); while (this.m_velocities.length < new_length) this.m_velocities[this.m_velocities.length] = new b2Velocity(); } }; b2Island.prototype.Clear = function() { this.m_bodyCount = 0; this.m_contactCount = 0; this.m_jointCount = 0; }; b2Island.prototype.AddBody = function(body) { body.m_islandIndex = this.m_bodyCount; this.m_bodies[this.m_bodyCount++] = body; }; b2Island.prototype.AddContact = function(contact) { this.m_contacts[this.m_contactCount++] = contact; }; b2Island.prototype.AddJoint = function(joint) { this.m_joints[this.m_jointCount++] = joint; }; b2Island.prototype.Solve = function(profile, step, gravity, allowSleep) { var timer = b2Island.s_timer.Reset(); var h = step.dt; for (var i = 0; i < this.m_bodyCount; ++i) { var b = this.m_bodies[i]; this.m_positions[i].c.Copy(b.m_sweep.c); var a = b.m_sweep.a; var v = this.m_velocities[i].v.Copy(b.m_linearVelocity); var w = b.m_angularVelocity; b.m_sweep.c0.Copy(b.m_sweep.c); b.m_sweep.a0 = b.m_sweep.a; if (b.m_type === exports.b2BodyType.b2_dynamicBody) { v.x += h * (b.m_gravityScale * gravity.x + b.m_invMass * b.m_force.x); v.y += h * (b.m_gravityScale * gravity.y + b.m_invMass * b.m_force.y); w += h * b.m_invI * b.m_torque; v.SelfMul(1 / (1 + h * b.m_linearDamping)); w *= 1 / (1 + h * b.m_angularDamping); } this.m_positions[i].a = a; this.m_velocities[i].w = w; } timer.Reset(); var solverData = b2Island.s_solverData; solverData.step.Copy(step); solverData.positions = this.m_positions; solverData.velocities = this.m_velocities; var contactSolverDef = b2Island.s_contactSolverDef; contactSolverDef.step.Copy(step); contactSolverDef.contacts = this.m_contacts; contactSolverDef.count = this.m_contactCount; contactSolverDef.positions = this.m_positions; contactSolverDef.velocities = this.m_velocities; contactSolverDef.allocator = this.m_allocator; var contactSolver = b2Island.s_contactSolver.Initialize(contactSolverDef); contactSolver.InitializeVelocityConstraints(); step.warmStarting && contactSolver.WarmStart(); for (var i = 0; i < this.m_jointCount; ++i) this.m_joints[i].InitVelocityConstraints(solverData); profile.solveInit = timer.GetMilliseconds(); timer.Reset(); for (var i = 0; i < step.velocityIterations; ++i) { for (var j = 0; j < this.m_jointCount; ++j) this.m_joints[j].SolveVelocityConstraints(solverData); contactSolver.SolveVelocityConstraints(); } contactSolver.StoreImpulses(); profile.solveVelocity = timer.GetMilliseconds(); for (var i = 0; i < this.m_bodyCount; ++i) { var c = this.m_positions[i].c; var a = this.m_positions[i].a; var v = this.m_velocities[i].v; var w = this.m_velocities[i].w; var translation = b2Vec2.MulSV(h, v, b2Island.s_translation); if (b2Vec2.DotVV(translation, translation) > b2_maxTranslationSquared) { var ratio = b2_maxTranslation / translation.Length(); v.SelfMul(ratio); } var rotation = h * w; if (rotation * rotation > b2_maxRotationSquared) { var ratio = b2_maxRotation / b2Abs(rotation); w *= ratio; } c.x += h * v.x; c.y += h * v.y; a += h * w; this.m_positions[i].a = a; this.m_velocities[i].w = w; } timer.Reset(); var positionSolved = false; for (var i = 0; i < step.positionIterations; ++i) { var contactsOkay = contactSolver.SolvePositionConstraints(); var jointsOkay = true; for (var j = 0; j < this.m_jointCount; ++j) { var jointOkay = this.m_joints[j].SolvePositionConstraints(solverData); jointsOkay = jointsOkay && jointOkay; } if (contactsOkay && jointsOkay) { positionSolved = true; break; } } for (var i = 0; i < this.m_bodyCount; ++i) { var body = this.m_bodies[i]; body.m_sweep.c.Copy(this.m_positions[i].c); body.m_sweep.a = this.m_positions[i].a; body.m_linearVelocity.Copy(this.m_velocities[i].v); body.m_angularVelocity = this.m_velocities[i].w; body.SynchronizeTransform(); } profile.solvePosition = timer.GetMilliseconds(); this.Report(contactSolver.m_velocityConstraints); if (allowSleep) { var minSleepTime = b2_maxFloat; var linTolSqr = b2_linearSleepTolerance * b2_linearSleepTolerance; var angTolSqr = b2_angularSleepTolerance * b2_angularSleepTolerance; for (var i = 0; i < this.m_bodyCount; ++i) { var b = this.m_bodies[i]; if (b.GetType() === exports.b2BodyType.b2_staticBody) continue; if (!b.m_autoSleepFlag || b.m_angularVelocity * b.m_angularVelocity > angTolSqr || b2Vec2.DotVV(b.m_linearVelocity, b.m_linearVelocity) > linTolSqr) { b.m_sleepTime = 0; minSleepTime = 0; } else { b.m_sleepTime += h; minSleepTime = b2Min(minSleepTime, b.m_sleepTime); } } if (minSleepTime >= b2_timeToSleep && positionSolved) for (var i = 0; i < this.m_bodyCount; ++i) { var b = this.m_bodies[i]; b.SetAwake(false); } } }; b2Island.prototype.SolveTOI = function(subStep, toiIndexA, toiIndexB) { for (var i = 0; i < this.m_bodyCount; ++i) { var b = this.m_bodies[i]; this.m_positions[i].c.Copy(b.m_sweep.c); this.m_positions[i].a = b.m_sweep.a; this.m_velocities[i].v.Copy(b.m_linearVelocity); this.m_velocities[i].w = b.m_angularVelocity; } var contactSolverDef = b2Island.s_contactSolverDef; contactSolverDef.contacts = this.m_contacts; contactSolverDef.count = this.m_contactCount; contactSolverDef.allocator = this.m_allocator; contactSolverDef.step.Copy(subStep); contactSolverDef.positions = this.m_positions; contactSolverDef.velocities = this.m_velocities; var contactSolver = b2Island.s_contactSolver.Initialize(contactSolverDef); for (var i = 0; i < subStep.positionIterations; ++i) { var contactsOkay = contactSolver.SolveTOIPositionConstraints(toiIndexA, toiIndexB); if (contactsOkay) break; } this.m_bodies[toiIndexA].m_sweep.c0.Copy(this.m_positions[toiIndexA].c); this.m_bodies[toiIndexA].m_sweep.a0 = this.m_positions[toiIndexA].a; this.m_bodies[toiIndexB].m_sweep.c0.Copy(this.m_positions[toiIndexB].c); this.m_bodies[toiIndexB].m_sweep.a0 = this.m_positions[toiIndexB].a; contactSolver.InitializeVelocityConstraints(); for (var i = 0; i < subStep.velocityIterations; ++i) contactSolver.SolveVelocityConstraints(); var h = subStep.dt; for (var i = 0; i < this.m_bodyCount; ++i) { var c = this.m_positions[i].c; var a = this.m_positions[i].a; var v = this.m_velocities[i].v; var w = this.m_velocities[i].w; var translation = b2Vec2.MulSV(h, v, b2Island.s_translation); if (b2Vec2.DotVV(translation, translation) > b2_maxTranslationSquared) { var ratio = b2_maxTranslation / translation.Length(); v.SelfMul(ratio); } var rotation = h * w; if (rotation * rotation > b2_maxRotationSquared) { var ratio = b2_maxRotation / b2Abs(rotation); w *= ratio; } c.SelfMulAdd(h, v); a += h * w; this.m_positions[i].a = a; this.m_velocities[i].w = w; var body = this.m_bodies[i]; body.m_sweep.c.Copy(c); body.m_sweep.a = a; body.m_linearVelocity.Copy(v); body.m_angularVelocity = w; body.SynchronizeTransform(); } this.Report(contactSolver.m_velocityConstraints); }; b2Island.prototype.Report = function(constraints) { if (null === this.m_listener) return; for (var i = 0; i < this.m_contactCount; ++i) { var c = this.m_contacts[i]; if (!c) continue; var vc = constraints[i]; var impulse = b2Island.s_impulse; impulse.count = vc.pointCount; for (var j = 0; j < vc.pointCount; ++j) { impulse.normalImpulses[j] = vc.points[j].normalImpulse; impulse.tangentImpulses[j] = vc.points[j].tangentImpulse; } this.m_listener.PostSolve(c, impulse); } }; b2Island.s_timer = new b2Timer(); b2Island.s_solverData = new b2SolverData(); b2Island.s_contactSolverDef = new b2ContactSolverDef(); b2Island.s_contactSolver = new b2ContactSolver(); b2Island.s_translation = new b2Vec2(); b2Island.s_impulse = new b2ContactImpulse(); return b2Island; })(); (function(b2ParticleFlag) { b2ParticleFlag[b2ParticleFlag["b2_waterParticle"] = 0] = "b2_waterParticle"; b2ParticleFlag[b2ParticleFlag["b2_zombieParticle"] = 2] = "b2_zombieParticle"; b2ParticleFlag[b2ParticleFlag["b2_wallParticle"] = 4] = "b2_wallParticle"; b2ParticleFlag[b2ParticleFlag["b2_springParticle"] = 8] = "b2_springParticle"; b2ParticleFlag[b2ParticleFlag["b2_elasticParticle"] = 16] = "b2_elasticParticle"; b2ParticleFlag[b2ParticleFlag["b2_viscousParticle"] = 32] = "b2_viscousParticle"; b2ParticleFlag[b2ParticleFlag["b2_powderParticle"] = 64] = "b2_powderParticle"; b2ParticleFlag[b2ParticleFlag["b2_tensileParticle"] = 128] = "b2_tensileParticle"; b2ParticleFlag[b2ParticleFlag["b2_colorMixingParticle"] = 256] = "b2_colorMixingParticle"; b2ParticleFlag[b2ParticleFlag["b2_destructionListenerParticle"] = 512] = "b2_destructionListenerParticle"; b2ParticleFlag[b2ParticleFlag["b2_barrierParticle"] = 1024] = "b2_barrierParticle"; b2ParticleFlag[b2ParticleFlag["b2_staticPressureParticle"] = 2048] = "b2_staticPressureParticle"; b2ParticleFlag[b2ParticleFlag["b2_reactiveParticle"] = 4096] = "b2_reactiveParticle"; b2ParticleFlag[b2ParticleFlag["b2_repulsiveParticle"] = 8192] = "b2_repulsiveParticle"; b2ParticleFlag[b2ParticleFlag["b2_fixtureContactListenerParticle"] = 16384] = "b2_fixtureContactListenerParticle"; b2ParticleFlag[b2ParticleFlag["b2_particleContactListenerParticle"] = 32768] = "b2_particleContactListenerParticle"; b2ParticleFlag[b2ParticleFlag["b2_fixtureContactFilterParticle"] = 65536] = "b2_fixtureContactFilterParticle"; b2ParticleFlag[b2ParticleFlag["b2_particleContactFilterParticle"] = 131072] = "b2_particleContactFilterParticle"; })(exports.b2ParticleFlag || (exports.b2ParticleFlag = {})); var b2ParticleDef = (function() { function b2ParticleDef() { this.flags = 0; this.position = new b2Vec2(); this.velocity = new b2Vec2(); this.color = new b2Color(0, 0, 0, 0); this.lifetime = 0; this.userData = null; this.group = null; } return b2ParticleDef; })(); function b2CalculateParticleIterations(gravity, radius, timeStep) { var B2_MAX_RECOMMENDED_PARTICLE_ITERATIONS = 8; var B2_RADIUS_THRESHOLD = .01; var iterations = Math.ceil(Math.sqrt(gravity / (B2_RADIUS_THRESHOLD * radius)) * timeStep); return b2Clamp(iterations, 1, B2_MAX_RECOMMENDED_PARTICLE_ITERATIONS); } var b2ParticleHandle = (function() { function b2ParticleHandle() { this.m_index = b2_invalidParticleIndex; } b2ParticleHandle.prototype.GetIndex = function() { return this.m_index; }; b2ParticleHandle.prototype.SetIndex = function(index) { this.m_index = index; }; return b2ParticleHandle; })(); (function(b2ParticleGroupFlag) { b2ParticleGroupFlag[b2ParticleGroupFlag["b2_solidParticleGroup"] = 1] = "b2_solidParticleGroup"; b2ParticleGroupFlag[b2ParticleGroupFlag["b2_rigidParticleGroup"] = 2] = "b2_rigidParticleGroup"; b2ParticleGroupFlag[b2ParticleGroupFlag["b2_particleGroupCanBeEmpty"] = 4] = "b2_particleGroupCanBeEmpty"; b2ParticleGroupFlag[b2ParticleGroupFlag["b2_particleGroupWillBeDestroyed"] = 8] = "b2_particleGroupWillBeDestroyed"; b2ParticleGroupFlag[b2ParticleGroupFlag["b2_particleGroupNeedsUpdateDepth"] = 16] = "b2_particleGroupNeedsUpdateDepth"; b2ParticleGroupFlag[b2ParticleGroupFlag["b2_particleGroupInternalMask"] = 24] = "b2_particleGroupInternalMask"; })(exports.b2ParticleGroupFlag || (exports.b2ParticleGroupFlag = {})); var b2ParticleGroupDef = (function() { function b2ParticleGroupDef() { this.flags = 0; this.groupFlags = 0; this.position = new b2Vec2(); this.angle = 0; this.linearVelocity = new b2Vec2(); this.angularVelocity = 0; this.color = new b2Color(); this.strength = 1; this.shapeCount = 0; this.stride = 0; this.particleCount = 0; this.lifetime = 0; this.userData = null; this.group = null; } return b2ParticleGroupDef; })(); var b2ParticleGroup = (function() { function b2ParticleGroup(system) { this.m_firstIndex = 0; this.m_lastIndex = 0; this.m_groupFlags = 0; this.m_strength = 1; this.m_prev = null; this.m_next = null; this.m_timestamp = -1; this.m_mass = 0; this.m_inertia = 0; this.m_center = new b2Vec2(); this.m_linearVelocity = new b2Vec2(); this.m_angularVelocity = 0; this.m_transform = new b2Transform(); this.m_userData = null; this.m_system = system; } b2ParticleGroup.prototype.GetNext = function() { return this.m_next; }; b2ParticleGroup.prototype.GetParticleSystem = function() { return this.m_system; }; b2ParticleGroup.prototype.GetParticleCount = function() { return this.m_lastIndex - this.m_firstIndex; }; b2ParticleGroup.prototype.GetBufferIndex = function() { return this.m_firstIndex; }; b2ParticleGroup.prototype.ContainsParticle = function(index) { return this.m_firstIndex <= index && index < this.m_lastIndex; }; b2ParticleGroup.prototype.GetAllParticleFlags = function() { if (!this.m_system.m_flagsBuffer.data) throw new Error(); var flags = 0; for (var i = this.m_firstIndex; i < this.m_lastIndex; i++) flags |= this.m_system.m_flagsBuffer.data[i]; return flags; }; b2ParticleGroup.prototype.GetGroupFlags = function() { return this.m_groupFlags; }; b2ParticleGroup.prototype.SetGroupFlags = function(flags) { flags |= this.m_groupFlags & exports.b2ParticleGroupFlag.b2_particleGroupInternalMask; this.m_system.SetGroupFlags(this, flags); }; b2ParticleGroup.prototype.GetMass = function() { this.UpdateStatistics(); return this.m_mass; }; b2ParticleGroup.prototype.GetInertia = function() { this.UpdateStatistics(); return this.m_inertia; }; b2ParticleGroup.prototype.GetCenter = function() { this.UpdateStatistics(); return this.m_center; }; b2ParticleGroup.prototype.GetLinearVelocity = function() { this.UpdateStatistics(); return this.m_linearVelocity; }; b2ParticleGroup.prototype.GetAngularVelocity = function() { this.UpdateStatistics(); return this.m_angularVelocity; }; b2ParticleGroup.prototype.GetTransform = function() { return this.m_transform; }; b2ParticleGroup.prototype.GetPosition = function() { return this.m_transform.p; }; b2ParticleGroup.prototype.GetAngle = function() { return this.m_transform.q.GetAngle(); }; b2ParticleGroup.prototype.GetLinearVelocityFromWorldPoint = function(worldPoint, out) { var s_t0 = b2ParticleGroup.GetLinearVelocityFromWorldPoint_s_t0; this.UpdateStatistics(); return b2Vec2.AddVCrossSV(this.m_linearVelocity, this.m_angularVelocity, b2Vec2.SubVV(worldPoint, this.m_center, s_t0), out); }; b2ParticleGroup.prototype.GetUserData = function() { return this.m_userData; }; b2ParticleGroup.prototype.SetUserData = function(data) { this.m_userData = data; }; b2ParticleGroup.prototype.ApplyForce = function(force) { this.m_system.ApplyForce(this.m_firstIndex, this.m_lastIndex, force); }; b2ParticleGroup.prototype.ApplyLinearImpulse = function(impulse) { this.m_system.ApplyLinearImpulse(this.m_firstIndex, this.m_lastIndex, impulse); }; b2ParticleGroup.prototype.DestroyParticles = function(callDestructionListener) { if (this.m_system.m_world.IsLocked()) throw new Error(); for (var i = this.m_firstIndex; i < this.m_lastIndex; i++) this.m_system.DestroyParticle(i, callDestructionListener); }; b2ParticleGroup.prototype.UpdateStatistics = function() { if (!this.m_system.m_positionBuffer.data) throw new Error(); if (!this.m_system.m_velocityBuffer.data) throw new Error(); var p = new b2Vec2(); var v = new b2Vec2(); if (this.m_timestamp !== this.m_system.m_timestamp) { var m = this.m_system.GetParticleMass(); this.m_mass = m * (this.m_lastIndex - this.m_firstIndex); this.m_center.SetZero(); this.m_linearVelocity.SetZero(); for (var i = this.m_firstIndex; i < this.m_lastIndex; i++) { this.m_center.SelfMulAdd(m, this.m_system.m_positionBuffer.data[i]); this.m_linearVelocity.SelfMulAdd(m, this.m_system.m_velocityBuffer.data[i]); } if (this.m_mass > 0) { var inv_mass = 1 / this.m_mass; this.m_center.SelfMul(inv_mass); this.m_linearVelocity.SelfMul(inv_mass); } this.m_inertia = 0; this.m_angularVelocity = 0; for (var i = this.m_firstIndex; i < this.m_lastIndex; i++) { b2Vec2.SubVV(this.m_system.m_positionBuffer.data[i], this.m_center, p); b2Vec2.SubVV(this.m_system.m_velocityBuffer.data[i], this.m_linearVelocity, v); this.m_inertia += m * b2Vec2.DotVV(p, p); this.m_angularVelocity += m * b2Vec2.CrossVV(p, v); } this.m_inertia > 0 && (this.m_angularVelocity *= 1 / this.m_inertia); this.m_timestamp = this.m_system.m_timestamp; } }; b2ParticleGroup.GetLinearVelocityFromWorldPoint_s_t0 = new b2Vec2(); return b2ParticleGroup; })(); var b2StackQueue = (function() { function b2StackQueue(capacity) { this.m_front = 0; this.m_back = 0; this.m_capacity = 0; this.m_buffer = b2MakeArray(capacity, (function(index) { return null; })); this.m_capacity = capacity; } b2StackQueue.prototype.Push = function(item) { if (this.m_back >= this.m_capacity) { for (var i = this.m_front; i < this.m_back; i++) this.m_buffer[i - this.m_front] = this.m_buffer[i]; this.m_back -= this.m_front; this.m_front = 0; if (this.m_back >= this.m_capacity) if (this.m_capacity > 0) { this.m_buffer.concat(b2MakeArray(this.m_capacity, (function(index) { return null; }))); this.m_capacity *= 2; } else { this.m_buffer.concat(b2MakeArray(1, (function(index) { return null; }))); this.m_capacity = 1; } } this.m_buffer[this.m_back] = item; this.m_back++; }; b2StackQueue.prototype.Pop = function() { this.m_buffer[this.m_front] = null; this.m_front++; }; b2StackQueue.prototype.Empty = function() { return this.m_front === this.m_back; }; b2StackQueue.prototype.Front = function() { var item = this.m_buffer[this.m_front]; if (!item) throw new Error(); return item; }; return b2StackQueue; })(); var b2VoronoiDiagram = (function() { function b2VoronoiDiagram(generatorCapacity) { this.m_generatorCapacity = 0; this.m_generatorCount = 0; this.m_countX = 0; this.m_countY = 0; this.m_diagram = []; this.m_generatorBuffer = b2MakeArray(generatorCapacity, (function(index) { return new b2VoronoiDiagram.Generator(); })); this.m_generatorCapacity = generatorCapacity; } b2VoronoiDiagram.prototype.AddGenerator = function(center, tag, necessary) { var g = this.m_generatorBuffer[this.m_generatorCount++]; g.center.Copy(center); g.tag = tag; g.necessary = necessary; }; b2VoronoiDiagram.prototype.Generate = function(radius, margin) { var inverseRadius = 1 / radius; var lower = new b2Vec2(+b2_maxFloat, +b2_maxFloat); var upper = new b2Vec2(-b2_maxFloat, -b2_maxFloat); var necessary_count = 0; for (var k = 0; k < this.m_generatorCount; k++) { var g = this.m_generatorBuffer[k]; if (g.necessary) { b2Vec2.MinV(lower, g.center, lower); b2Vec2.MaxV(upper, g.center, upper); ++necessary_count; } } if (0 === necessary_count) { this.m_countX = 0; this.m_countY = 0; return; } lower.x -= margin; lower.y -= margin; upper.x += margin; upper.y += margin; this.m_countX = 1 + Math.floor(inverseRadius * (upper.x - lower.x)); this.m_countY = 1 + Math.floor(inverseRadius * (upper.y - lower.y)); this.m_diagram = []; var queue = new b2StackQueue(4 * this.m_countX * this.m_countY); for (var k = 0; k < this.m_generatorCount; k++) { var g = this.m_generatorBuffer[k]; g.center.SelfSub(lower).SelfMul(inverseRadius); var x = Math.floor(g.center.x); var y = Math.floor(g.center.y); x >= 0 && y >= 0 && x < this.m_countX && y < this.m_countY && queue.Push(new b2VoronoiDiagram.Task(x, y, x + y * this.m_countX, g)); } while (!queue.Empty()) { var task = queue.Front(); var x = task.m_x; var y = task.m_y; var i = task.m_i; var g = task.m_generator; queue.Pop(); if (!this.m_diagram[i]) { this.m_diagram[i] = g; x > 0 && queue.Push(new b2VoronoiDiagram.Task(x - 1, y, i - 1, g)); y > 0 && queue.Push(new b2VoronoiDiagram.Task(x, y - 1, i - this.m_countX, g)); x < this.m_countX - 1 && queue.Push(new b2VoronoiDiagram.Task(x + 1, y, i + 1, g)); y < this.m_countY - 1 && queue.Push(new b2VoronoiDiagram.Task(x, y + 1, i + this.m_countX, g)); } } for (var y = 0; y < this.m_countY; y++) for (var x = 0; x < this.m_countX - 1; x++) { var i = x + y * this.m_countX; var a = this.m_diagram[i]; var b = this.m_diagram[i + 1]; if (a !== b) { queue.Push(new b2VoronoiDiagram.Task(x, y, i, b)); queue.Push(new b2VoronoiDiagram.Task(x + 1, y, i + 1, a)); } } for (var y = 0; y < this.m_countY - 1; y++) for (var x = 0; x < this.m_countX; x++) { var i = x + y * this.m_countX; var a = this.m_diagram[i]; var b = this.m_diagram[i + this.m_countX]; if (a !== b) { queue.Push(new b2VoronoiDiagram.Task(x, y, i, b)); queue.Push(new b2VoronoiDiagram.Task(x, y + 1, i + this.m_countX, a)); } } while (!queue.Empty()) { var task = queue.Front(); var x = task.m_x; var y = task.m_y; var i = task.m_i; var k = task.m_generator; queue.Pop(); var a = this.m_diagram[i]; var b = k; if (a !== b) { var ax = a.center.x - x; var ay = a.center.y - y; var bx = b.center.x - x; var by = b.center.y - y; var a2 = ax * ax + ay * ay; var b2 = bx * bx + by * by; if (a2 > b2) { this.m_diagram[i] = b; x > 0 && queue.Push(new b2VoronoiDiagram.Task(x - 1, y, i - 1, b)); y > 0 && queue.Push(new b2VoronoiDiagram.Task(x, y - 1, i - this.m_countX, b)); x < this.m_countX - 1 && queue.Push(new b2VoronoiDiagram.Task(x + 1, y, i + 1, b)); y < this.m_countY - 1 && queue.Push(new b2VoronoiDiagram.Task(x, y + 1, i + this.m_countX, b)); } } } }; b2VoronoiDiagram.prototype.GetNodes = function(callback) { for (var y = 0; y < this.m_countY - 1; y++) for (var x = 0; x < this.m_countX - 1; x++) { var i = x + y * this.m_countX; var a = this.m_diagram[i]; var b = this.m_diagram[i + 1]; var c = this.m_diagram[i + this.m_countX]; var d = this.m_diagram[i + 1 + this.m_countX]; if (b !== c) { a !== b && a !== c && (a.necessary || b.necessary || c.necessary) && callback(a.tag, b.tag, c.tag); d !== b && d !== c && (a.necessary || b.necessary || c.necessary) && callback(b.tag, d.tag, c.tag); } } }; return b2VoronoiDiagram; })(); (function(b2VoronoiDiagram) { var Generator = (function() { function Generator() { this.center = new b2Vec2(); this.tag = 0; this.necessary = false; } return Generator; })(); b2VoronoiDiagram.Generator = Generator; var Task = (function() { function Task(x, y, i, g) { this.m_x = x; this.m_y = y; this.m_i = i; this.m_generator = g; } return Task; })(); b2VoronoiDiagram.Task = Task; })(b2VoronoiDiagram || (b2VoronoiDiagram = {})); function std_iter_swap(array, a, b) { var tmp = array[a]; array[a] = array[b]; array[b] = tmp; } function default_compare(a, b) { return a < b; } function std_sort(array, first, len, cmp) { void 0 === first && (first = 0); void 0 === len && (len = array.length - first); void 0 === cmp && (cmp = default_compare); var left = first; var stack = []; var pos = 0; for (;;) { for (;left + 1 < len; len++) { var pivot = array[left + Math.floor(Math.random() * (len - left))]; stack[pos++] = len; for (var right = left - 1; ;) { while (cmp(array[++right], pivot)) ; while (cmp(pivot, array[--len])) ; if (right >= len) break; std_iter_swap(array, right, len); } } if (0 === pos) break; left = len; len = stack[--pos]; } return array; } function std_stable_sort(array, first, len, cmp) { void 0 === first && (first = 0); void 0 === len && (len = array.length - first); void 0 === cmp && (cmp = default_compare); return std_sort(array, first, len, cmp); } function std_remove_if(array, predicate, length) { void 0 === length && (length = array.length); var l = 0; for (var c = 0; c < length; ++c) { if (predicate(array[c])) continue; if (c === l) { ++l; continue; } std_iter_swap(array, l++, c); } return l; } function std_lower_bound(array, first, last, val, cmp) { void 0 === cmp && (cmp = default_compare); var count = last - first; while (count > 0) { var step = Math.floor(count / 2); var it = first + step; if (cmp(array[it], val)) { first = ++it; count -= step + 1; } else count = step; } return first; } function std_upper_bound(array, first, last, val, cmp) { void 0 === cmp && (cmp = default_compare); var count = last - first; while (count > 0) { var step = Math.floor(count / 2); var it = first + step; if (cmp(val, array[it])) count = step; else { first = ++it; count -= step + 1; } } return first; } function std_rotate(array, first, n_first, last) { var next = n_first; while (first !== next) { std_iter_swap(array, first++, next++); next === last ? next = n_first : first === n_first && (n_first = next); } } function std_unique(array, first, last, cmp) { if (first === last) return last; var result = first; while (++first !== last) cmp(array[result], array[first]) || std_iter_swap(array, ++result, first); return ++result; } var b2GrowableBuffer = (function() { function b2GrowableBuffer(allocator) { this.data = []; this.count = 0; this.capacity = 0; this.allocator = allocator; } b2GrowableBuffer.prototype.Append = function() { this.count >= this.capacity && this.Grow(); return this.count++; }; b2GrowableBuffer.prototype.Reserve = function(newCapacity) { if (this.capacity >= newCapacity) return; for (var i = this.capacity; i < newCapacity; ++i) this.data[i] = this.allocator(); this.capacity = newCapacity; }; b2GrowableBuffer.prototype.Grow = function() { var newCapacity = this.capacity ? 2 * this.capacity : b2_minParticleSystemBufferCapacity; this.Reserve(newCapacity); }; b2GrowableBuffer.prototype.Free = function() { if (0 === this.data.length) return; this.data = []; this.capacity = 0; this.count = 0; }; b2GrowableBuffer.prototype.Shorten = function(newEnd) {}; b2GrowableBuffer.prototype.Data = function() { return this.data; }; b2GrowableBuffer.prototype.GetCount = function() { return this.count; }; b2GrowableBuffer.prototype.SetCount = function(newCount) { this.count = newCount; }; b2GrowableBuffer.prototype.GetCapacity = function() { return this.capacity; }; b2GrowableBuffer.prototype.RemoveIf = function(pred) { this.count = std_remove_if(this.data, pred, this.count); }; b2GrowableBuffer.prototype.Unique = function(pred) { this.count = std_unique(this.data, 0, this.count, pred); }; return b2GrowableBuffer; })(); var b2FixtureParticleQueryCallback = (function(_super) { __extends(b2FixtureParticleQueryCallback, _super); function b2FixtureParticleQueryCallback(system) { var _this = _super.call(this) || this; _this.m_system = system; return _this; } b2FixtureParticleQueryCallback.prototype.ShouldQueryParticleSystem = function(system) { return false; }; b2FixtureParticleQueryCallback.prototype.ReportFixture = function(fixture) { if (fixture.IsSensor()) return true; var shape = fixture.GetShape(); var childCount = shape.GetChildCount(); for (var childIndex = 0; childIndex < childCount; childIndex++) { var aabb = fixture.GetAABB(childIndex); var enumerator = this.m_system.GetInsideBoundsEnumerator(aabb); var index = void 0; while ((index = enumerator.GetNext()) >= 0) this.ReportFixtureAndParticle(fixture, childIndex, index); } return true; }; b2FixtureParticleQueryCallback.prototype.ReportParticle = function(system, index) { return false; }; b2FixtureParticleQueryCallback.prototype.ReportFixtureAndParticle = function(fixture, childIndex, index) {}; return b2FixtureParticleQueryCallback; })(b2QueryCallback); var b2ParticleContact = (function() { function b2ParticleContact() { this.indexA = 0; this.indexB = 0; this.weight = 0; this.normal = new b2Vec2(); this.flags = 0; } b2ParticleContact.prototype.SetIndices = function(a, b) { this.indexA = a; this.indexB = b; }; b2ParticleContact.prototype.SetWeight = function(w) { this.weight = w; }; b2ParticleContact.prototype.SetNormal = function(n) { this.normal.Copy(n); }; b2ParticleContact.prototype.SetFlags = function(f) { this.flags = f; }; b2ParticleContact.prototype.GetIndexA = function() { return this.indexA; }; b2ParticleContact.prototype.GetIndexB = function() { return this.indexB; }; b2ParticleContact.prototype.GetWeight = function() { return this.weight; }; b2ParticleContact.prototype.GetNormal = function() { return this.normal; }; b2ParticleContact.prototype.GetFlags = function() { return this.flags; }; b2ParticleContact.prototype.IsEqual = function(rhs) { return this.indexA === rhs.indexA && this.indexB === rhs.indexB && this.flags === rhs.flags && this.weight === rhs.weight && this.normal.x === rhs.normal.x && this.normal.y === rhs.normal.y; }; b2ParticleContact.prototype.IsNotEqual = function(rhs) { return !this.IsEqual(rhs); }; b2ParticleContact.prototype.ApproximatelyEqual = function(rhs) { var MAX_WEIGHT_DIFF = .01; var MAX_NORMAL_DIFF_SQ = 1e-4; return this.indexA === rhs.indexA && this.indexB === rhs.indexB && this.flags === rhs.flags && b2Abs(this.weight - rhs.weight) < MAX_WEIGHT_DIFF && b2Vec2.DistanceSquaredVV(this.normal, rhs.normal) < MAX_NORMAL_DIFF_SQ; }; return b2ParticleContact; })(); var b2ParticleBodyContact = (function() { function b2ParticleBodyContact() { this.index = 0; this.weight = 0; this.normal = new b2Vec2(); this.mass = 0; } return b2ParticleBodyContact; })(); var b2ParticlePair = (function() { function b2ParticlePair() { this.indexA = 0; this.indexB = 0; this.flags = 0; this.strength = 0; this.distance = 0; } return b2ParticlePair; })(); var b2ParticleTriad = (function() { function b2ParticleTriad() { this.indexA = 0; this.indexB = 0; this.indexC = 0; this.flags = 0; this.strength = 0; this.pa = new b2Vec2(0, 0); this.pb = new b2Vec2(0, 0); this.pc = new b2Vec2(0, 0); this.ka = 0; this.kb = 0; this.kc = 0; this.s = 0; } return b2ParticleTriad; })(); var b2ParticleSystemDef = (function() { function b2ParticleSystemDef() { this.strictContactCheck = false; this.density = 1; this.gravityScale = 1; this.radius = 1; this.maxCount = 0; this.pressureStrength = .005; this.dampingStrength = 1; this.elasticStrength = .25; this.springStrength = .25; this.viscousStrength = .25; this.surfaceTensionPressureStrength = .2; this.surfaceTensionNormalStrength = .2; this.repulsiveStrength = 1; this.powderStrength = .5; this.ejectionStrength = .5; this.staticPressureStrength = .2; this.staticPressureRelaxation = .2; this.staticPressureIterations = 8; this.colorMixingStrength = .5; this.destroyByAge = true; this.lifetimeGranularity = 1 / 60; } b2ParticleSystemDef.prototype.Copy = function(def) { this.strictContactCheck = def.strictContactCheck; this.density = def.density; this.gravityScale = def.gravityScale; this.radius = def.radius; this.maxCount = def.maxCount; this.pressureStrength = def.pressureStrength; this.dampingStrength = def.dampingStrength; this.elasticStrength = def.elasticStrength; this.springStrength = def.springStrength; this.viscousStrength = def.viscousStrength; this.surfaceTensionPressureStrength = def.surfaceTensionPressureStrength; this.surfaceTensionNormalStrength = def.surfaceTensionNormalStrength; this.repulsiveStrength = def.repulsiveStrength; this.powderStrength = def.powderStrength; this.ejectionStrength = def.ejectionStrength; this.staticPressureStrength = def.staticPressureStrength; this.staticPressureRelaxation = def.staticPressureRelaxation; this.staticPressureIterations = def.staticPressureIterations; this.colorMixingStrength = def.colorMixingStrength; this.destroyByAge = def.destroyByAge; this.lifetimeGranularity = def.lifetimeGranularity; return this; }; b2ParticleSystemDef.prototype.Clone = function() { return new b2ParticleSystemDef().Copy(this); }; return b2ParticleSystemDef; })(); exports.b2ParticleSystem = (function() { function b2ParticleSystem(def, world) { this.m_paused = false; this.m_timestamp = 0; this.m_allParticleFlags = 0; this.m_needsUpdateAllParticleFlags = false; this.m_allGroupFlags = 0; this.m_needsUpdateAllGroupFlags = false; this.m_hasForce = false; this.m_iterationIndex = 0; this.m_inverseDensity = 0; this.m_particleDiameter = 0; this.m_inverseDiameter = 0; this.m_squaredDiameter = 0; this.m_count = 0; this.m_internalAllocatedCapacity = 0; this.m_handleIndexBuffer = new b2ParticleSystem.UserOverridableBuffer(); this.m_flagsBuffer = new b2ParticleSystem.UserOverridableBuffer(); this.m_positionBuffer = new b2ParticleSystem.UserOverridableBuffer(); this.m_velocityBuffer = new b2ParticleSystem.UserOverridableBuffer(); this.m_forceBuffer = []; this.m_weightBuffer = []; this.m_staticPressureBuffer = []; this.m_accumulationBuffer = []; this.m_accumulation2Buffer = []; this.m_depthBuffer = []; this.m_colorBuffer = new b2ParticleSystem.UserOverridableBuffer(); this.m_groupBuffer = []; this.m_userDataBuffer = new b2ParticleSystem.UserOverridableBuffer(); this.m_stuckThreshold = 0; this.m_lastBodyContactStepBuffer = new b2ParticleSystem.UserOverridableBuffer(); this.m_bodyContactCountBuffer = new b2ParticleSystem.UserOverridableBuffer(); this.m_consecutiveContactStepsBuffer = new b2ParticleSystem.UserOverridableBuffer(); this.m_stuckParticleBuffer = new b2GrowableBuffer(function() { return 0; }); this.m_proxyBuffer = new b2GrowableBuffer(function() { return new b2ParticleSystem.Proxy(); }); this.m_contactBuffer = new b2GrowableBuffer(function() { return new b2ParticleContact(); }); this.m_bodyContactBuffer = new b2GrowableBuffer(function() { return new b2ParticleBodyContact(); }); this.m_pairBuffer = new b2GrowableBuffer(function() { return new b2ParticlePair(); }); this.m_triadBuffer = new b2GrowableBuffer(function() { return new b2ParticleTriad(); }); this.m_expirationTimeBuffer = new b2ParticleSystem.UserOverridableBuffer(); this.m_indexByExpirationTimeBuffer = new b2ParticleSystem.UserOverridableBuffer(); this.m_timeElapsed = 0; this.m_expirationTimeBufferRequiresSorting = false; this.m_groupCount = 0; this.m_groupList = null; this.m_def = new b2ParticleSystemDef(); this.m_prev = null; this.m_next = null; this.SetStrictContactCheck(def.strictContactCheck); this.SetDensity(def.density); this.SetGravityScale(def.gravityScale); this.SetRadius(def.radius); this.SetMaxParticleCount(def.maxCount); this.m_def = def.Clone(); this.m_world = world; this.SetDestructionByAge(this.m_def.destroyByAge); } b2ParticleSystem.computeTag = function(x, y) { return (y + b2ParticleSystem.yOffset >>> 0 << b2ParticleSystem.yShift) + (b2ParticleSystem.xScale * x + b2ParticleSystem.xOffset >>> 0) >>> 0; }; b2ParticleSystem.computeRelativeTag = function(tag, x, y) { return tag + (y << b2ParticleSystem.yShift) + (x << b2ParticleSystem.xShift) >>> 0; }; b2ParticleSystem.prototype.Drop = function() { while (this.m_groupList) this.DestroyParticleGroup(this.m_groupList); this.FreeUserOverridableBuffer(this.m_handleIndexBuffer); this.FreeUserOverridableBuffer(this.m_flagsBuffer); this.FreeUserOverridableBuffer(this.m_lastBodyContactStepBuffer); this.FreeUserOverridableBuffer(this.m_bodyContactCountBuffer); this.FreeUserOverridableBuffer(this.m_consecutiveContactStepsBuffer); this.FreeUserOverridableBuffer(this.m_positionBuffer); this.FreeUserOverridableBuffer(this.m_velocityBuffer); this.FreeUserOverridableBuffer(this.m_colorBuffer); this.FreeUserOverridableBuffer(this.m_userDataBuffer); this.FreeUserOverridableBuffer(this.m_expirationTimeBuffer); this.FreeUserOverridableBuffer(this.m_indexByExpirationTimeBuffer); this.FreeBuffer(this.m_forceBuffer, this.m_internalAllocatedCapacity); this.FreeBuffer(this.m_weightBuffer, this.m_internalAllocatedCapacity); this.FreeBuffer(this.m_staticPressureBuffer, this.m_internalAllocatedCapacity); this.FreeBuffer(this.m_accumulationBuffer, this.m_internalAllocatedCapacity); this.FreeBuffer(this.m_accumulation2Buffer, this.m_internalAllocatedCapacity); this.FreeBuffer(this.m_depthBuffer, this.m_internalAllocatedCapacity); this.FreeBuffer(this.m_groupBuffer, this.m_internalAllocatedCapacity); }; b2ParticleSystem.prototype.CreateParticle = function(def) { if (this.m_world.IsLocked()) throw new Error(); if (this.m_count >= this.m_internalAllocatedCapacity) { var capacity = this.m_count ? 2 * this.m_count : b2_minParticleSystemBufferCapacity; this.ReallocateInternalAllocatedBuffers(capacity); } if (this.m_count >= this.m_internalAllocatedCapacity) { if (!this.m_def.destroyByAge) return b2_invalidParticleIndex; this.DestroyOldestParticle(0, false); this.SolveZombie(); } var index = this.m_count++; if (!this.m_flagsBuffer.data) throw new Error(); this.m_flagsBuffer.data[index] = 0; this.m_lastBodyContactStepBuffer.data && (this.m_lastBodyContactStepBuffer.data[index] = 0); this.m_bodyContactCountBuffer.data && (this.m_bodyContactCountBuffer.data[index] = 0); this.m_consecutiveContactStepsBuffer.data && (this.m_consecutiveContactStepsBuffer.data[index] = 0); if (!this.m_positionBuffer.data) throw new Error(); if (!this.m_velocityBuffer.data) throw new Error(); this.m_positionBuffer.data[index] = (this.m_positionBuffer.data[index] || new b2Vec2()).Copy(b2Maybe(def.position, b2Vec2.ZERO)); this.m_velocityBuffer.data[index] = (this.m_velocityBuffer.data[index] || new b2Vec2()).Copy(b2Maybe(def.velocity, b2Vec2.ZERO)); this.m_weightBuffer[index] = 0; this.m_forceBuffer[index] = (this.m_forceBuffer[index] || new b2Vec2()).SetZero(); this.m_staticPressureBuffer && (this.m_staticPressureBuffer[index] = 0); this.m_depthBuffer && (this.m_depthBuffer[index] = 0); var color = new b2Color().Copy(b2Maybe(def.color, b2Color.ZERO)); if (this.m_colorBuffer.data || !color.IsZero()) { this.m_colorBuffer.data = this.RequestBuffer(this.m_colorBuffer.data); this.m_colorBuffer.data[index] = (this.m_colorBuffer.data[index] || new b2Color()).Copy(color); } if (this.m_userDataBuffer.data || def.userData) { this.m_userDataBuffer.data = this.RequestBuffer(this.m_userDataBuffer.data); this.m_userDataBuffer.data[index] = def.userData; } this.m_handleIndexBuffer.data && (this.m_handleIndexBuffer.data[index] = null); var proxy = this.m_proxyBuffer.data[this.m_proxyBuffer.Append()]; var lifetime = b2Maybe(def.lifetime, 0); var finiteLifetime = lifetime > 0; if (this.m_expirationTimeBuffer.data || finiteLifetime) { this.SetParticleLifetime(index, finiteLifetime ? lifetime : this.ExpirationTimeToLifetime(-this.GetQuantizedTimeElapsed())); if (!this.m_indexByExpirationTimeBuffer.data) throw new Error(); this.m_indexByExpirationTimeBuffer.data[index] = index; } proxy.index = index; var group = b2Maybe(def.group, null); this.m_groupBuffer[index] = group; if (group) if (group.m_firstIndex < group.m_lastIndex) { this.RotateBuffer(group.m_firstIndex, group.m_lastIndex, index); group.m_lastIndex = index + 1; } else { group.m_firstIndex = index; group.m_lastIndex = index + 1; } this.SetParticleFlags(index, b2Maybe(def.flags, 0)); return index; }; b2ParticleSystem.prototype.GetParticleHandleFromIndex = function(index) { this.m_handleIndexBuffer.data = this.RequestBuffer(this.m_handleIndexBuffer.data); var handle = this.m_handleIndexBuffer.data[index]; if (handle) return handle; handle = new b2ParticleHandle(); handle.SetIndex(index); this.m_handleIndexBuffer.data[index] = handle; return handle; }; b2ParticleSystem.prototype.DestroyParticle = function(index, callDestructionListener) { void 0 === callDestructionListener && (callDestructionListener = false); if (!this.m_flagsBuffer.data) throw new Error(); var flags = exports.b2ParticleFlag.b2_zombieParticle; callDestructionListener && (flags |= exports.b2ParticleFlag.b2_destructionListenerParticle); this.SetParticleFlags(index, this.m_flagsBuffer.data[index] | flags); }; b2ParticleSystem.prototype.DestroyOldestParticle = function(index, callDestructionListener) { void 0 === callDestructionListener && (callDestructionListener = false); var particleCount = this.GetParticleCount(); if (!this.m_indexByExpirationTimeBuffer.data) throw new Error(); if (!this.m_expirationTimeBuffer.data) throw new Error(); var oldestFiniteLifetimeParticle = this.m_indexByExpirationTimeBuffer.data[particleCount - (index + 1)]; var oldestInfiniteLifetimeParticle = this.m_indexByExpirationTimeBuffer.data[index]; this.DestroyParticle(this.m_expirationTimeBuffer.data[oldestFiniteLifetimeParticle] > 0 ? oldestFiniteLifetimeParticle : oldestInfiniteLifetimeParticle, callDestructionListener); }; b2ParticleSystem.prototype.DestroyParticlesInShape = function(shape, xf, callDestructionListener) { void 0 === callDestructionListener && (callDestructionListener = false); var s_aabb = b2ParticleSystem.DestroyParticlesInShape_s_aabb; if (this.m_world.IsLocked()) throw new Error(); var callback = new b2ParticleSystem.DestroyParticlesInShapeCallback(this, shape, xf, callDestructionListener); var aabb = s_aabb; shape.ComputeAABB(aabb, xf, 0); this.m_world.QueryAABB(callback, aabb); return callback.Destroyed(); }; b2ParticleSystem.prototype.CreateParticleGroup = function(groupDef) { var s_transform = b2ParticleSystem.CreateParticleGroup_s_transform; if (this.m_world.IsLocked()) throw new Error(); var transform = s_transform; transform.SetPositionAngle(b2Maybe(groupDef.position, b2Vec2.ZERO), b2Maybe(groupDef.angle, 0)); var firstIndex = this.m_count; groupDef.shape && this.CreateParticlesWithShapeForGroup(groupDef.shape, groupDef, transform); groupDef.shapes && this.CreateParticlesWithShapesForGroup(groupDef.shapes, b2Maybe(groupDef.shapeCount, groupDef.shapes.length), groupDef, transform); if (groupDef.positionData) { var count = b2Maybe(groupDef.particleCount, groupDef.positionData.length); for (var i = 0; i < count; i++) { var p = groupDef.positionData[i]; this.CreateParticleForGroup(groupDef, transform, p); } } var lastIndex = this.m_count; var group = new b2ParticleGroup(this); group.m_firstIndex = firstIndex; group.m_lastIndex = lastIndex; group.m_strength = b2Maybe(groupDef.strength, 1); group.m_userData = groupDef.userData; group.m_transform.Copy(transform); group.m_prev = null; group.m_next = this.m_groupList; this.m_groupList && (this.m_groupList.m_prev = group); this.m_groupList = group; ++this.m_groupCount; for (var i = firstIndex; i < lastIndex; i++) this.m_groupBuffer[i] = group; this.SetGroupFlags(group, b2Maybe(groupDef.groupFlags, 0)); var filter = new b2ParticleSystem.ConnectionFilter(); this.UpdateContacts(true); this.UpdatePairsAndTriads(firstIndex, lastIndex, filter); if (groupDef.group) { this.JoinParticleGroups(groupDef.group, group); group = groupDef.group; } return group; }; b2ParticleSystem.prototype.JoinParticleGroups = function(groupA, groupB) { if (this.m_world.IsLocked()) throw new Error(); this.RotateBuffer(groupB.m_firstIndex, groupB.m_lastIndex, this.m_count); this.RotateBuffer(groupA.m_firstIndex, groupA.m_lastIndex, groupB.m_firstIndex); var filter = new b2ParticleSystem.JoinParticleGroupsFilter(groupB.m_firstIndex); this.UpdateContacts(true); this.UpdatePairsAndTriads(groupA.m_firstIndex, groupB.m_lastIndex, filter); for (var i = groupB.m_firstIndex; i < groupB.m_lastIndex; i++) this.m_groupBuffer[i] = groupA; var groupFlags = groupA.m_groupFlags | groupB.m_groupFlags; this.SetGroupFlags(groupA, groupFlags); groupA.m_lastIndex = groupB.m_lastIndex; groupB.m_firstIndex = groupB.m_lastIndex; this.DestroyParticleGroup(groupB); }; b2ParticleSystem.prototype.SplitParticleGroup = function(group) { this.UpdateContacts(true); var particleCount = group.GetParticleCount(); var nodeBuffer = b2MakeArray(particleCount, (function(index) { return new b2ParticleSystem.ParticleListNode(); })); b2ParticleSystem.InitializeParticleLists(group, nodeBuffer); this.MergeParticleListsInContact(group, nodeBuffer); var survivingList = b2ParticleSystem.FindLongestParticleList(group, nodeBuffer); this.MergeZombieParticleListNodes(group, nodeBuffer, survivingList); this.CreateParticleGroupsFromParticleList(group, nodeBuffer, survivingList); this.UpdatePairsAndTriadsWithParticleList(group, nodeBuffer); }; b2ParticleSystem.prototype.GetParticleGroupList = function() { return this.m_groupList; }; b2ParticleSystem.prototype.GetParticleGroupCount = function() { return this.m_groupCount; }; b2ParticleSystem.prototype.GetParticleCount = function() { return this.m_count; }; b2ParticleSystem.prototype.GetMaxParticleCount = function() { return this.m_def.maxCount; }; b2ParticleSystem.prototype.SetMaxParticleCount = function(count) { this.m_def.maxCount = count; }; b2ParticleSystem.prototype.GetAllParticleFlags = function() { return this.m_allParticleFlags; }; b2ParticleSystem.prototype.GetAllGroupFlags = function() { return this.m_allGroupFlags; }; b2ParticleSystem.prototype.SetPaused = function(paused) { this.m_paused = paused; }; b2ParticleSystem.prototype.GetPaused = function() { return this.m_paused; }; b2ParticleSystem.prototype.SetDensity = function(density) { this.m_def.density = density; this.m_inverseDensity = 1 / this.m_def.density; }; b2ParticleSystem.prototype.GetDensity = function() { return this.m_def.density; }; b2ParticleSystem.prototype.SetGravityScale = function(gravityScale) { this.m_def.gravityScale = gravityScale; }; b2ParticleSystem.prototype.GetGravityScale = function() { return this.m_def.gravityScale; }; b2ParticleSystem.prototype.SetDamping = function(damping) { this.m_def.dampingStrength = damping; }; b2ParticleSystem.prototype.GetDamping = function() { return this.m_def.dampingStrength; }; b2ParticleSystem.prototype.SetStaticPressureIterations = function(iterations) { this.m_def.staticPressureIterations = iterations; }; b2ParticleSystem.prototype.GetStaticPressureIterations = function() { return this.m_def.staticPressureIterations; }; b2ParticleSystem.prototype.SetRadius = function(radius) { this.m_particleDiameter = 2 * radius; this.m_squaredDiameter = this.m_particleDiameter * this.m_particleDiameter; this.m_inverseDiameter = 1 / this.m_particleDiameter; }; b2ParticleSystem.prototype.GetRadius = function() { return this.m_particleDiameter / 2; }; b2ParticleSystem.prototype.GetPositionBuffer = function() { if (!this.m_positionBuffer.data) throw new Error(); return this.m_positionBuffer.data; }; b2ParticleSystem.prototype.GetVelocityBuffer = function() { if (!this.m_velocityBuffer.data) throw new Error(); return this.m_velocityBuffer.data; }; b2ParticleSystem.prototype.GetColorBuffer = function() { this.m_colorBuffer.data = this.RequestBuffer(this.m_colorBuffer.data); return this.m_colorBuffer.data; }; b2ParticleSystem.prototype.GetGroupBuffer = function() { return this.m_groupBuffer; }; b2ParticleSystem.prototype.GetWeightBuffer = function() { return this.m_weightBuffer; }; b2ParticleSystem.prototype.GetUserDataBuffer = function() { this.m_userDataBuffer.data = this.RequestBuffer(this.m_userDataBuffer.data); return this.m_userDataBuffer.data; }; b2ParticleSystem.prototype.GetFlagsBuffer = function() { if (!this.m_flagsBuffer.data) throw new Error(); return this.m_flagsBuffer.data; }; b2ParticleSystem.prototype.SetParticleFlags = function(index, newFlags) { if (!this.m_flagsBuffer.data) throw new Error(); var oldFlags = this.m_flagsBuffer.data[index]; oldFlags & ~newFlags && (this.m_needsUpdateAllParticleFlags = true); if (~this.m_allParticleFlags & newFlags) { newFlags & exports.b2ParticleFlag.b2_tensileParticle && (this.m_accumulation2Buffer = this.RequestBuffer(this.m_accumulation2Buffer)); newFlags & exports.b2ParticleFlag.b2_colorMixingParticle && (this.m_colorBuffer.data = this.RequestBuffer(this.m_colorBuffer.data)); this.m_allParticleFlags |= newFlags; } this.m_flagsBuffer.data[index] = newFlags; }; b2ParticleSystem.prototype.GetParticleFlags = function(index) { if (!this.m_flagsBuffer.data) throw new Error(); return this.m_flagsBuffer.data[index]; }; b2ParticleSystem.prototype.SetFlagsBuffer = function(buffer, capacity) { this.SetUserOverridableBuffer(this.m_flagsBuffer, buffer, capacity); }; b2ParticleSystem.prototype.SetPositionBuffer = function(buffer, capacity) { this.SetUserOverridableBuffer(this.m_positionBuffer, buffer, capacity); }; b2ParticleSystem.prototype.SetVelocityBuffer = function(buffer, capacity) { this.SetUserOverridableBuffer(this.m_velocityBuffer, buffer, capacity); }; b2ParticleSystem.prototype.SetColorBuffer = function(buffer, capacity) { this.SetUserOverridableBuffer(this.m_colorBuffer, buffer, capacity); }; b2ParticleSystem.prototype.SetUserDataBuffer = function(buffer, capacity) { this.SetUserOverridableBuffer(this.m_userDataBuffer, buffer, capacity); }; b2ParticleSystem.prototype.GetContacts = function() { return this.m_contactBuffer.data; }; b2ParticleSystem.prototype.GetContactCount = function() { return this.m_contactBuffer.count; }; b2ParticleSystem.prototype.GetBodyContacts = function() { return this.m_bodyContactBuffer.data; }; b2ParticleSystem.prototype.GetBodyContactCount = function() { return this.m_bodyContactBuffer.count; }; b2ParticleSystem.prototype.GetPairs = function() { return this.m_pairBuffer.data; }; b2ParticleSystem.prototype.GetPairCount = function() { return this.m_pairBuffer.count; }; b2ParticleSystem.prototype.GetTriads = function() { return this.m_triadBuffer.data; }; b2ParticleSystem.prototype.GetTriadCount = function() { return this.m_triadBuffer.count; }; b2ParticleSystem.prototype.SetStuckThreshold = function(steps) { this.m_stuckThreshold = steps; if (steps > 0) { this.m_lastBodyContactStepBuffer.data = this.RequestBuffer(this.m_lastBodyContactStepBuffer.data); this.m_bodyContactCountBuffer.data = this.RequestBuffer(this.m_bodyContactCountBuffer.data); this.m_consecutiveContactStepsBuffer.data = this.RequestBuffer(this.m_consecutiveContactStepsBuffer.data); } }; b2ParticleSystem.prototype.GetStuckCandidates = function() { return this.m_stuckParticleBuffer.Data(); }; b2ParticleSystem.prototype.GetStuckCandidateCount = function() { return this.m_stuckParticleBuffer.GetCount(); }; b2ParticleSystem.prototype.ComputeCollisionEnergy = function() { if (!this.m_velocityBuffer.data) throw new Error(); var s_v = b2ParticleSystem.ComputeCollisionEnergy_s_v; var vel_data = this.m_velocityBuffer.data; var sum_v2 = 0; for (var k = 0; k < this.m_contactBuffer.count; k++) { var contact = this.m_contactBuffer.data[k]; var a = contact.indexA; var b = contact.indexB; var n = contact.normal; var v = b2Vec2.SubVV(vel_data[b], vel_data[a], s_v); var vn = b2Vec2.DotVV(v, n); vn < 0 && (sum_v2 += vn * vn); } return .5 * this.GetParticleMass() * sum_v2; }; b2ParticleSystem.prototype.SetStrictContactCheck = function(enabled) { this.m_def.strictContactCheck = enabled; }; b2ParticleSystem.prototype.GetStrictContactCheck = function() { return this.m_def.strictContactCheck; }; b2ParticleSystem.prototype.SetParticleLifetime = function(index, lifetime) { var initializeExpirationTimes = null === this.m_indexByExpirationTimeBuffer.data; this.m_expirationTimeBuffer.data = this.RequestBuffer(this.m_expirationTimeBuffer.data); this.m_indexByExpirationTimeBuffer.data = this.RequestBuffer(this.m_indexByExpirationTimeBuffer.data); if (initializeExpirationTimes) { var particleCount = this.GetParticleCount(); for (var i = 0; i < particleCount; ++i) this.m_indexByExpirationTimeBuffer.data[i] = i; } var quantizedLifetime = lifetime / this.m_def.lifetimeGranularity; var newExpirationTime = quantizedLifetime > 0 ? this.GetQuantizedTimeElapsed() + quantizedLifetime : quantizedLifetime; if (newExpirationTime !== this.m_expirationTimeBuffer.data[index]) { this.m_expirationTimeBuffer.data[index] = newExpirationTime; this.m_expirationTimeBufferRequiresSorting = true; } }; b2ParticleSystem.prototype.GetParticleLifetime = function(index) { return this.ExpirationTimeToLifetime(this.GetExpirationTimeBuffer()[index]); }; b2ParticleSystem.prototype.SetDestructionByAge = function(enable) { enable && this.GetExpirationTimeBuffer(); this.m_def.destroyByAge = enable; }; b2ParticleSystem.prototype.GetDestructionByAge = function() { return this.m_def.destroyByAge; }; b2ParticleSystem.prototype.GetExpirationTimeBuffer = function() { this.m_expirationTimeBuffer.data = this.RequestBuffer(this.m_expirationTimeBuffer.data); return this.m_expirationTimeBuffer.data; }; b2ParticleSystem.prototype.ExpirationTimeToLifetime = function(expirationTime) { return (expirationTime > 0 ? expirationTime - this.GetQuantizedTimeElapsed() : expirationTime) * this.m_def.lifetimeGranularity; }; b2ParticleSystem.prototype.GetIndexByExpirationTimeBuffer = function() { this.GetParticleCount() ? this.SetParticleLifetime(0, this.GetParticleLifetime(0)) : this.m_indexByExpirationTimeBuffer.data = this.RequestBuffer(this.m_indexByExpirationTimeBuffer.data); if (!this.m_indexByExpirationTimeBuffer.data) throw new Error(); return this.m_indexByExpirationTimeBuffer.data; }; b2ParticleSystem.prototype.ParticleApplyLinearImpulse = function(index, impulse) { this.ApplyLinearImpulse(index, index + 1, impulse); }; b2ParticleSystem.prototype.ApplyLinearImpulse = function(firstIndex, lastIndex, impulse) { if (!this.m_velocityBuffer.data) throw new Error(); var vel_data = this.m_velocityBuffer.data; var numParticles = lastIndex - firstIndex; var totalMass = numParticles * this.GetParticleMass(); var velocityDelta = new b2Vec2().Copy(impulse).SelfMul(1 / totalMass); for (var i = firstIndex; i < lastIndex; i++) vel_data[i].SelfAdd(velocityDelta); }; b2ParticleSystem.IsSignificantForce = function(force) { return 0 !== force.x || 0 !== force.y; }; b2ParticleSystem.prototype.ParticleApplyForce = function(index, force) { if (!this.m_flagsBuffer.data) throw new Error(); if (b2ParticleSystem.IsSignificantForce(force) && this.ForceCanBeApplied(this.m_flagsBuffer.data[index])) { this.PrepareForceBuffer(); this.m_forceBuffer[index].SelfAdd(force); } }; b2ParticleSystem.prototype.ApplyForce = function(firstIndex, lastIndex, force) { var distributedForce = new b2Vec2().Copy(force).SelfMul(1 / (lastIndex - firstIndex)); if (b2ParticleSystem.IsSignificantForce(distributedForce)) { this.PrepareForceBuffer(); for (var i = firstIndex; i < lastIndex; i++) this.m_forceBuffer[i].SelfAdd(distributedForce); } }; b2ParticleSystem.prototype.GetNext = function() { return this.m_next; }; b2ParticleSystem.prototype.QueryAABB = function(callback, aabb) { if (0 === this.m_proxyBuffer.count) return; var beginProxy = 0; var endProxy = this.m_proxyBuffer.count; var firstProxy = std_lower_bound(this.m_proxyBuffer.data, beginProxy, endProxy, b2ParticleSystem.computeTag(this.m_inverseDiameter * aabb.lowerBound.x, this.m_inverseDiameter * aabb.lowerBound.y), b2ParticleSystem.Proxy.CompareProxyTag); var lastProxy = std_upper_bound(this.m_proxyBuffer.data, firstProxy, endProxy, b2ParticleSystem.computeTag(this.m_inverseDiameter * aabb.upperBound.x, this.m_inverseDiameter * aabb.upperBound.y), b2ParticleSystem.Proxy.CompareTagProxy); if (!this.m_positionBuffer.data) throw new Error(); var pos_data = this.m_positionBuffer.data; for (var k = firstProxy; k < lastProxy; ++k) { var proxy = this.m_proxyBuffer.data[k]; var i = proxy.index; var p = pos_data[i]; if (aabb.lowerBound.x < p.x && p.x < aabb.upperBound.x && aabb.lowerBound.y < p.y && p.y < aabb.upperBound.y && !callback.ReportParticle(this, i)) break; } }; b2ParticleSystem.prototype.QueryShapeAABB = function(callback, shape, xf, childIndex) { void 0 === childIndex && (childIndex = 0); var s_aabb = b2ParticleSystem.QueryShapeAABB_s_aabb; var aabb = s_aabb; shape.ComputeAABB(aabb, xf, childIndex); this.QueryAABB(callback, aabb); }; b2ParticleSystem.prototype.QueryPointAABB = function(callback, point, slop) { void 0 === slop && (slop = b2_linearSlop); var s_aabb = b2ParticleSystem.QueryPointAABB_s_aabb; var aabb = s_aabb; aabb.lowerBound.Set(point.x - slop, point.y - slop); aabb.upperBound.Set(point.x + slop, point.y + slop); this.QueryAABB(callback, aabb); }; b2ParticleSystem.prototype.RayCast = function(callback, point1, point2) { var s_aabb = b2ParticleSystem.RayCast_s_aabb; var s_p = b2ParticleSystem.RayCast_s_p; var s_v = b2ParticleSystem.RayCast_s_v; var s_n = b2ParticleSystem.RayCast_s_n; var s_point = b2ParticleSystem.RayCast_s_point; if (0 === this.m_proxyBuffer.count) return; if (!this.m_positionBuffer.data) throw new Error(); var pos_data = this.m_positionBuffer.data; var aabb = s_aabb; b2Vec2.MinV(point1, point2, aabb.lowerBound); b2Vec2.MaxV(point1, point2, aabb.upperBound); var fraction = 1; var v = b2Vec2.SubVV(point2, point1, s_v); var v2 = b2Vec2.DotVV(v, v); var enumerator = this.GetInsideBoundsEnumerator(aabb); var i; while ((i = enumerator.GetNext()) >= 0) { var p = b2Vec2.SubVV(point1, pos_data[i], s_p); var pv = b2Vec2.DotVV(p, v); var p2 = b2Vec2.DotVV(p, p); var determinant = pv * pv - v2 * (p2 - this.m_squaredDiameter); if (determinant >= 0) { var sqrtDeterminant = b2Sqrt(determinant); var t = (-pv - sqrtDeterminant) / v2; if (t > fraction) continue; if (t < 0) { t = (-pv + sqrtDeterminant) / v2; if (t < 0 || t > fraction) continue; } var n = b2Vec2.AddVMulSV(p, t, v, s_n); n.Normalize(); var f = callback.ReportParticle(this, i, b2Vec2.AddVMulSV(point1, t, v, s_point), n, t); fraction = b2Min(fraction, f); if (fraction <= 0) break; } } }; b2ParticleSystem.prototype.ComputeAABB = function(aabb) { var particleCount = this.GetParticleCount(); aabb.lowerBound.x = +b2_maxFloat; aabb.lowerBound.y = +b2_maxFloat; aabb.upperBound.x = -b2_maxFloat; aabb.upperBound.y = -b2_maxFloat; if (!this.m_positionBuffer.data) throw new Error(); var pos_data = this.m_positionBuffer.data; for (var i = 0; i < particleCount; i++) { var p = pos_data[i]; b2Vec2.MinV(aabb.lowerBound, p, aabb.lowerBound); b2Vec2.MaxV(aabb.upperBound, p, aabb.upperBound); } aabb.lowerBound.x -= this.m_particleDiameter; aabb.lowerBound.y -= this.m_particleDiameter; aabb.upperBound.x += this.m_particleDiameter; aabb.upperBound.y += this.m_particleDiameter; }; b2ParticleSystem.prototype.FreeBuffer = function(b, capacity) { if (null === b) return; b.length = 0; }; b2ParticleSystem.prototype.FreeUserOverridableBuffer = function(b) { 0 === b.userSuppliedCapacity && this.FreeBuffer(b.data, this.m_internalAllocatedCapacity); }; b2ParticleSystem.prototype.ReallocateBuffer3 = function(oldBuffer, oldCapacity, newCapacity) { if (newCapacity <= oldCapacity) throw new Error(); var newBuffer = oldBuffer ? oldBuffer.slice() : []; newBuffer.length = newCapacity; return newBuffer; }; b2ParticleSystem.prototype.ReallocateBuffer5 = function(buffer, userSuppliedCapacity, oldCapacity, newCapacity, deferred) { if (newCapacity <= oldCapacity) throw new Error(); if (!(!userSuppliedCapacity || newCapacity <= userSuppliedCapacity)) throw new Error(); deferred && !buffer || userSuppliedCapacity || (buffer = this.ReallocateBuffer3(buffer, oldCapacity, newCapacity)); return buffer; }; b2ParticleSystem.prototype.ReallocateBuffer4 = function(buffer, oldCapacity, newCapacity, deferred) { return this.ReallocateBuffer5(buffer.data, buffer.userSuppliedCapacity, oldCapacity, newCapacity, deferred); }; b2ParticleSystem.prototype.RequestBuffer = function(buffer) { if (!buffer) { 0 === this.m_internalAllocatedCapacity && this.ReallocateInternalAllocatedBuffers(b2_minParticleSystemBufferCapacity); buffer = []; buffer.length = this.m_internalAllocatedCapacity; } return buffer; }; b2ParticleSystem.prototype.ReallocateHandleBuffers = function(newCapacity) { this.m_handleIndexBuffer.data = this.ReallocateBuffer4(this.m_handleIndexBuffer, this.m_internalAllocatedCapacity, newCapacity, true); }; b2ParticleSystem.prototype.ReallocateInternalAllocatedBuffers = function(capacity) { function LimitCapacity(capacity, maxCount) { return maxCount && capacity > maxCount ? maxCount : capacity; } capacity = LimitCapacity(capacity, this.m_def.maxCount); capacity = LimitCapacity(capacity, this.m_flagsBuffer.userSuppliedCapacity); capacity = LimitCapacity(capacity, this.m_positionBuffer.userSuppliedCapacity); capacity = LimitCapacity(capacity, this.m_velocityBuffer.userSuppliedCapacity); capacity = LimitCapacity(capacity, this.m_colorBuffer.userSuppliedCapacity); capacity = LimitCapacity(capacity, this.m_userDataBuffer.userSuppliedCapacity); if (this.m_internalAllocatedCapacity < capacity) { this.ReallocateHandleBuffers(capacity); this.m_flagsBuffer.data = this.ReallocateBuffer4(this.m_flagsBuffer, this.m_internalAllocatedCapacity, capacity, false); var stuck = this.m_stuckThreshold > 0; this.m_lastBodyContactStepBuffer.data = this.ReallocateBuffer4(this.m_lastBodyContactStepBuffer, this.m_internalAllocatedCapacity, capacity, stuck); this.m_bodyContactCountBuffer.data = this.ReallocateBuffer4(this.m_bodyContactCountBuffer, this.m_internalAllocatedCapacity, capacity, stuck); this.m_consecutiveContactStepsBuffer.data = this.ReallocateBuffer4(this.m_consecutiveContactStepsBuffer, this.m_internalAllocatedCapacity, capacity, stuck); this.m_positionBuffer.data = this.ReallocateBuffer4(this.m_positionBuffer, this.m_internalAllocatedCapacity, capacity, false); this.m_velocityBuffer.data = this.ReallocateBuffer4(this.m_velocityBuffer, this.m_internalAllocatedCapacity, capacity, false); this.m_forceBuffer = this.ReallocateBuffer5(this.m_forceBuffer, 0, this.m_internalAllocatedCapacity, capacity, false); this.m_weightBuffer = this.ReallocateBuffer5(this.m_weightBuffer, 0, this.m_internalAllocatedCapacity, capacity, false); this.m_staticPressureBuffer = this.ReallocateBuffer5(this.m_staticPressureBuffer, 0, this.m_internalAllocatedCapacity, capacity, true); this.m_accumulationBuffer = this.ReallocateBuffer5(this.m_accumulationBuffer, 0, this.m_internalAllocatedCapacity, capacity, false); this.m_accumulation2Buffer = this.ReallocateBuffer5(this.m_accumulation2Buffer, 0, this.m_internalAllocatedCapacity, capacity, true); this.m_depthBuffer = this.ReallocateBuffer5(this.m_depthBuffer, 0, this.m_internalAllocatedCapacity, capacity, true); this.m_colorBuffer.data = this.ReallocateBuffer4(this.m_colorBuffer, this.m_internalAllocatedCapacity, capacity, true); this.m_groupBuffer = this.ReallocateBuffer5(this.m_groupBuffer, 0, this.m_internalAllocatedCapacity, capacity, false); this.m_userDataBuffer.data = this.ReallocateBuffer4(this.m_userDataBuffer, this.m_internalAllocatedCapacity, capacity, true); this.m_expirationTimeBuffer.data = this.ReallocateBuffer4(this.m_expirationTimeBuffer, this.m_internalAllocatedCapacity, capacity, true); this.m_indexByExpirationTimeBuffer.data = this.ReallocateBuffer4(this.m_indexByExpirationTimeBuffer, this.m_internalAllocatedCapacity, capacity, false); this.m_internalAllocatedCapacity = capacity; } }; b2ParticleSystem.prototype.CreateParticleForGroup = function(groupDef, xf, p) { var particleDef = new b2ParticleDef(); particleDef.flags = b2Maybe(groupDef.flags, 0); b2Transform.MulXV(xf, p, particleDef.position); b2Vec2.AddVV(b2Maybe(groupDef.linearVelocity, b2Vec2.ZERO), b2Vec2.CrossSV(b2Maybe(groupDef.angularVelocity, 0), b2Vec2.SubVV(particleDef.position, b2Maybe(groupDef.position, b2Vec2.ZERO), b2Vec2.s_t0), b2Vec2.s_t0), particleDef.velocity); particleDef.color.Copy(b2Maybe(groupDef.color, b2Color.ZERO)); particleDef.lifetime = b2Maybe(groupDef.lifetime, 0); particleDef.userData = groupDef.userData; this.CreateParticle(particleDef); }; b2ParticleSystem.prototype.CreateParticlesStrokeShapeForGroup = function(shape, groupDef, xf) { var s_edge = b2ParticleSystem.CreateParticlesStrokeShapeForGroup_s_edge; var s_d = b2ParticleSystem.CreateParticlesStrokeShapeForGroup_s_d; var s_p = b2ParticleSystem.CreateParticlesStrokeShapeForGroup_s_p; var stride = b2Maybe(groupDef.stride, 0); 0 === stride && (stride = this.GetParticleStride()); var positionOnEdge = 0; var childCount = shape.GetChildCount(); for (var childIndex = 0; childIndex < childCount; childIndex++) { var edge = null; if (shape.GetType() === exports.b2ShapeType.e_edgeShape) edge = shape; else { edge = s_edge; shape.GetChildEdge(edge, childIndex); } var d = b2Vec2.SubVV(edge.m_vertex2, edge.m_vertex1, s_d); var edgeLength = d.Length(); while (positionOnEdge < edgeLength) { var p = b2Vec2.AddVMulSV(edge.m_vertex1, positionOnEdge / edgeLength, d, s_p); this.CreateParticleForGroup(groupDef, xf, p); positionOnEdge += stride; } positionOnEdge -= edgeLength; } }; b2ParticleSystem.prototype.CreateParticlesFillShapeForGroup = function(shape, groupDef, xf) { var s_aabb = b2ParticleSystem.CreateParticlesFillShapeForGroup_s_aabb; var s_p = b2ParticleSystem.CreateParticlesFillShapeForGroup_s_p; var stride = b2Maybe(groupDef.stride, 0); 0 === stride && (stride = this.GetParticleStride()); var identity = b2Transform.IDENTITY; var aabb = s_aabb; shape.ComputeAABB(aabb, identity, 0); for (var y = Math.floor(aabb.lowerBound.y / stride) * stride; y < aabb.upperBound.y; y += stride) for (var x = Math.floor(aabb.lowerBound.x / stride) * stride; x < aabb.upperBound.x; x += stride) { var p = s_p.Set(x, y); shape.TestPoint(identity, p) && this.CreateParticleForGroup(groupDef, xf, p); } }; b2ParticleSystem.prototype.CreateParticlesWithShapeForGroup = function(shape, groupDef, xf) { switch (shape.GetType()) { case exports.b2ShapeType.e_edgeShape: case exports.b2ShapeType.e_chainShape: this.CreateParticlesStrokeShapeForGroup(shape, groupDef, xf); break; case exports.b2ShapeType.e_polygonShape: case exports.b2ShapeType.e_circleShape: this.CreateParticlesFillShapeForGroup(shape, groupDef, xf); } }; b2ParticleSystem.prototype.CreateParticlesWithShapesForGroup = function(shapes, shapeCount, groupDef, xf) { var compositeShape = new b2ParticleSystem.CompositeShape(shapes, shapeCount); this.CreateParticlesFillShapeForGroup(compositeShape, groupDef, xf); }; b2ParticleSystem.prototype.CloneParticle = function(oldIndex, group) { var def = new b2ParticleDef(); if (!this.m_flagsBuffer.data) throw new Error(); if (!this.m_positionBuffer.data) throw new Error(); if (!this.m_velocityBuffer.data) throw new Error(); def.flags = this.m_flagsBuffer.data[oldIndex]; def.position.Copy(this.m_positionBuffer.data[oldIndex]); def.velocity.Copy(this.m_velocityBuffer.data[oldIndex]); this.m_colorBuffer.data && def.color.Copy(this.m_colorBuffer.data[oldIndex]); this.m_userDataBuffer.data && (def.userData = this.m_userDataBuffer.data[oldIndex]); def.group = group; var newIndex = this.CreateParticle(def); if (this.m_handleIndexBuffer.data) { var handle = this.m_handleIndexBuffer.data[oldIndex]; handle && handle.SetIndex(newIndex); this.m_handleIndexBuffer.data[newIndex] = handle; this.m_handleIndexBuffer.data[oldIndex] = null; } this.m_lastBodyContactStepBuffer.data && (this.m_lastBodyContactStepBuffer.data[newIndex] = this.m_lastBodyContactStepBuffer.data[oldIndex]); this.m_bodyContactCountBuffer.data && (this.m_bodyContactCountBuffer.data[newIndex] = this.m_bodyContactCountBuffer.data[oldIndex]); this.m_consecutiveContactStepsBuffer.data && (this.m_consecutiveContactStepsBuffer.data[newIndex] = this.m_consecutiveContactStepsBuffer.data[oldIndex]); this.m_hasForce && this.m_forceBuffer[newIndex].Copy(this.m_forceBuffer[oldIndex]); this.m_staticPressureBuffer && (this.m_staticPressureBuffer[newIndex] = this.m_staticPressureBuffer[oldIndex]); this.m_depthBuffer && (this.m_depthBuffer[newIndex] = this.m_depthBuffer[oldIndex]); this.m_expirationTimeBuffer.data && (this.m_expirationTimeBuffer.data[newIndex] = this.m_expirationTimeBuffer.data[oldIndex]); return newIndex; }; b2ParticleSystem.prototype.DestroyParticlesInGroup = function(group, callDestructionListener) { void 0 === callDestructionListener && (callDestructionListener = false); for (var i = group.m_firstIndex; i < group.m_lastIndex; i++) this.DestroyParticle(i, callDestructionListener); }; b2ParticleSystem.prototype.DestroyParticleGroup = function(group) { this.m_world.m_destructionListener && this.m_world.m_destructionListener.SayGoodbyeParticleGroup(group); this.SetGroupFlags(group, 0); for (var i = group.m_firstIndex; i < group.m_lastIndex; i++) this.m_groupBuffer[i] = null; group.m_prev && (group.m_prev.m_next = group.m_next); group.m_next && (group.m_next.m_prev = group.m_prev); group === this.m_groupList && (this.m_groupList = group.m_next); --this.m_groupCount; }; b2ParticleSystem.ParticleCanBeConnected = function(flags, group) { return 0 !== (flags & (exports.b2ParticleFlag.b2_wallParticle | exports.b2ParticleFlag.b2_springParticle | exports.b2ParticleFlag.b2_elasticParticle)) || null !== group && 0 !== (group.GetGroupFlags() & exports.b2ParticleGroupFlag.b2_rigidParticleGroup); }; b2ParticleSystem.prototype.UpdatePairsAndTriads = function(firstIndex, lastIndex, filter) { var s_dab = b2ParticleSystem.UpdatePairsAndTriads_s_dab; var s_dbc = b2ParticleSystem.UpdatePairsAndTriads_s_dbc; var s_dca = b2ParticleSystem.UpdatePairsAndTriads_s_dca; if (!this.m_flagsBuffer.data) throw new Error(); if (!this.m_positionBuffer.data) throw new Error(); if (!this.m_velocityBuffer.data) throw new Error(); var pos_data = this.m_positionBuffer.data; var particleFlags = 0; for (var i = firstIndex; i < lastIndex; i++) particleFlags |= this.m_flagsBuffer.data[i]; if (particleFlags & b2ParticleSystem.k_pairFlags) for (var k = 0; k < this.m_contactBuffer.count; k++) { var contact = this.m_contactBuffer.data[k]; var a = contact.indexA; var b = contact.indexB; var af = this.m_flagsBuffer.data[a]; var bf = this.m_flagsBuffer.data[b]; var groupA = this.m_groupBuffer[a]; var groupB = this.m_groupBuffer[b]; if (a >= firstIndex && a < lastIndex && b >= firstIndex && b < lastIndex && !((af | bf) & exports.b2ParticleFlag.b2_zombieParticle) && (af | bf) & b2ParticleSystem.k_pairFlags && (filter.IsNecessary(a) || filter.IsNecessary(b)) && b2ParticleSystem.ParticleCanBeConnected(af, groupA) && b2ParticleSystem.ParticleCanBeConnected(bf, groupB) && filter.ShouldCreatePair(a, b)) { var pair = this.m_pairBuffer.data[this.m_pairBuffer.Append()]; pair.indexA = a; pair.indexB = b; pair.flags = contact.flags; pair.strength = b2Min(groupA ? groupA.m_strength : 1, groupB ? groupB.m_strength : 1); pair.distance = b2Vec2.DistanceVV(pos_data[a], pos_data[b]); } std_stable_sort(this.m_pairBuffer.data, 0, this.m_pairBuffer.count, b2ParticleSystem.ComparePairIndices); this.m_pairBuffer.Unique(b2ParticleSystem.MatchPairIndices); } if (particleFlags & b2ParticleSystem.k_triadFlags) { var diagram = new b2VoronoiDiagram(lastIndex - firstIndex); for (var i = firstIndex; i < lastIndex; i++) { var flags = this.m_flagsBuffer.data[i]; var group = this.m_groupBuffer[i]; flags & exports.b2ParticleFlag.b2_zombieParticle || !b2ParticleSystem.ParticleCanBeConnected(flags, group) || diagram.AddGenerator(pos_data[i], i, filter.IsNecessary(i)); } var stride = this.GetParticleStride(); diagram.Generate(stride / 2, 2 * stride); var system_1 = this; var callback = function(a, b, c) { if (!system_1.m_flagsBuffer.data) throw new Error(); var af = system_1.m_flagsBuffer.data[a]; var bf = system_1.m_flagsBuffer.data[b]; var cf = system_1.m_flagsBuffer.data[c]; if ((af | bf | cf) & b2ParticleSystem.k_triadFlags && filter.ShouldCreateTriad(a, b, c)) { var pa = pos_data[a]; var pb = pos_data[b]; var pc = pos_data[c]; var dab = b2Vec2.SubVV(pa, pb, s_dab); var dbc = b2Vec2.SubVV(pb, pc, s_dbc); var dca = b2Vec2.SubVV(pc, pa, s_dca); var maxDistanceSquared = b2_maxTriadDistanceSquared * system_1.m_squaredDiameter; if (b2Vec2.DotVV(dab, dab) > maxDistanceSquared || b2Vec2.DotVV(dbc, dbc) > maxDistanceSquared || b2Vec2.DotVV(dca, dca) > maxDistanceSquared) return; var groupA = system_1.m_groupBuffer[a]; var groupB = system_1.m_groupBuffer[b]; var groupC = system_1.m_groupBuffer[c]; var triad = system_1.m_triadBuffer.data[system_1.m_triadBuffer.Append()]; triad.indexA = a; triad.indexB = b; triad.indexC = c; triad.flags = af | bf | cf; triad.strength = b2Min(b2Min(groupA ? groupA.m_strength : 1, groupB ? groupB.m_strength : 1), groupC ? groupC.m_strength : 1); var midPoint_x = (pa.x + pb.x + pc.x) / 3; var midPoint_y = (pa.y + pb.y + pc.y) / 3; triad.pa.x = pa.x - midPoint_x; triad.pa.y = pa.y - midPoint_y; triad.pb.x = pb.x - midPoint_x; triad.pb.y = pb.y - midPoint_y; triad.pc.x = pc.x - midPoint_x; triad.pc.y = pc.y - midPoint_y; triad.ka = -b2Vec2.DotVV(dca, dab); triad.kb = -b2Vec2.DotVV(dab, dbc); triad.kc = -b2Vec2.DotVV(dbc, dca); triad.s = b2Vec2.CrossVV(pa, pb) + b2Vec2.CrossVV(pb, pc) + b2Vec2.CrossVV(pc, pa); } }; diagram.GetNodes(callback); std_stable_sort(this.m_triadBuffer.data, 0, this.m_triadBuffer.count, b2ParticleSystem.CompareTriadIndices); this.m_triadBuffer.Unique(b2ParticleSystem.MatchTriadIndices); } }; b2ParticleSystem.prototype.UpdatePairsAndTriadsWithReactiveParticles = function() { var filter = new b2ParticleSystem.ReactiveFilter(this.m_flagsBuffer); this.UpdatePairsAndTriads(0, this.m_count, filter); if (!this.m_flagsBuffer.data) throw new Error(); for (var i = 0; i < this.m_count; i++) this.m_flagsBuffer.data[i] &= ~exports.b2ParticleFlag.b2_reactiveParticle; this.m_allParticleFlags &= ~exports.b2ParticleFlag.b2_reactiveParticle; }; b2ParticleSystem.ComparePairIndices = function(a, b) { var diffA = a.indexA - b.indexA; if (0 !== diffA) return diffA < 0; return a.indexB < b.indexB; }; b2ParticleSystem.MatchPairIndices = function(a, b) { return a.indexA === b.indexA && a.indexB === b.indexB; }; b2ParticleSystem.CompareTriadIndices = function(a, b) { var diffA = a.indexA - b.indexA; if (0 !== diffA) return diffA < 0; var diffB = a.indexB - b.indexB; if (0 !== diffB) return diffB < 0; return a.indexC < b.indexC; }; b2ParticleSystem.MatchTriadIndices = function(a, b) { return a.indexA === b.indexA && a.indexB === b.indexB && a.indexC === b.indexC; }; b2ParticleSystem.InitializeParticleLists = function(group, nodeBuffer) { var bufferIndex = group.GetBufferIndex(); var particleCount = group.GetParticleCount(); for (var i = 0; i < particleCount; i++) { var node = nodeBuffer[i]; node.list = node; node.next = null; node.count = 1; node.index = i + bufferIndex; } }; b2ParticleSystem.prototype.MergeParticleListsInContact = function(group, nodeBuffer) { var bufferIndex = group.GetBufferIndex(); for (var k = 0; k < this.m_contactBuffer.count; k++) { var contact = this.m_contactBuffer.data[k]; var a = contact.indexA; var b = contact.indexB; if (!group.ContainsParticle(a) || !group.ContainsParticle(b)) continue; var listA = nodeBuffer[a - bufferIndex].list; var listB = nodeBuffer[b - bufferIndex].list; if (listA === listB) continue; if (listA.count < listB.count) { var _tmp = listA; listA = listB; listB = _tmp; } b2ParticleSystem.MergeParticleLists(listA, listB); } }; b2ParticleSystem.MergeParticleLists = function(listA, listB) { for (var b = listB; ;) { b.list = listA; var nextB = b.next; if (!nextB) { b.next = listA.next; break; } b = nextB; } listA.next = listB; listA.count += listB.count; listB.count = 0; }; b2ParticleSystem.FindLongestParticleList = function(group, nodeBuffer) { var particleCount = group.GetParticleCount(); var result = nodeBuffer[0]; for (var i = 0; i < particleCount; i++) { var node = nodeBuffer[i]; result.count < node.count && (result = node); } return result; }; b2ParticleSystem.prototype.MergeZombieParticleListNodes = function(group, nodeBuffer, survivingList) { if (!this.m_flagsBuffer.data) throw new Error(); var particleCount = group.GetParticleCount(); for (var i = 0; i < particleCount; i++) { var node = nodeBuffer[i]; node !== survivingList && this.m_flagsBuffer.data[node.index] & exports.b2ParticleFlag.b2_zombieParticle && b2ParticleSystem.MergeParticleListAndNode(survivingList, node); } }; b2ParticleSystem.MergeParticleListAndNode = function(list, node) { node.list = list; node.next = list.next; list.next = node; list.count++; node.count = 0; }; b2ParticleSystem.prototype.CreateParticleGroupsFromParticleList = function(group, nodeBuffer, survivingList) { if (!this.m_flagsBuffer.data) throw new Error(); var particleCount = group.GetParticleCount(); var def = new b2ParticleGroupDef(); def.groupFlags = group.GetGroupFlags(); def.userData = group.GetUserData(); for (var i = 0; i < particleCount; i++) { var list = nodeBuffer[i]; if (!list.count || list === survivingList) continue; var newGroup = this.CreateParticleGroup(def); for (var node = list; node; node = node.next) { var oldIndex = node.index; var newIndex = this.CloneParticle(oldIndex, newGroup); this.m_flagsBuffer.data[oldIndex] |= exports.b2ParticleFlag.b2_zombieParticle; node.index = newIndex; } } }; b2ParticleSystem.prototype.UpdatePairsAndTriadsWithParticleList = function(group, nodeBuffer) { var bufferIndex = group.GetBufferIndex(); for (var k = 0; k < this.m_pairBuffer.count; k++) { var pair = this.m_pairBuffer.data[k]; var a = pair.indexA; var b = pair.indexB; group.ContainsParticle(a) && (pair.indexA = nodeBuffer[a - bufferIndex].index); group.ContainsParticle(b) && (pair.indexB = nodeBuffer[b - bufferIndex].index); } for (var k = 0; k < this.m_triadBuffer.count; k++) { var triad = this.m_triadBuffer.data[k]; var a = triad.indexA; var b = triad.indexB; var c = triad.indexC; group.ContainsParticle(a) && (triad.indexA = nodeBuffer[a - bufferIndex].index); group.ContainsParticle(b) && (triad.indexB = nodeBuffer[b - bufferIndex].index); group.ContainsParticle(c) && (triad.indexC = nodeBuffer[c - bufferIndex].index); } }; b2ParticleSystem.prototype.ComputeDepth = function() { var contactGroups = []; var contactGroupsCount = 0; for (var k = 0; k < this.m_contactBuffer.count; k++) { var contact = this.m_contactBuffer.data[k]; var a = contact.indexA; var b = contact.indexB; var groupA = this.m_groupBuffer[a]; var groupB = this.m_groupBuffer[b]; groupA && groupA === groupB && groupA.m_groupFlags & exports.b2ParticleGroupFlag.b2_particleGroupNeedsUpdateDepth && (contactGroups[contactGroupsCount++] = contact); } var groupsToUpdate = []; var groupsToUpdateCount = 0; for (var group = this.m_groupList; group; group = group.GetNext()) if (group.m_groupFlags & exports.b2ParticleGroupFlag.b2_particleGroupNeedsUpdateDepth) { groupsToUpdate[groupsToUpdateCount++] = group; this.SetGroupFlags(group, group.m_groupFlags & ~exports.b2ParticleGroupFlag.b2_particleGroupNeedsUpdateDepth); for (var i = group.m_firstIndex; i < group.m_lastIndex; i++) this.m_accumulationBuffer[i] = 0; } for (var k = 0; k < contactGroupsCount; k++) { var contact = contactGroups[k]; var a = contact.indexA; var b = contact.indexB; var w = contact.weight; this.m_accumulationBuffer[a] += w; this.m_accumulationBuffer[b] += w; } for (var i = 0; i < groupsToUpdateCount; i++) { var group = groupsToUpdate[i]; for (var i_1 = group.m_firstIndex; i_1 < group.m_lastIndex; i_1++) { var w = this.m_accumulationBuffer[i_1]; this.m_depthBuffer[i_1] = w < .8 ? 0 : b2_maxFloat; } } var iterationCount = b2Sqrt(this.m_count) >> 0; for (var t = 0; t < iterationCount; t++) { var updated = false; for (var k = 0; k < contactGroupsCount; k++) { var contact = contactGroups[k]; var a = contact.indexA; var b = contact.indexB; var r = 1 - contact.weight; var ap0 = this.m_depthBuffer[a]; var bp0 = this.m_depthBuffer[b]; var ap1 = bp0 + r; var bp1 = ap0 + r; if (ap0 > ap1) { this.m_depthBuffer[a] = ap1; updated = true; } if (bp0 > bp1) { this.m_depthBuffer[b] = bp1; updated = true; } } if (!updated) break; } for (var i = 0; i < groupsToUpdateCount; i++) { var group = groupsToUpdate[i]; for (var i_2 = group.m_firstIndex; i_2 < group.m_lastIndex; i_2++) this.m_depthBuffer[i_2] < b2_maxFloat ? this.m_depthBuffer[i_2] *= this.m_particleDiameter : this.m_depthBuffer[i_2] = 0; } }; b2ParticleSystem.prototype.GetInsideBoundsEnumerator = function(aabb) { var lowerTag = b2ParticleSystem.computeTag(this.m_inverseDiameter * aabb.lowerBound.x - 1, this.m_inverseDiameter * aabb.lowerBound.y - 1); var upperTag = b2ParticleSystem.computeTag(this.m_inverseDiameter * aabb.upperBound.x + 1, this.m_inverseDiameter * aabb.upperBound.y + 1); var beginProxy = 0; var endProxy = this.m_proxyBuffer.count; var firstProxy = std_lower_bound(this.m_proxyBuffer.data, beginProxy, endProxy, lowerTag, b2ParticleSystem.Proxy.CompareProxyTag); var lastProxy = std_upper_bound(this.m_proxyBuffer.data, beginProxy, endProxy, upperTag, b2ParticleSystem.Proxy.CompareTagProxy); return new b2ParticleSystem.InsideBoundsEnumerator(this, lowerTag, upperTag, firstProxy, lastProxy); }; b2ParticleSystem.prototype.UpdateAllParticleFlags = function() { if (!this.m_flagsBuffer.data) throw new Error(); this.m_allParticleFlags = 0; for (var i = 0; i < this.m_count; i++) this.m_allParticleFlags |= this.m_flagsBuffer.data[i]; this.m_needsUpdateAllParticleFlags = false; }; b2ParticleSystem.prototype.UpdateAllGroupFlags = function() { this.m_allGroupFlags = 0; for (var group = this.m_groupList; group; group = group.GetNext()) this.m_allGroupFlags |= group.m_groupFlags; this.m_needsUpdateAllGroupFlags = false; }; b2ParticleSystem.prototype.AddContact = function(a, b, contacts) { if (!this.m_flagsBuffer.data) throw new Error(); if (!this.m_positionBuffer.data) throw new Error(); var s_d = b2ParticleSystem.AddContact_s_d; var pos_data = this.m_positionBuffer.data; var d = b2Vec2.SubVV(pos_data[b], pos_data[a], s_d); var distBtParticlesSq = b2Vec2.DotVV(d, d); if (distBtParticlesSq < this.m_squaredDiameter) { var invD = b2InvSqrt(distBtParticlesSq); isFinite(invD) || (invD = 198177537e11); var contact = this.m_contactBuffer.data[this.m_contactBuffer.Append()]; contact.indexA = a; contact.indexB = b; contact.flags = this.m_flagsBuffer.data[a] | this.m_flagsBuffer.data[b]; contact.weight = 1 - distBtParticlesSq * invD * this.m_inverseDiameter; b2Vec2.MulSV(invD, d, contact.normal); } }; b2ParticleSystem.prototype.FindContacts_Reference = function(contacts) { var beginProxy = 0; var endProxy = this.m_proxyBuffer.count; this.m_contactBuffer.count = 0; for (var a = beginProxy, c = beginProxy; a < endProxy; a++) { var rightTag = b2ParticleSystem.computeRelativeTag(this.m_proxyBuffer.data[a].tag, 1, 0); for (var b = a + 1; b < endProxy; b++) { if (rightTag < this.m_proxyBuffer.data[b].tag) break; this.AddContact(this.m_proxyBuffer.data[a].index, this.m_proxyBuffer.data[b].index, this.m_contactBuffer); } var bottomLeftTag = b2ParticleSystem.computeRelativeTag(this.m_proxyBuffer.data[a].tag, -1, 1); for (;c < endProxy; c++) if (bottomLeftTag <= this.m_proxyBuffer.data[c].tag) break; var bottomRightTag = b2ParticleSystem.computeRelativeTag(this.m_proxyBuffer.data[a].tag, 1, 1); for (var b = c; b < endProxy; b++) { if (bottomRightTag < this.m_proxyBuffer.data[b].tag) break; this.AddContact(this.m_proxyBuffer.data[a].index, this.m_proxyBuffer.data[b].index, this.m_contactBuffer); } } }; b2ParticleSystem.prototype.FindContacts = function(contacts) { this.FindContacts_Reference(contacts); }; b2ParticleSystem.prototype.UpdateProxies_Reference = function(proxies) { if (!this.m_positionBuffer.data) throw new Error(); var pos_data = this.m_positionBuffer.data; var inv_diam = this.m_inverseDiameter; for (var k = 0; k < this.m_proxyBuffer.count; ++k) { var proxy = this.m_proxyBuffer.data[k]; var i = proxy.index; var p = pos_data[i]; proxy.tag = b2ParticleSystem.computeTag(inv_diam * p.x, inv_diam * p.y); } }; b2ParticleSystem.prototype.UpdateProxies = function(proxies) { this.UpdateProxies_Reference(proxies); }; b2ParticleSystem.prototype.SortProxies = function(proxies) { std_sort(this.m_proxyBuffer.data, 0, this.m_proxyBuffer.count, b2ParticleSystem.Proxy.CompareProxyProxy); }; b2ParticleSystem.prototype.FilterContacts = function(contacts) { var contactFilter = this.GetParticleContactFilter(); if (null === contactFilter) return; var system = this; var predicate = function(contact) { return 0 !== (contact.flags & exports.b2ParticleFlag.b2_particleContactFilterParticle) && !contactFilter.ShouldCollideParticleParticle(system, contact.indexA, contact.indexB); }; this.m_contactBuffer.RemoveIf(predicate); }; b2ParticleSystem.prototype.NotifyContactListenerPreContact = function(particlePairs) { var contactListener = this.GetParticleContactListener(); if (null === contactListener) return; particlePairs.Initialize(this.m_contactBuffer, this.m_flagsBuffer); throw new Error(); }; b2ParticleSystem.prototype.NotifyContactListenerPostContact = function(particlePairs) { var contactListener = this.GetParticleContactListener(); if (null === contactListener) return; for (var k = 0; k < this.m_contactBuffer.count; ++k) { var contact = this.m_contactBuffer.data[k]; contactListener.BeginContactParticleParticle(this, contact); } throw new Error(); }; b2ParticleSystem.b2ParticleContactIsZombie = function(contact) { return (contact.flags & exports.b2ParticleFlag.b2_zombieParticle) === exports.b2ParticleFlag.b2_zombieParticle; }; b2ParticleSystem.prototype.UpdateContacts = function(exceptZombie) { this.UpdateProxies(this.m_proxyBuffer); this.SortProxies(this.m_proxyBuffer); var particlePairs = new b2ParticleSystem.b2ParticlePairSet(); this.NotifyContactListenerPreContact(particlePairs); this.FindContacts(this.m_contactBuffer); this.FilterContacts(this.m_contactBuffer); this.NotifyContactListenerPostContact(particlePairs); exceptZombie && this.m_contactBuffer.RemoveIf(b2ParticleSystem.b2ParticleContactIsZombie); }; b2ParticleSystem.prototype.NotifyBodyContactListenerPreContact = function(fixtureSet) { var contactListener = this.GetFixtureContactListener(); if (null === contactListener) return; fixtureSet.Initialize(this.m_bodyContactBuffer, this.m_flagsBuffer); throw new Error(); }; b2ParticleSystem.prototype.NotifyBodyContactListenerPostContact = function(fixtureSet) { var contactListener = this.GetFixtureContactListener(); if (null === contactListener) return; for (var k = 0; k < this.m_bodyContactBuffer.count; k++) { var contact = this.m_bodyContactBuffer.data[k]; contactListener.BeginContactFixtureParticle(this, contact); } throw new Error(); }; b2ParticleSystem.prototype.UpdateBodyContacts = function() { var s_aabb = b2ParticleSystem.UpdateBodyContacts_s_aabb; var fixtureSet = new b2ParticleSystem.FixtureParticleSet(); this.NotifyBodyContactListenerPreContact(fixtureSet); if (this.m_stuckThreshold > 0) { if (!this.m_bodyContactCountBuffer.data) throw new Error(); if (!this.m_lastBodyContactStepBuffer.data) throw new Error(); if (!this.m_consecutiveContactStepsBuffer.data) throw new Error(); var particleCount = this.GetParticleCount(); for (var i = 0; i < particleCount; i++) { this.m_bodyContactCountBuffer.data[i] = 0; this.m_timestamp > this.m_lastBodyContactStepBuffer.data[i] + 1 && (this.m_consecutiveContactStepsBuffer.data[i] = 0); } } this.m_bodyContactBuffer.SetCount(0); this.m_stuckParticleBuffer.SetCount(0); var aabb = s_aabb; this.ComputeAABB(aabb); var callback = new b2ParticleSystem.UpdateBodyContactsCallback(this, this.GetFixtureContactFilter()); this.m_world.QueryAABB(callback, aabb); this.m_def.strictContactCheck && this.RemoveSpuriousBodyContacts(); this.NotifyBodyContactListenerPostContact(fixtureSet); }; b2ParticleSystem.prototype.Solve = function(step) { var s_subStep = b2ParticleSystem.Solve_s_subStep; if (0 === this.m_count) return; this.m_expirationTimeBuffer.data && this.SolveLifetimes(step); this.m_allParticleFlags & exports.b2ParticleFlag.b2_zombieParticle && this.SolveZombie(); this.m_needsUpdateAllParticleFlags && this.UpdateAllParticleFlags(); this.m_needsUpdateAllGroupFlags && this.UpdateAllGroupFlags(); if (this.m_paused) return; for (this.m_iterationIndex = 0; this.m_iterationIndex < step.particleIterations; this.m_iterationIndex++) { ++this.m_timestamp; var subStep = s_subStep.Copy(step); subStep.dt /= step.particleIterations; subStep.inv_dt *= step.particleIterations; this.UpdateContacts(false); this.UpdateBodyContacts(); this.ComputeWeight(); this.m_allGroupFlags & exports.b2ParticleGroupFlag.b2_particleGroupNeedsUpdateDepth && this.ComputeDepth(); this.m_allParticleFlags & exports.b2ParticleFlag.b2_reactiveParticle && this.UpdatePairsAndTriadsWithReactiveParticles(); this.m_hasForce && this.SolveForce(subStep); this.m_allParticleFlags & exports.b2ParticleFlag.b2_viscousParticle && this.SolveViscous(); this.m_allParticleFlags & exports.b2ParticleFlag.b2_repulsiveParticle && this.SolveRepulsive(subStep); this.m_allParticleFlags & exports.b2ParticleFlag.b2_powderParticle && this.SolvePowder(subStep); this.m_allParticleFlags & exports.b2ParticleFlag.b2_tensileParticle && this.SolveTensile(subStep); this.m_allGroupFlags & exports.b2ParticleGroupFlag.b2_solidParticleGroup && this.SolveSolid(subStep); this.m_allParticleFlags & exports.b2ParticleFlag.b2_colorMixingParticle && this.SolveColorMixing(); this.SolveGravity(subStep); this.m_allParticleFlags & exports.b2ParticleFlag.b2_staticPressureParticle && this.SolveStaticPressure(subStep); this.SolvePressure(subStep); this.SolveDamping(subStep); this.m_allParticleFlags & b2ParticleSystem.k_extraDampingFlags && this.SolveExtraDamping(); this.m_allParticleFlags & exports.b2ParticleFlag.b2_elasticParticle && this.SolveElastic(subStep); this.m_allParticleFlags & exports.b2ParticleFlag.b2_springParticle && this.SolveSpring(subStep); this.LimitVelocity(subStep); this.m_allGroupFlags & exports.b2ParticleGroupFlag.b2_rigidParticleGroup && this.SolveRigidDamping(); this.m_allParticleFlags & exports.b2ParticleFlag.b2_barrierParticle && this.SolveBarrier(subStep); this.SolveCollision(subStep); this.m_allGroupFlags & exports.b2ParticleGroupFlag.b2_rigidParticleGroup && this.SolveRigid(subStep); this.m_allParticleFlags & exports.b2ParticleFlag.b2_wallParticle && this.SolveWall(); if (!this.m_positionBuffer.data) throw new Error(); if (!this.m_velocityBuffer.data) throw new Error(); for (var i = 0; i < this.m_count; i++) this.m_positionBuffer.data[i].SelfMulAdd(subStep.dt, this.m_velocityBuffer.data[i]); } }; b2ParticleSystem.prototype.SolveCollision = function(step) { var s_aabb = b2ParticleSystem.SolveCollision_s_aabb; if (!this.m_positionBuffer.data) throw new Error(); if (!this.m_velocityBuffer.data) throw new Error(); var pos_data = this.m_positionBuffer.data; var vel_data = this.m_velocityBuffer.data; var aabb = s_aabb; aabb.lowerBound.x = +b2_maxFloat; aabb.lowerBound.y = +b2_maxFloat; aabb.upperBound.x = -b2_maxFloat; aabb.upperBound.y = -b2_maxFloat; for (var i = 0; i < this.m_count; i++) { var v = vel_data[i]; var p1 = pos_data[i]; var p2_x = p1.x + step.dt * v.x; var p2_y = p1.y + step.dt * v.y; aabb.lowerBound.x = b2Min(aabb.lowerBound.x, b2Min(p1.x, p2_x)); aabb.lowerBound.y = b2Min(aabb.lowerBound.y, b2Min(p1.y, p2_y)); aabb.upperBound.x = b2Max(aabb.upperBound.x, b2Max(p1.x, p2_x)); aabb.upperBound.y = b2Max(aabb.upperBound.y, b2Max(p1.y, p2_y)); } var callback = new b2ParticleSystem.SolveCollisionCallback(this, step); this.m_world.QueryAABB(callback, aabb); }; b2ParticleSystem.prototype.LimitVelocity = function(step) { if (!this.m_velocityBuffer.data) throw new Error(); var vel_data = this.m_velocityBuffer.data; var criticalVelocitySquared = this.GetCriticalVelocitySquared(step); for (var i = 0; i < this.m_count; i++) { var v = vel_data[i]; var v2 = b2Vec2.DotVV(v, v); v2 > criticalVelocitySquared && v.SelfMul(b2Sqrt(criticalVelocitySquared / v2)); } }; b2ParticleSystem.prototype.SolveGravity = function(step) { if (!this.m_velocityBuffer.data) throw new Error(); var s_gravity = b2ParticleSystem.SolveGravity_s_gravity; var vel_data = this.m_velocityBuffer.data; var gravity = b2Vec2.MulSV(step.dt * this.m_def.gravityScale, this.m_world.GetGravity(), s_gravity); for (var i = 0; i < this.m_count; i++) vel_data[i].SelfAdd(gravity); }; b2ParticleSystem.prototype.SolveBarrier = function(step) { var s_aabb = b2ParticleSystem.SolveBarrier_s_aabb; var s_va = b2ParticleSystem.SolveBarrier_s_va; var s_vb = b2ParticleSystem.SolveBarrier_s_vb; var s_pba = b2ParticleSystem.SolveBarrier_s_pba; var s_vba = b2ParticleSystem.SolveBarrier_s_vba; var s_vc = b2ParticleSystem.SolveBarrier_s_vc; var s_pca = b2ParticleSystem.SolveBarrier_s_pca; var s_vca = b2ParticleSystem.SolveBarrier_s_vca; var s_qba = b2ParticleSystem.SolveBarrier_s_qba; var s_qca = b2ParticleSystem.SolveBarrier_s_qca; var s_dv = b2ParticleSystem.SolveBarrier_s_dv; var s_f = b2ParticleSystem.SolveBarrier_s_f; if (!this.m_flagsBuffer.data) throw new Error(); if (!this.m_positionBuffer.data) throw new Error(); if (!this.m_velocityBuffer.data) throw new Error(); var pos_data = this.m_positionBuffer.data; var vel_data = this.m_velocityBuffer.data; for (var i = 0; i < this.m_count; i++) { var flags = this.m_flagsBuffer.data[i]; 0 !== (flags & b2ParticleSystem.k_barrierWallFlags) && vel_data[i].SetZero(); } var tmax = b2_barrierCollisionTime * step.dt; var mass = this.GetParticleMass(); for (var k = 0; k < this.m_pairBuffer.count; k++) { var pair = this.m_pairBuffer.data[k]; if (pair.flags & exports.b2ParticleFlag.b2_barrierParticle) { var a = pair.indexA; var b = pair.indexB; var pa = pos_data[a]; var pb = pos_data[b]; var aabb = s_aabb; b2Vec2.MinV(pa, pb, aabb.lowerBound); b2Vec2.MaxV(pa, pb, aabb.upperBound); var aGroup = this.m_groupBuffer[a]; var bGroup = this.m_groupBuffer[b]; var va = this.GetLinearVelocity(aGroup, a, pa, s_va); var vb = this.GetLinearVelocity(bGroup, b, pb, s_vb); var pba = b2Vec2.SubVV(pb, pa, s_pba); var vba = b2Vec2.SubVV(vb, va, s_vba); var enumerator = this.GetInsideBoundsEnumerator(aabb); var c = void 0; while ((c = enumerator.GetNext()) >= 0) { var pc = pos_data[c]; var cGroup = this.m_groupBuffer[c]; if (aGroup !== cGroup && bGroup !== cGroup) { var vc = this.GetLinearVelocity(cGroup, c, pc, s_vc); var pca = b2Vec2.SubVV(pc, pa, s_pca); var vca = b2Vec2.SubVV(vc, va, s_vca); var e2 = b2Vec2.CrossVV(vba, vca); var e1 = b2Vec2.CrossVV(pba, vca) - b2Vec2.CrossVV(pca, vba); var e0 = b2Vec2.CrossVV(pba, pca); var s = void 0, t = void 0; var qba = s_qba, qca = s_qca; if (0 === e2) { if (0 === e1) continue; t = -e0 / e1; if (!(t >= 0 && t < tmax)) continue; b2Vec2.AddVMulSV(pba, t, vba, qba); b2Vec2.AddVMulSV(pca, t, vca, qca); s = b2Vec2.DotVV(qba, qca) / b2Vec2.DotVV(qba, qba); if (!(s >= 0 && s <= 1)) continue; } else { var det = e1 * e1 - 4 * e0 * e2; if (det < 0) continue; var sqrtDet = b2Sqrt(det); var t1 = (-e1 - sqrtDet) / (2 * e2); var t2 = (-e1 + sqrtDet) / (2 * e2); if (t1 > t2) { var tmp = t1; t1 = t2; t2 = tmp; } t = t1; b2Vec2.AddVMulSV(pba, t, vba, qba); b2Vec2.AddVMulSV(pca, t, vca, qca); s = b2Vec2.DotVV(qba, qca) / b2Vec2.DotVV(qba, qba); if (!(t >= 0 && t < tmax && s >= 0 && s <= 1)) { t = t2; if (!(t >= 0 && t < tmax)) continue; b2Vec2.AddVMulSV(pba, t, vba, qba); b2Vec2.AddVMulSV(pca, t, vca, qca); s = b2Vec2.DotVV(qba, qca) / b2Vec2.DotVV(qba, qba); if (!(s >= 0 && s <= 1)) continue; } } var dv = s_dv; dv.x = va.x + s * vba.x - vc.x; dv.y = va.y + s * vba.y - vc.y; var f = b2Vec2.MulSV(mass, dv, s_f); if (cGroup && this.IsRigidGroup(cGroup)) { var mass_1 = cGroup.GetMass(); var inertia = cGroup.GetInertia(); mass_1 > 0 && cGroup.m_linearVelocity.SelfMulAdd(1 / mass_1, f); inertia > 0 && (cGroup.m_angularVelocity += b2Vec2.CrossVV(b2Vec2.SubVV(pc, cGroup.GetCenter(), b2Vec2.s_t0), f) / inertia); } else vel_data[c].SelfAdd(dv); this.ParticleApplyForce(c, f.SelfMul(-step.inv_dt)); } } } } }; b2ParticleSystem.prototype.SolveStaticPressure = function(step) { if (!this.m_flagsBuffer.data) throw new Error(); this.m_staticPressureBuffer = this.RequestBuffer(this.m_staticPressureBuffer); var criticalPressure = this.GetCriticalPressure(step); var pressurePerWeight = this.m_def.staticPressureStrength * criticalPressure; var maxPressure = b2_maxParticlePressure * criticalPressure; var relaxation = this.m_def.staticPressureRelaxation; for (var t = 0; t < this.m_def.staticPressureIterations; t++) { for (var i = 0; i < this.m_count; i++) this.m_accumulationBuffer[i] = 0; for (var k = 0; k < this.m_contactBuffer.count; k++) { var contact = this.m_contactBuffer.data[k]; if (contact.flags & exports.b2ParticleFlag.b2_staticPressureParticle) { var a = contact.indexA; var b = contact.indexB; var w = contact.weight; this.m_accumulationBuffer[a] += w * this.m_staticPressureBuffer[b]; this.m_accumulationBuffer[b] += w * this.m_staticPressureBuffer[a]; } } for (var i = 0; i < this.m_count; i++) { var w = this.m_weightBuffer[i]; if (this.m_flagsBuffer.data[i] & exports.b2ParticleFlag.b2_staticPressureParticle) { var wh = this.m_accumulationBuffer[i]; var h = (wh + pressurePerWeight * (w - b2_minParticleWeight)) / (w + relaxation); this.m_staticPressureBuffer[i] = b2Clamp(h, 0, maxPressure); } else this.m_staticPressureBuffer[i] = 0; } } }; b2ParticleSystem.prototype.ComputeWeight = function() { for (var k = 0; k < this.m_count; k++) this.m_weightBuffer[k] = 0; for (var k = 0; k < this.m_bodyContactBuffer.count; k++) { var contact = this.m_bodyContactBuffer.data[k]; var a = contact.index; var w = contact.weight; this.m_weightBuffer[a] += w; } for (var k = 0; k < this.m_contactBuffer.count; k++) { var contact = this.m_contactBuffer.data[k]; var a = contact.indexA; var b = contact.indexB; var w = contact.weight; this.m_weightBuffer[a] += w; this.m_weightBuffer[b] += w; } }; b2ParticleSystem.prototype.SolvePressure = function(step) { var s_f = b2ParticleSystem.SolvePressure_s_f; if (!this.m_flagsBuffer.data) throw new Error(); if (!this.m_positionBuffer.data) throw new Error(); if (!this.m_velocityBuffer.data) throw new Error(); var pos_data = this.m_positionBuffer.data; var vel_data = this.m_velocityBuffer.data; var criticalPressure = this.GetCriticalPressure(step); var pressurePerWeight = this.m_def.pressureStrength * criticalPressure; var maxPressure = b2_maxParticlePressure * criticalPressure; for (var i = 0; i < this.m_count; i++) { var w = this.m_weightBuffer[i]; var h = pressurePerWeight * b2Max(0, w - b2_minParticleWeight); this.m_accumulationBuffer[i] = b2Min(h, maxPressure); } if (this.m_allParticleFlags & b2ParticleSystem.k_noPressureFlags) for (var i = 0; i < this.m_count; i++) this.m_flagsBuffer.data[i] & b2ParticleSystem.k_noPressureFlags && (this.m_accumulationBuffer[i] = 0); if (this.m_allParticleFlags & exports.b2ParticleFlag.b2_staticPressureParticle) for (var i = 0; i < this.m_count; i++) this.m_flagsBuffer.data[i] & exports.b2ParticleFlag.b2_staticPressureParticle && (this.m_accumulationBuffer[i] += this.m_staticPressureBuffer[i]); var velocityPerPressure = step.dt / (this.m_def.density * this.m_particleDiameter); var inv_mass = this.GetParticleInvMass(); for (var k = 0; k < this.m_bodyContactBuffer.count; k++) { var contact = this.m_bodyContactBuffer.data[k]; var a = contact.index; var b = contact.body; var w = contact.weight; var m = contact.mass; var n = contact.normal; var p = pos_data[a]; var h = this.m_accumulationBuffer[a] + pressurePerWeight * w; var f = b2Vec2.MulSV(velocityPerPressure * w * m * h, n, s_f); vel_data[a].SelfMulSub(inv_mass, f); b.ApplyLinearImpulse(f, p, true); } for (var k = 0; k < this.m_contactBuffer.count; k++) { var contact = this.m_contactBuffer.data[k]; var a = contact.indexA; var b = contact.indexB; var w = contact.weight; var n = contact.normal; var h = this.m_accumulationBuffer[a] + this.m_accumulationBuffer[b]; var f = b2Vec2.MulSV(velocityPerPressure * w * h, n, s_f); vel_data[a].SelfSub(f); vel_data[b].SelfAdd(f); } }; b2ParticleSystem.prototype.SolveDamping = function(step) { var s_v = b2ParticleSystem.SolveDamping_s_v; var s_f = b2ParticleSystem.SolveDamping_s_f; if (!this.m_positionBuffer.data) throw new Error(); if (!this.m_velocityBuffer.data) throw new Error(); var pos_data = this.m_positionBuffer.data; var vel_data = this.m_velocityBuffer.data; var linearDamping = this.m_def.dampingStrength; var quadraticDamping = 1 / this.GetCriticalVelocity(step); var inv_mass = this.GetParticleInvMass(); for (var k = 0; k < this.m_bodyContactBuffer.count; k++) { var contact = this.m_bodyContactBuffer.data[k]; var a = contact.index; var b = contact.body; var w = contact.weight; var m = contact.mass; var n = contact.normal; var p = pos_data[a]; var v = b2Vec2.SubVV(b.GetLinearVelocityFromWorldPoint(p, b2Vec2.s_t0), vel_data[a], s_v); var vn = b2Vec2.DotVV(v, n); if (vn < 0) { var damping = b2Max(linearDamping * w, b2Min(-quadraticDamping * vn, .5)); var f = b2Vec2.MulSV(damping * m * vn, n, s_f); vel_data[a].SelfMulAdd(inv_mass, f); b.ApplyLinearImpulse(f.SelfNeg(), p, true); } } for (var k = 0; k < this.m_contactBuffer.count; k++) { var contact = this.m_contactBuffer.data[k]; var a = contact.indexA; var b = contact.indexB; var w = contact.weight; var n = contact.normal; var v = b2Vec2.SubVV(vel_data[b], vel_data[a], s_v); var vn = b2Vec2.DotVV(v, n); if (vn < 0) { var damping = b2Max(linearDamping * w, b2Min(-quadraticDamping * vn, .5)); var f = b2Vec2.MulSV(damping * vn, n, s_f); vel_data[a].SelfAdd(f); vel_data[b].SelfSub(f); } } }; b2ParticleSystem.prototype.SolveRigidDamping = function() { var s_t0 = b2ParticleSystem.SolveRigidDamping_s_t0; var s_t1 = b2ParticleSystem.SolveRigidDamping_s_t1; var s_p = b2ParticleSystem.SolveRigidDamping_s_p; var s_v = b2ParticleSystem.SolveRigidDamping_s_v; var invMassA = [ 0 ], invInertiaA = [ 0 ], tangentDistanceA = [ 0 ]; var invMassB = [ 0 ], invInertiaB = [ 0 ], tangentDistanceB = [ 0 ]; if (!this.m_positionBuffer.data) throw new Error(); var pos_data = this.m_positionBuffer.data; var damping = this.m_def.dampingStrength; for (var k = 0; k < this.m_bodyContactBuffer.count; k++) { var contact = this.m_bodyContactBuffer.data[k]; var a = contact.index; var aGroup = this.m_groupBuffer[a]; if (aGroup && this.IsRigidGroup(aGroup)) { var b = contact.body; var n = contact.normal; var w = contact.weight; var p = pos_data[a]; var v = b2Vec2.SubVV(b.GetLinearVelocityFromWorldPoint(p, s_t0), aGroup.GetLinearVelocityFromWorldPoint(p, s_t1), s_v); var vn = b2Vec2.DotVV(v, n); if (vn < 0) { this.InitDampingParameterWithRigidGroupOrParticle(invMassA, invInertiaA, tangentDistanceA, true, aGroup, a, p, n); this.InitDampingParameter(invMassB, invInertiaB, tangentDistanceB, b.GetMass(), b.GetInertia() - b.GetMass() * b.GetLocalCenter().LengthSquared(), b.GetWorldCenter(), p, n); var f = damping * b2Min(w, 1) * this.ComputeDampingImpulse(invMassA[0], invInertiaA[0], tangentDistanceA[0], invMassB[0], invInertiaB[0], tangentDistanceB[0], vn); this.ApplyDamping(invMassA[0], invInertiaA[0], tangentDistanceA[0], true, aGroup, a, f, n); b.ApplyLinearImpulse(b2Vec2.MulSV(-f, n, b2Vec2.s_t0), p, true); } } } for (var k = 0; k < this.m_contactBuffer.count; k++) { var contact = this.m_contactBuffer.data[k]; var a = contact.indexA; var b = contact.indexB; var n = contact.normal; var w = contact.weight; var aGroup = this.m_groupBuffer[a]; var bGroup = this.m_groupBuffer[b]; var aRigid = this.IsRigidGroup(aGroup); var bRigid = this.IsRigidGroup(bGroup); if (aGroup !== bGroup && (aRigid || bRigid)) { var p = b2Vec2.MidVV(pos_data[a], pos_data[b], s_p); var v = b2Vec2.SubVV(this.GetLinearVelocity(bGroup, b, p, s_t0), this.GetLinearVelocity(aGroup, a, p, s_t1), s_v); var vn = b2Vec2.DotVV(v, n); if (vn < 0) { this.InitDampingParameterWithRigidGroupOrParticle(invMassA, invInertiaA, tangentDistanceA, aRigid, aGroup, a, p, n); this.InitDampingParameterWithRigidGroupOrParticle(invMassB, invInertiaB, tangentDistanceB, bRigid, bGroup, b, p, n); var f = damping * w * this.ComputeDampingImpulse(invMassA[0], invInertiaA[0], tangentDistanceA[0], invMassB[0], invInertiaB[0], tangentDistanceB[0], vn); this.ApplyDamping(invMassA[0], invInertiaA[0], tangentDistanceA[0], aRigid, aGroup, a, f, n); this.ApplyDamping(invMassB[0], invInertiaB[0], tangentDistanceB[0], bRigid, bGroup, b, -f, n); } } } }; b2ParticleSystem.prototype.SolveExtraDamping = function() { var s_v = b2ParticleSystem.SolveExtraDamping_s_v; var s_f = b2ParticleSystem.SolveExtraDamping_s_f; if (!this.m_flagsBuffer.data) throw new Error(); if (!this.m_positionBuffer.data) throw new Error(); if (!this.m_velocityBuffer.data) throw new Error(); var vel_data = this.m_velocityBuffer.data; var pos_data = this.m_positionBuffer.data; var inv_mass = this.GetParticleInvMass(); for (var k = 0; k < this.m_bodyContactBuffer.count; k++) { var contact = this.m_bodyContactBuffer.data[k]; var a = contact.index; if (this.m_flagsBuffer.data[a] & b2ParticleSystem.k_extraDampingFlags) { var b = contact.body; var m = contact.mass; var n = contact.normal; var p = pos_data[a]; var v = b2Vec2.SubVV(b.GetLinearVelocityFromWorldPoint(p, b2Vec2.s_t0), vel_data[a], s_v); var vn = b2Vec2.DotVV(v, n); if (vn < 0) { var f = b2Vec2.MulSV(.5 * m * vn, n, s_f); vel_data[a].SelfMulAdd(inv_mass, f); b.ApplyLinearImpulse(f.SelfNeg(), p, true); } } } }; b2ParticleSystem.prototype.SolveWall = function() { if (!this.m_flagsBuffer.data) throw new Error(); if (!this.m_velocityBuffer.data) throw new Error(); var vel_data = this.m_velocityBuffer.data; for (var i = 0; i < this.m_count; i++) this.m_flagsBuffer.data[i] & exports.b2ParticleFlag.b2_wallParticle && vel_data[i].SetZero(); }; b2ParticleSystem.prototype.SolveRigid = function(step) { var s_position = b2ParticleSystem.SolveRigid_s_position; var s_rotation = b2ParticleSystem.SolveRigid_s_rotation; var s_transform = b2ParticleSystem.SolveRigid_s_transform; var s_velocityTransform = b2ParticleSystem.SolveRigid_s_velocityTransform; if (!this.m_positionBuffer.data) throw new Error(); if (!this.m_velocityBuffer.data) throw new Error(); var pos_data = this.m_positionBuffer.data; var vel_data = this.m_velocityBuffer.data; for (var group = this.m_groupList; group; group = group.GetNext()) if (group.m_groupFlags & exports.b2ParticleGroupFlag.b2_rigidParticleGroup) { group.UpdateStatistics(); var rotation = s_rotation; rotation.SetAngle(step.dt * group.m_angularVelocity); var position = b2Vec2.AddVV(group.m_center, b2Vec2.SubVV(b2Vec2.MulSV(step.dt, group.m_linearVelocity, b2Vec2.s_t0), b2Rot.MulRV(rotation, group.m_center, b2Vec2.s_t1), b2Vec2.s_t0), s_position); var transform = s_transform; transform.SetPositionRotation(position, rotation); b2Transform.MulXX(transform, group.m_transform, group.m_transform); var velocityTransform = s_velocityTransform; velocityTransform.p.x = step.inv_dt * transform.p.x; velocityTransform.p.y = step.inv_dt * transform.p.y; velocityTransform.q.s = step.inv_dt * transform.q.s; velocityTransform.q.c = step.inv_dt * (transform.q.c - 1); for (var i = group.m_firstIndex; i < group.m_lastIndex; i++) b2Transform.MulXV(velocityTransform, pos_data[i], vel_data[i]); } }; b2ParticleSystem.prototype.SolveElastic = function(step) { var s_pa = b2ParticleSystem.SolveElastic_s_pa; var s_pb = b2ParticleSystem.SolveElastic_s_pb; var s_pc = b2ParticleSystem.SolveElastic_s_pc; var s_r = b2ParticleSystem.SolveElastic_s_r; var s_t0 = b2ParticleSystem.SolveElastic_s_t0; if (!this.m_positionBuffer.data) throw new Error(); if (!this.m_velocityBuffer.data) throw new Error(); var pos_data = this.m_positionBuffer.data; var vel_data = this.m_velocityBuffer.data; var elasticStrength = step.inv_dt * this.m_def.elasticStrength; for (var k = 0; k < this.m_triadBuffer.count; k++) { var triad = this.m_triadBuffer.data[k]; if (triad.flags & exports.b2ParticleFlag.b2_elasticParticle) { var a = triad.indexA; var b = triad.indexB; var c = triad.indexC; var oa = triad.pa; var ob = triad.pb; var oc = triad.pc; var pa = s_pa.Copy(pos_data[a]); var pb = s_pb.Copy(pos_data[b]); var pc = s_pc.Copy(pos_data[c]); var va = vel_data[a]; var vb = vel_data[b]; var vc = vel_data[c]; pa.SelfMulAdd(step.dt, va); pb.SelfMulAdd(step.dt, vb); pc.SelfMulAdd(step.dt, vc); var midPoint_x = (pa.x + pb.x + pc.x) / 3; var midPoint_y = (pa.y + pb.y + pc.y) / 3; pa.x -= midPoint_x; pa.y -= midPoint_y; pb.x -= midPoint_x; pb.y -= midPoint_y; pc.x -= midPoint_x; pc.y -= midPoint_y; var r = s_r; r.s = b2Vec2.CrossVV(oa, pa) + b2Vec2.CrossVV(ob, pb) + b2Vec2.CrossVV(oc, pc); r.c = b2Vec2.DotVV(oa, pa) + b2Vec2.DotVV(ob, pb) + b2Vec2.DotVV(oc, pc); var r2 = r.s * r.s + r.c * r.c; var invR = b2InvSqrt(r2); isFinite(invR) || (invR = 198177537e11); r.s *= invR; r.c *= invR; var strength = elasticStrength * triad.strength; b2Rot.MulRV(r, oa, s_t0); b2Vec2.SubVV(s_t0, pa, s_t0); b2Vec2.MulSV(strength, s_t0, s_t0); va.SelfAdd(s_t0); b2Rot.MulRV(r, ob, s_t0); b2Vec2.SubVV(s_t0, pb, s_t0); b2Vec2.MulSV(strength, s_t0, s_t0); vb.SelfAdd(s_t0); b2Rot.MulRV(r, oc, s_t0); b2Vec2.SubVV(s_t0, pc, s_t0); b2Vec2.MulSV(strength, s_t0, s_t0); vc.SelfAdd(s_t0); } } }; b2ParticleSystem.prototype.SolveSpring = function(step) { var s_pa = b2ParticleSystem.SolveSpring_s_pa; var s_pb = b2ParticleSystem.SolveSpring_s_pb; var s_d = b2ParticleSystem.SolveSpring_s_d; var s_f = b2ParticleSystem.SolveSpring_s_f; if (!this.m_positionBuffer.data) throw new Error(); if (!this.m_velocityBuffer.data) throw new Error(); var pos_data = this.m_positionBuffer.data; var vel_data = this.m_velocityBuffer.data; var springStrength = step.inv_dt * this.m_def.springStrength; for (var k = 0; k < this.m_pairBuffer.count; k++) { var pair = this.m_pairBuffer.data[k]; if (pair.flags & exports.b2ParticleFlag.b2_springParticle) { var a = pair.indexA; var b = pair.indexB; var pa = s_pa.Copy(pos_data[a]); var pb = s_pb.Copy(pos_data[b]); var va = vel_data[a]; var vb = vel_data[b]; pa.SelfMulAdd(step.dt, va); pb.SelfMulAdd(step.dt, vb); var d = b2Vec2.SubVV(pb, pa, s_d); var r0 = pair.distance; var r1 = d.Length(); var strength = springStrength * pair.strength; var f = b2Vec2.MulSV(strength * (r0 - r1) / r1, d, s_f); va.SelfSub(f); vb.SelfAdd(f); } } }; b2ParticleSystem.prototype.SolveTensile = function(step) { var s_weightedNormal = b2ParticleSystem.SolveTensile_s_weightedNormal; var s_s = b2ParticleSystem.SolveTensile_s_s; var s_f = b2ParticleSystem.SolveTensile_s_f; if (!this.m_velocityBuffer.data) throw new Error(); var vel_data = this.m_velocityBuffer.data; for (var i = 0; i < this.m_count; i++) { this.m_accumulation2Buffer[i] = new b2Vec2(); this.m_accumulation2Buffer[i].SetZero(); } for (var k = 0; k < this.m_contactBuffer.count; k++) { var contact = this.m_contactBuffer.data[k]; if (contact.flags & exports.b2ParticleFlag.b2_tensileParticle) { var a = contact.indexA; var b = contact.indexB; var w = contact.weight; var n = contact.normal; var weightedNormal = b2Vec2.MulSV((1 - w) * w, n, s_weightedNormal); this.m_accumulation2Buffer[a].SelfSub(weightedNormal); this.m_accumulation2Buffer[b].SelfAdd(weightedNormal); } } var criticalVelocity = this.GetCriticalVelocity(step); var pressureStrength = this.m_def.surfaceTensionPressureStrength * criticalVelocity; var normalStrength = this.m_def.surfaceTensionNormalStrength * criticalVelocity; var maxVelocityVariation = b2_maxParticleForce * criticalVelocity; for (var k = 0; k < this.m_contactBuffer.count; k++) { var contact = this.m_contactBuffer.data[k]; if (contact.flags & exports.b2ParticleFlag.b2_tensileParticle) { var a = contact.indexA; var b = contact.indexB; var w = contact.weight; var n = contact.normal; var h = this.m_weightBuffer[a] + this.m_weightBuffer[b]; var s = b2Vec2.SubVV(this.m_accumulation2Buffer[b], this.m_accumulation2Buffer[a], s_s); var fn = b2Min(pressureStrength * (h - 2) + normalStrength * b2Vec2.DotVV(s, n), maxVelocityVariation) * w; var f = b2Vec2.MulSV(fn, n, s_f); vel_data[a].SelfSub(f); vel_data[b].SelfAdd(f); } } }; b2ParticleSystem.prototype.SolveViscous = function() { var s_v = b2ParticleSystem.SolveViscous_s_v; var s_f = b2ParticleSystem.SolveViscous_s_f; if (!this.m_flagsBuffer.data) throw new Error(); if (!this.m_positionBuffer.data) throw new Error(); if (!this.m_velocityBuffer.data) throw new Error(); var pos_data = this.m_positionBuffer.data; var vel_data = this.m_velocityBuffer.data; var viscousStrength = this.m_def.viscousStrength; var inv_mass = this.GetParticleInvMass(); for (var k = 0; k < this.m_bodyContactBuffer.count; k++) { var contact = this.m_bodyContactBuffer.data[k]; var a = contact.index; if (this.m_flagsBuffer.data[a] & exports.b2ParticleFlag.b2_viscousParticle) { var b = contact.body; var w = contact.weight; var m = contact.mass; var p = pos_data[a]; var v = b2Vec2.SubVV(b.GetLinearVelocityFromWorldPoint(p, b2Vec2.s_t0), vel_data[a], s_v); var f = b2Vec2.MulSV(viscousStrength * m * w, v, s_f); vel_data[a].SelfMulAdd(inv_mass, f); b.ApplyLinearImpulse(f.SelfNeg(), p, true); } } for (var k = 0; k < this.m_contactBuffer.count; k++) { var contact = this.m_contactBuffer.data[k]; if (contact.flags & exports.b2ParticleFlag.b2_viscousParticle) { var a = contact.indexA; var b = contact.indexB; var w = contact.weight; var v = b2Vec2.SubVV(vel_data[b], vel_data[a], s_v); var f = b2Vec2.MulSV(viscousStrength * w, v, s_f); vel_data[a].SelfAdd(f); vel_data[b].SelfSub(f); } } }; b2ParticleSystem.prototype.SolveRepulsive = function(step) { var s_f = b2ParticleSystem.SolveRepulsive_s_f; if (!this.m_velocityBuffer.data) throw new Error(); var vel_data = this.m_velocityBuffer.data; var repulsiveStrength = this.m_def.repulsiveStrength * this.GetCriticalVelocity(step); for (var k = 0; k < this.m_contactBuffer.count; k++) { var contact = this.m_contactBuffer.data[k]; if (contact.flags & exports.b2ParticleFlag.b2_repulsiveParticle) { var a = contact.indexA; var b = contact.indexB; if (this.m_groupBuffer[a] !== this.m_groupBuffer[b]) { var w = contact.weight; var n = contact.normal; var f = b2Vec2.MulSV(repulsiveStrength * w, n, s_f); vel_data[a].SelfSub(f); vel_data[b].SelfAdd(f); } } } }; b2ParticleSystem.prototype.SolvePowder = function(step) { var s_f = b2ParticleSystem.SolvePowder_s_f; if (!this.m_flagsBuffer.data) throw new Error(); if (!this.m_positionBuffer.data) throw new Error(); if (!this.m_velocityBuffer.data) throw new Error(); var pos_data = this.m_positionBuffer.data; var vel_data = this.m_velocityBuffer.data; var powderStrength = this.m_def.powderStrength * this.GetCriticalVelocity(step); var minWeight = 1 - b2_particleStride; var inv_mass = this.GetParticleInvMass(); for (var k = 0; k < this.m_bodyContactBuffer.count; k++) { var contact = this.m_bodyContactBuffer.data[k]; var a = contact.index; if (this.m_flagsBuffer.data[a] & exports.b2ParticleFlag.b2_powderParticle) { var w = contact.weight; if (w > minWeight) { var b = contact.body; var m = contact.mass; var p = pos_data[a]; var n = contact.normal; var f = b2Vec2.MulSV(powderStrength * m * (w - minWeight), n, s_f); vel_data[a].SelfMulSub(inv_mass, f); b.ApplyLinearImpulse(f, p, true); } } } for (var k = 0; k < this.m_contactBuffer.count; k++) { var contact = this.m_contactBuffer.data[k]; if (contact.flags & exports.b2ParticleFlag.b2_powderParticle) { var w = contact.weight; if (w > minWeight) { var a = contact.indexA; var b = contact.indexB; var n = contact.normal; var f = b2Vec2.MulSV(powderStrength * (w - minWeight), n, s_f); vel_data[a].SelfSub(f); vel_data[b].SelfAdd(f); } } } }; b2ParticleSystem.prototype.SolveSolid = function(step) { var s_f = b2ParticleSystem.SolveSolid_s_f; if (!this.m_velocityBuffer.data) throw new Error(); var vel_data = this.m_velocityBuffer.data; this.m_depthBuffer = this.RequestBuffer(this.m_depthBuffer); var ejectionStrength = step.inv_dt * this.m_def.ejectionStrength; for (var k = 0; k < this.m_contactBuffer.count; k++) { var contact = this.m_contactBuffer.data[k]; var a = contact.indexA; var b = contact.indexB; if (this.m_groupBuffer[a] !== this.m_groupBuffer[b]) { var w = contact.weight; var n = contact.normal; var h = this.m_depthBuffer[a] + this.m_depthBuffer[b]; var f = b2Vec2.MulSV(ejectionStrength * h * w, n, s_f); vel_data[a].SelfSub(f); vel_data[b].SelfAdd(f); } } }; b2ParticleSystem.prototype.SolveForce = function(step) { if (!this.m_velocityBuffer.data) throw new Error(); var vel_data = this.m_velocityBuffer.data; var velocityPerForce = step.dt * this.GetParticleInvMass(); for (var i = 0; i < this.m_count; i++) vel_data[i].SelfMulAdd(velocityPerForce, this.m_forceBuffer[i]); this.m_hasForce = false; }; b2ParticleSystem.prototype.SolveColorMixing = function() { if (!this.m_flagsBuffer.data) throw new Error(); if (!this.m_colorBuffer.data) throw new Error(); var colorMixing = .5 * this.m_def.colorMixingStrength; if (colorMixing) for (var k = 0; k < this.m_contactBuffer.count; k++) { var contact = this.m_contactBuffer.data[k]; var a = contact.indexA; var b = contact.indexB; if (this.m_flagsBuffer.data[a] & this.m_flagsBuffer.data[b] & exports.b2ParticleFlag.b2_colorMixingParticle) { var colorA = this.m_colorBuffer.data[a]; var colorB = this.m_colorBuffer.data[b]; b2Color.MixColors(colorA, colorB, colorMixing); } } }; b2ParticleSystem.prototype.SolveZombie = function() { if (!this.m_flagsBuffer.data) throw new Error(); if (!this.m_positionBuffer.data) throw new Error(); if (!this.m_velocityBuffer.data) throw new Error(); var newCount = 0; var newIndices = []; for (var i = 0; i < this.m_count; i++) newIndices[i] = b2_invalidParticleIndex; var allParticleFlags = 0; for (var i = 0; i < this.m_count; i++) { var flags = this.m_flagsBuffer.data[i]; if (flags & exports.b2ParticleFlag.b2_zombieParticle) { var destructionListener = this.m_world.m_destructionListener; flags & exports.b2ParticleFlag.b2_destructionListenerParticle && destructionListener && destructionListener.SayGoodbyeParticle(this, i); if (this.m_handleIndexBuffer.data) { var handle = this.m_handleIndexBuffer.data[i]; if (handle) { handle.SetIndex(b2_invalidParticleIndex); this.m_handleIndexBuffer.data[i] = null; } } newIndices[i] = b2_invalidParticleIndex; } else { newIndices[i] = newCount; if (i !== newCount) { if (this.m_handleIndexBuffer.data) { var handle = this.m_handleIndexBuffer.data[i]; handle && handle.SetIndex(newCount); this.m_handleIndexBuffer.data[newCount] = handle; } this.m_flagsBuffer.data[newCount] = this.m_flagsBuffer.data[i]; this.m_lastBodyContactStepBuffer.data && (this.m_lastBodyContactStepBuffer.data[newCount] = this.m_lastBodyContactStepBuffer.data[i]); this.m_bodyContactCountBuffer.data && (this.m_bodyContactCountBuffer.data[newCount] = this.m_bodyContactCountBuffer.data[i]); this.m_consecutiveContactStepsBuffer.data && (this.m_consecutiveContactStepsBuffer.data[newCount] = this.m_consecutiveContactStepsBuffer.data[i]); this.m_positionBuffer.data[newCount].Copy(this.m_positionBuffer.data[i]); this.m_velocityBuffer.data[newCount].Copy(this.m_velocityBuffer.data[i]); this.m_groupBuffer[newCount] = this.m_groupBuffer[i]; this.m_hasForce && this.m_forceBuffer[newCount].Copy(this.m_forceBuffer[i]); this.m_staticPressureBuffer && (this.m_staticPressureBuffer[newCount] = this.m_staticPressureBuffer[i]); this.m_depthBuffer && (this.m_depthBuffer[newCount] = this.m_depthBuffer[i]); this.m_colorBuffer.data && this.m_colorBuffer.data[newCount].Copy(this.m_colorBuffer.data[i]); this.m_userDataBuffer.data && (this.m_userDataBuffer.data[newCount] = this.m_userDataBuffer.data[i]); this.m_expirationTimeBuffer.data && (this.m_expirationTimeBuffer.data[newCount] = this.m_expirationTimeBuffer.data[i]); } newCount++; allParticleFlags |= flags; } } var Test = { IsProxyInvalid: function(proxy) { return proxy.index < 0; }, IsContactInvalid: function(contact) { return contact.indexA < 0 || contact.indexB < 0; }, IsBodyContactInvalid: function(contact) { return contact.index < 0; }, IsPairInvalid: function(pair) { return pair.indexA < 0 || pair.indexB < 0; }, IsTriadInvalid: function(triad) { return triad.indexA < 0 || triad.indexB < 0 || triad.indexC < 0; } }; for (var k = 0; k < this.m_proxyBuffer.count; k++) { var proxy = this.m_proxyBuffer.data[k]; proxy.index = newIndices[proxy.index]; } this.m_proxyBuffer.RemoveIf(Test.IsProxyInvalid); for (var k = 0; k < this.m_contactBuffer.count; k++) { var contact = this.m_contactBuffer.data[k]; contact.indexA = newIndices[contact.indexA]; contact.indexB = newIndices[contact.indexB]; } this.m_contactBuffer.RemoveIf(Test.IsContactInvalid); for (var k = 0; k < this.m_bodyContactBuffer.count; k++) { var contact = this.m_bodyContactBuffer.data[k]; contact.index = newIndices[contact.index]; } this.m_bodyContactBuffer.RemoveIf(Test.IsBodyContactInvalid); for (var k = 0; k < this.m_pairBuffer.count; k++) { var pair = this.m_pairBuffer.data[k]; pair.indexA = newIndices[pair.indexA]; pair.indexB = newIndices[pair.indexB]; } this.m_pairBuffer.RemoveIf(Test.IsPairInvalid); for (var k = 0; k < this.m_triadBuffer.count; k++) { var triad = this.m_triadBuffer.data[k]; triad.indexA = newIndices[triad.indexA]; triad.indexB = newIndices[triad.indexB]; triad.indexC = newIndices[triad.indexC]; } this.m_triadBuffer.RemoveIf(Test.IsTriadInvalid); if (this.m_indexByExpirationTimeBuffer.data) { var writeOffset = 0; for (var readOffset = 0; readOffset < this.m_count; readOffset++) { var newIndex = newIndices[this.m_indexByExpirationTimeBuffer.data[readOffset]]; newIndex !== b2_invalidParticleIndex && (this.m_indexByExpirationTimeBuffer.data[writeOffset++] = newIndex); } } for (var group = this.m_groupList; group; group = group.GetNext()) { var firstIndex = newCount; var lastIndex = 0; var modified = false; for (var i = group.m_firstIndex; i < group.m_lastIndex; i++) { var j = newIndices[i]; if (j >= 0) { firstIndex = b2Min(firstIndex, j); lastIndex = b2Max(lastIndex, j + 1); } else modified = true; } if (firstIndex < lastIndex) { group.m_firstIndex = firstIndex; group.m_lastIndex = lastIndex; modified && group.m_groupFlags & exports.b2ParticleGroupFlag.b2_solidParticleGroup && this.SetGroupFlags(group, group.m_groupFlags | exports.b2ParticleGroupFlag.b2_particleGroupNeedsUpdateDepth); } else { group.m_firstIndex = 0; group.m_lastIndex = 0; group.m_groupFlags & exports.b2ParticleGroupFlag.b2_particleGroupCanBeEmpty || this.SetGroupFlags(group, group.m_groupFlags | exports.b2ParticleGroupFlag.b2_particleGroupWillBeDestroyed); } } this.m_count = newCount; this.m_allParticleFlags = allParticleFlags; this.m_needsUpdateAllParticleFlags = false; for (var group = this.m_groupList; group; ) { var next = group.GetNext(); group.m_groupFlags & exports.b2ParticleGroupFlag.b2_particleGroupWillBeDestroyed && this.DestroyParticleGroup(group); group = next; } }; b2ParticleSystem.prototype.SolveLifetimes = function(step) { if (!this.m_expirationTimeBuffer.data) throw new Error(); if (!this.m_indexByExpirationTimeBuffer.data) throw new Error(); this.m_timeElapsed = this.LifetimeToExpirationTime(step.dt); var quantizedTimeElapsed = this.GetQuantizedTimeElapsed(); var expirationTimes = this.m_expirationTimeBuffer.data; var expirationTimeIndices = this.m_indexByExpirationTimeBuffer.data; var particleCount = this.GetParticleCount(); if (this.m_expirationTimeBufferRequiresSorting) { var ExpirationTimeComparator = function(particleIndexA, particleIndexB) { var expirationTimeA = expirationTimes[particleIndexA]; var expirationTimeB = expirationTimes[particleIndexB]; var infiniteExpirationTimeA = expirationTimeA <= 0; var infiniteExpirationTimeB = expirationTimeB <= 0; return infiniteExpirationTimeA === infiniteExpirationTimeB ? expirationTimeA > expirationTimeB : infiniteExpirationTimeA; }; std_sort(expirationTimeIndices, 0, particleCount, ExpirationTimeComparator); this.m_expirationTimeBufferRequiresSorting = false; } for (var i = particleCount - 1; i >= 0; --i) { var particleIndex = expirationTimeIndices[i]; var expirationTime = expirationTimes[particleIndex]; if (quantizedTimeElapsed < expirationTime || expirationTime <= 0) break; this.DestroyParticle(particleIndex); } }; b2ParticleSystem.prototype.RotateBuffer = function(start, mid, end) { if (start === mid || mid === end) return; function newIndices(i) { return i < start ? i : i < mid ? i + end - mid : i < end ? i + start - mid : i; } if (!this.m_flagsBuffer.data) throw new Error(); if (!this.m_positionBuffer.data) throw new Error(); if (!this.m_velocityBuffer.data) throw new Error(); std_rotate(this.m_flagsBuffer.data, start, mid, end); this.m_lastBodyContactStepBuffer.data && std_rotate(this.m_lastBodyContactStepBuffer.data, start, mid, end); this.m_bodyContactCountBuffer.data && std_rotate(this.m_bodyContactCountBuffer.data, start, mid, end); this.m_consecutiveContactStepsBuffer.data && std_rotate(this.m_consecutiveContactStepsBuffer.data, start, mid, end); std_rotate(this.m_positionBuffer.data, start, mid, end); std_rotate(this.m_velocityBuffer.data, start, mid, end); std_rotate(this.m_groupBuffer, start, mid, end); this.m_hasForce && std_rotate(this.m_forceBuffer, start, mid, end); this.m_staticPressureBuffer && std_rotate(this.m_staticPressureBuffer, start, mid, end); this.m_depthBuffer && std_rotate(this.m_depthBuffer, start, mid, end); this.m_colorBuffer.data && std_rotate(this.m_colorBuffer.data, start, mid, end); this.m_userDataBuffer.data && std_rotate(this.m_userDataBuffer.data, start, mid, end); if (this.m_handleIndexBuffer.data) { std_rotate(this.m_handleIndexBuffer.data, start, mid, end); for (var i = start; i < end; ++i) { var handle = this.m_handleIndexBuffer.data[i]; handle && handle.SetIndex(newIndices(handle.GetIndex())); } } if (this.m_expirationTimeBuffer.data) { std_rotate(this.m_expirationTimeBuffer.data, start, mid, end); var particleCount = this.GetParticleCount(); if (!this.m_indexByExpirationTimeBuffer.data) throw new Error(); var indexByExpirationTime = this.m_indexByExpirationTimeBuffer.data; for (var i = 0; i < particleCount; ++i) indexByExpirationTime[i] = newIndices(indexByExpirationTime[i]); } for (var k = 0; k < this.m_proxyBuffer.count; k++) { var proxy = this.m_proxyBuffer.data[k]; proxy.index = newIndices(proxy.index); } for (var k = 0; k < this.m_contactBuffer.count; k++) { var contact = this.m_contactBuffer.data[k]; contact.indexA = newIndices(contact.indexA); contact.indexB = newIndices(contact.indexB); } for (var k = 0; k < this.m_bodyContactBuffer.count; k++) { var contact = this.m_bodyContactBuffer.data[k]; contact.index = newIndices(contact.index); } for (var k = 0; k < this.m_pairBuffer.count; k++) { var pair = this.m_pairBuffer.data[k]; pair.indexA = newIndices(pair.indexA); pair.indexB = newIndices(pair.indexB); } for (var k = 0; k < this.m_triadBuffer.count; k++) { var triad = this.m_triadBuffer.data[k]; triad.indexA = newIndices(triad.indexA); triad.indexB = newIndices(triad.indexB); triad.indexC = newIndices(triad.indexC); } for (var group = this.m_groupList; group; group = group.GetNext()) { group.m_firstIndex = newIndices(group.m_firstIndex); group.m_lastIndex = newIndices(group.m_lastIndex - 1) + 1; } }; b2ParticleSystem.prototype.GetCriticalVelocity = function(step) { return this.m_particleDiameter * step.inv_dt; }; b2ParticleSystem.prototype.GetCriticalVelocitySquared = function(step) { var velocity = this.GetCriticalVelocity(step); return velocity * velocity; }; b2ParticleSystem.prototype.GetCriticalPressure = function(step) { return this.m_def.density * this.GetCriticalVelocitySquared(step); }; b2ParticleSystem.prototype.GetParticleStride = function() { return b2_particleStride * this.m_particleDiameter; }; b2ParticleSystem.prototype.GetParticleMass = function() { var stride = this.GetParticleStride(); return this.m_def.density * stride * stride; }; b2ParticleSystem.prototype.GetParticleInvMass = function() { var inverseStride = this.m_inverseDiameter * (1 / b2_particleStride); return this.m_inverseDensity * inverseStride * inverseStride; }; b2ParticleSystem.prototype.GetFixtureContactFilter = function() { return this.m_allParticleFlags & exports.b2ParticleFlag.b2_fixtureContactFilterParticle ? this.m_world.m_contactManager.m_contactFilter : null; }; b2ParticleSystem.prototype.GetParticleContactFilter = function() { return this.m_allParticleFlags & exports.b2ParticleFlag.b2_particleContactFilterParticle ? this.m_world.m_contactManager.m_contactFilter : null; }; b2ParticleSystem.prototype.GetFixtureContactListener = function() { return this.m_allParticleFlags & exports.b2ParticleFlag.b2_fixtureContactListenerParticle ? this.m_world.m_contactManager.m_contactListener : null; }; b2ParticleSystem.prototype.GetParticleContactListener = function() { return this.m_allParticleFlags & exports.b2ParticleFlag.b2_particleContactListenerParticle ? this.m_world.m_contactManager.m_contactListener : null; }; b2ParticleSystem.prototype.SetUserOverridableBuffer = function(buffer, newData, newCapacity) { buffer.data = newData; buffer.userSuppliedCapacity = newCapacity; }; b2ParticleSystem.prototype.SetGroupFlags = function(group, newFlags) { var oldFlags = group.m_groupFlags; (oldFlags ^ newFlags) & exports.b2ParticleGroupFlag.b2_solidParticleGroup && (newFlags |= exports.b2ParticleGroupFlag.b2_particleGroupNeedsUpdateDepth); oldFlags & ~newFlags && (this.m_needsUpdateAllGroupFlags = true); if (~this.m_allGroupFlags & newFlags) { newFlags & exports.b2ParticleGroupFlag.b2_solidParticleGroup && (this.m_depthBuffer = this.RequestBuffer(this.m_depthBuffer)); this.m_allGroupFlags |= newFlags; } group.m_groupFlags = newFlags; }; b2ParticleSystem.BodyContactCompare = function(lhs, rhs) { if (lhs.index === rhs.index) return lhs.weight > rhs.weight; return lhs.index < rhs.index; }; b2ParticleSystem.prototype.RemoveSpuriousBodyContacts = function() { std_sort(this.m_bodyContactBuffer.data, 0, this.m_bodyContactBuffer.count, b2ParticleSystem.BodyContactCompare); var s_n = b2ParticleSystem.RemoveSpuriousBodyContacts_s_n; var s_pos = b2ParticleSystem.RemoveSpuriousBodyContacts_s_pos; var s_normal = b2ParticleSystem.RemoveSpuriousBodyContacts_s_normal; var k_maxContactsPerPoint = 3; var system = this; var lastIndex = -1; var currentContacts = 0; var b2ParticleBodyContactRemovePredicate = function(contact) { if (contact.index !== lastIndex) { currentContacts = 0; lastIndex = contact.index; } if (currentContacts++ > k_maxContactsPerPoint) return true; var n = s_n.Copy(contact.normal); n.SelfMul(system.m_particleDiameter * (1 - contact.weight)); if (!system.m_positionBuffer.data) throw new Error(); var pos = b2Vec2.AddVV(system.m_positionBuffer.data[contact.index], n, s_pos); if (!contact.fixture.TestPoint(pos)) { var childCount = contact.fixture.GetShape().GetChildCount(); for (var childIndex = 0; childIndex < childCount; childIndex++) { var normal = s_normal; var distance = contact.fixture.ComputeDistance(pos, normal, childIndex); if (distance < b2_linearSlop) return false; } return true; } return false; }; this.m_bodyContactBuffer.count = std_remove_if(this.m_bodyContactBuffer.data, b2ParticleBodyContactRemovePredicate, this.m_bodyContactBuffer.count); }; b2ParticleSystem.prototype.DetectStuckParticle = function(particle) { if (this.m_stuckThreshold <= 0) return; if (!this.m_bodyContactCountBuffer.data) throw new Error(); if (!this.m_consecutiveContactStepsBuffer.data) throw new Error(); if (!this.m_lastBodyContactStepBuffer.data) throw new Error(); ++this.m_bodyContactCountBuffer.data[particle]; if (2 === this.m_bodyContactCountBuffer.data[particle]) { ++this.m_consecutiveContactStepsBuffer.data[particle]; this.m_consecutiveContactStepsBuffer.data[particle] > this.m_stuckThreshold && (this.m_stuckParticleBuffer.data[this.m_stuckParticleBuffer.Append()] = particle); } this.m_lastBodyContactStepBuffer.data[particle] = this.m_timestamp; }; b2ParticleSystem.prototype.ValidateParticleIndex = function(index) { return index >= 0 && index < this.GetParticleCount() && index !== b2_invalidParticleIndex; }; b2ParticleSystem.prototype.GetQuantizedTimeElapsed = function() { return Math.floor(this.m_timeElapsed / 4294967296); }; b2ParticleSystem.prototype.LifetimeToExpirationTime = function(lifetime) { return this.m_timeElapsed + Math.floor(lifetime / this.m_def.lifetimeGranularity * 4294967296); }; b2ParticleSystem.prototype.ForceCanBeApplied = function(flags) { return !(flags & exports.b2ParticleFlag.b2_wallParticle); }; b2ParticleSystem.prototype.PrepareForceBuffer = function() { if (!this.m_hasForce) { for (var i = 0; i < this.m_count; i++) this.m_forceBuffer[i].SetZero(); this.m_hasForce = true; } }; b2ParticleSystem.prototype.IsRigidGroup = function(group) { return null !== group && 0 !== (group.m_groupFlags & exports.b2ParticleGroupFlag.b2_rigidParticleGroup); }; b2ParticleSystem.prototype.GetLinearVelocity = function(group, particleIndex, point, out) { if (group && this.IsRigidGroup(group)) return group.GetLinearVelocityFromWorldPoint(point, out); if (!this.m_velocityBuffer.data) throw new Error(); return out.Copy(this.m_velocityBuffer.data[particleIndex]); }; b2ParticleSystem.prototype.InitDampingParameter = function(invMass, invInertia, tangentDistance, mass, inertia, center, point, normal) { invMass[0] = mass > 0 ? 1 / mass : 0; invInertia[0] = inertia > 0 ? 1 / inertia : 0; tangentDistance[0] = b2Vec2.CrossVV(b2Vec2.SubVV(point, center, b2Vec2.s_t0), normal); }; b2ParticleSystem.prototype.InitDampingParameterWithRigidGroupOrParticle = function(invMass, invInertia, tangentDistance, isRigidGroup, group, particleIndex, point, normal) { if (group && isRigidGroup) this.InitDampingParameter(invMass, invInertia, tangentDistance, group.GetMass(), group.GetInertia(), group.GetCenter(), point, normal); else { if (!this.m_flagsBuffer.data) throw new Error(); var flags = this.m_flagsBuffer.data[particleIndex]; this.InitDampingParameter(invMass, invInertia, tangentDistance, flags & exports.b2ParticleFlag.b2_wallParticle ? 0 : this.GetParticleMass(), 0, point, point, normal); } }; b2ParticleSystem.prototype.ComputeDampingImpulse = function(invMassA, invInertiaA, tangentDistanceA, invMassB, invInertiaB, tangentDistanceB, normalVelocity) { var invMass = invMassA + invInertiaA * tangentDistanceA * tangentDistanceA + invMassB + invInertiaB * tangentDistanceB * tangentDistanceB; return invMass > 0 ? normalVelocity / invMass : 0; }; b2ParticleSystem.prototype.ApplyDamping = function(invMass, invInertia, tangentDistance, isRigidGroup, group, particleIndex, impulse, normal) { if (group && isRigidGroup) { group.m_linearVelocity.SelfMulAdd(impulse * invMass, normal); group.m_angularVelocity += impulse * tangentDistance * invInertia; } else { if (!this.m_velocityBuffer.data) throw new Error(); this.m_velocityBuffer.data[particleIndex].SelfMulAdd(impulse * invMass, normal); } }; b2ParticleSystem.xTruncBits = 12; b2ParticleSystem.yTruncBits = 12; b2ParticleSystem.tagBits = 32; b2ParticleSystem.yOffset = 1 << b2ParticleSystem.yTruncBits - 1; b2ParticleSystem.yShift = b2ParticleSystem.tagBits - b2ParticleSystem.yTruncBits; b2ParticleSystem.xShift = b2ParticleSystem.tagBits - b2ParticleSystem.yTruncBits - b2ParticleSystem.xTruncBits; b2ParticleSystem.xScale = 1 << b2ParticleSystem.xShift; b2ParticleSystem.xOffset = b2ParticleSystem.xScale * (1 << b2ParticleSystem.xTruncBits - 1); b2ParticleSystem.yMask = (1 << b2ParticleSystem.yTruncBits) - 1 << b2ParticleSystem.yShift; b2ParticleSystem.xMask = ~b2ParticleSystem.yMask; b2ParticleSystem.DestroyParticlesInShape_s_aabb = new b2AABB(); b2ParticleSystem.CreateParticleGroup_s_transform = new b2Transform(); b2ParticleSystem.ComputeCollisionEnergy_s_v = new b2Vec2(); b2ParticleSystem.QueryShapeAABB_s_aabb = new b2AABB(); b2ParticleSystem.QueryPointAABB_s_aabb = new b2AABB(); b2ParticleSystem.RayCast_s_aabb = new b2AABB(); b2ParticleSystem.RayCast_s_p = new b2Vec2(); b2ParticleSystem.RayCast_s_v = new b2Vec2(); b2ParticleSystem.RayCast_s_n = new b2Vec2(); b2ParticleSystem.RayCast_s_point = new b2Vec2(); b2ParticleSystem.k_pairFlags = exports.b2ParticleFlag.b2_springParticle; b2ParticleSystem.k_triadFlags = exports.b2ParticleFlag.b2_elasticParticle; b2ParticleSystem.k_noPressureFlags = exports.b2ParticleFlag.b2_powderParticle | exports.b2ParticleFlag.b2_tensileParticle; b2ParticleSystem.k_extraDampingFlags = exports.b2ParticleFlag.b2_staticPressureParticle; b2ParticleSystem.k_barrierWallFlags = exports.b2ParticleFlag.b2_barrierParticle | exports.b2ParticleFlag.b2_wallParticle; b2ParticleSystem.CreateParticlesStrokeShapeForGroup_s_edge = new b2EdgeShape(); b2ParticleSystem.CreateParticlesStrokeShapeForGroup_s_d = new b2Vec2(); b2ParticleSystem.CreateParticlesStrokeShapeForGroup_s_p = new b2Vec2(); b2ParticleSystem.CreateParticlesFillShapeForGroup_s_aabb = new b2AABB(); b2ParticleSystem.CreateParticlesFillShapeForGroup_s_p = new b2Vec2(); b2ParticleSystem.UpdatePairsAndTriads_s_dab = new b2Vec2(); b2ParticleSystem.UpdatePairsAndTriads_s_dbc = new b2Vec2(); b2ParticleSystem.UpdatePairsAndTriads_s_dca = new b2Vec2(); b2ParticleSystem.AddContact_s_d = new b2Vec2(); b2ParticleSystem.UpdateBodyContacts_s_aabb = new b2AABB(); b2ParticleSystem.Solve_s_subStep = new b2TimeStep(); b2ParticleSystem.SolveCollision_s_aabb = new b2AABB(); b2ParticleSystem.SolveGravity_s_gravity = new b2Vec2(); b2ParticleSystem.SolveBarrier_s_aabb = new b2AABB(); b2ParticleSystem.SolveBarrier_s_va = new b2Vec2(); b2ParticleSystem.SolveBarrier_s_vb = new b2Vec2(); b2ParticleSystem.SolveBarrier_s_pba = new b2Vec2(); b2ParticleSystem.SolveBarrier_s_vba = new b2Vec2(); b2ParticleSystem.SolveBarrier_s_vc = new b2Vec2(); b2ParticleSystem.SolveBarrier_s_pca = new b2Vec2(); b2ParticleSystem.SolveBarrier_s_vca = new b2Vec2(); b2ParticleSystem.SolveBarrier_s_qba = new b2Vec2(); b2ParticleSystem.SolveBarrier_s_qca = new b2Vec2(); b2ParticleSystem.SolveBarrier_s_dv = new b2Vec2(); b2ParticleSystem.SolveBarrier_s_f = new b2Vec2(); b2ParticleSystem.SolvePressure_s_f = new b2Vec2(); b2ParticleSystem.SolveDamping_s_v = new b2Vec2(); b2ParticleSystem.SolveDamping_s_f = new b2Vec2(); b2ParticleSystem.SolveRigidDamping_s_t0 = new b2Vec2(); b2ParticleSystem.SolveRigidDamping_s_t1 = new b2Vec2(); b2ParticleSystem.SolveRigidDamping_s_p = new b2Vec2(); b2ParticleSystem.SolveRigidDamping_s_v = new b2Vec2(); b2ParticleSystem.SolveExtraDamping_s_v = new b2Vec2(); b2ParticleSystem.SolveExtraDamping_s_f = new b2Vec2(); b2ParticleSystem.SolveRigid_s_position = new b2Vec2(); b2ParticleSystem.SolveRigid_s_rotation = new b2Rot(); b2ParticleSystem.SolveRigid_s_transform = new b2Transform(); b2ParticleSystem.SolveRigid_s_velocityTransform = new b2Transform(); b2ParticleSystem.SolveElastic_s_pa = new b2Vec2(); b2ParticleSystem.SolveElastic_s_pb = new b2Vec2(); b2ParticleSystem.SolveElastic_s_pc = new b2Vec2(); b2ParticleSystem.SolveElastic_s_r = new b2Rot(); b2ParticleSystem.SolveElastic_s_t0 = new b2Vec2(); b2ParticleSystem.SolveSpring_s_pa = new b2Vec2(); b2ParticleSystem.SolveSpring_s_pb = new b2Vec2(); b2ParticleSystem.SolveSpring_s_d = new b2Vec2(); b2ParticleSystem.SolveSpring_s_f = new b2Vec2(); b2ParticleSystem.SolveTensile_s_weightedNormal = new b2Vec2(); b2ParticleSystem.SolveTensile_s_s = new b2Vec2(); b2ParticleSystem.SolveTensile_s_f = new b2Vec2(); b2ParticleSystem.SolveViscous_s_v = new b2Vec2(); b2ParticleSystem.SolveViscous_s_f = new b2Vec2(); b2ParticleSystem.SolveRepulsive_s_f = new b2Vec2(); b2ParticleSystem.SolvePowder_s_f = new b2Vec2(); b2ParticleSystem.SolveSolid_s_f = new b2Vec2(); b2ParticleSystem.RemoveSpuriousBodyContacts_s_n = new b2Vec2(); b2ParticleSystem.RemoveSpuriousBodyContacts_s_pos = new b2Vec2(); b2ParticleSystem.RemoveSpuriousBodyContacts_s_normal = new b2Vec2(); return b2ParticleSystem; })(); (function(b2ParticleSystem) { var UserOverridableBuffer = (function() { function UserOverridableBuffer() { this.data = null; this.userSuppliedCapacity = 0; } return UserOverridableBuffer; })(); b2ParticleSystem.UserOverridableBuffer = UserOverridableBuffer; var Proxy = (function() { function Proxy() { this.index = b2_invalidParticleIndex; this.tag = 0; } Proxy.CompareProxyProxy = function(a, b) { return a.tag < b.tag; }; Proxy.CompareTagProxy = function(a, b) { return a < b.tag; }; Proxy.CompareProxyTag = function(a, b) { return a.tag < b; }; return Proxy; })(); b2ParticleSystem.Proxy = Proxy; var InsideBoundsEnumerator = (function() { function InsideBoundsEnumerator(system, lower, upper, first, last) { this.m_system = system; this.m_xLower = (lower & b2ParticleSystem.xMask) >>> 0; this.m_xUpper = (upper & b2ParticleSystem.xMask) >>> 0; this.m_yLower = (lower & b2ParticleSystem.yMask) >>> 0; this.m_yUpper = (upper & b2ParticleSystem.yMask) >>> 0; this.m_first = first; this.m_last = last; } InsideBoundsEnumerator.prototype.GetNext = function() { while (this.m_first < this.m_last) { var xTag = (this.m_system.m_proxyBuffer.data[this.m_first].tag & b2ParticleSystem.xMask) >>> 0; if (xTag >= this.m_xLower && xTag <= this.m_xUpper) return this.m_system.m_proxyBuffer.data[this.m_first++].index; this.m_first++; } return b2_invalidParticleIndex; }; return InsideBoundsEnumerator; })(); b2ParticleSystem.InsideBoundsEnumerator = InsideBoundsEnumerator; var ParticleListNode = (function() { function ParticleListNode() { this.next = null; this.count = 0; this.index = 0; } return ParticleListNode; })(); b2ParticleSystem.ParticleListNode = ParticleListNode; var FixedSetAllocator = (function() { function FixedSetAllocator() {} FixedSetAllocator.prototype.Allocate = function(itemSize, count) { return count; }; FixedSetAllocator.prototype.Clear = function() {}; FixedSetAllocator.prototype.GetCount = function() { return 0; }; FixedSetAllocator.prototype.Invalidate = function(itemIndex) {}; FixedSetAllocator.prototype.GetValidBuffer = function() { return []; }; FixedSetAllocator.prototype.GetBuffer = function() { return []; }; FixedSetAllocator.prototype.SetCount = function(count) {}; return FixedSetAllocator; })(); b2ParticleSystem.FixedSetAllocator = FixedSetAllocator; var FixtureParticle = (function() { function FixtureParticle(fixture, particle) { this.second = b2_invalidParticleIndex; this.first = fixture; this.second = particle; } return FixtureParticle; })(); b2ParticleSystem.FixtureParticle = FixtureParticle; var FixtureParticleSet = (function(_super) { __extends(FixtureParticleSet, _super); function FixtureParticleSet() { return null !== _super && _super.apply(this, arguments) || this; } FixtureParticleSet.prototype.Initialize = function(bodyContactBuffer, flagsBuffer) {}; FixtureParticleSet.prototype.Find = function(pair) { return b2_invalidParticleIndex; }; return FixtureParticleSet; })(b2ParticleSystem.FixedSetAllocator); b2ParticleSystem.FixtureParticleSet = FixtureParticleSet; var ParticlePair = (function() { function ParticlePair(particleA, particleB) { this.first = b2_invalidParticleIndex; this.second = b2_invalidParticleIndex; this.first = particleA; this.second = particleB; } return ParticlePair; })(); b2ParticleSystem.ParticlePair = ParticlePair; var b2ParticlePairSet = (function(_super) { __extends(b2ParticlePairSet, _super); function b2ParticlePairSet() { return null !== _super && _super.apply(this, arguments) || this; } b2ParticlePairSet.prototype.Initialize = function(contactBuffer, flagsBuffer) {}; b2ParticlePairSet.prototype.Find = function(pair) { return b2_invalidParticleIndex; }; return b2ParticlePairSet; })(b2ParticleSystem.FixedSetAllocator); b2ParticleSystem.b2ParticlePairSet = b2ParticlePairSet; var ConnectionFilter = (function() { function ConnectionFilter() {} ConnectionFilter.prototype.IsNecessary = function(index) { return true; }; ConnectionFilter.prototype.ShouldCreatePair = function(a, b) { return true; }; ConnectionFilter.prototype.ShouldCreateTriad = function(a, b, c) { return true; }; return ConnectionFilter; })(); b2ParticleSystem.ConnectionFilter = ConnectionFilter; var DestroyParticlesInShapeCallback = (function(_super) { __extends(DestroyParticlesInShapeCallback, _super); function DestroyParticlesInShapeCallback(system, shape, xf, callDestructionListener) { var _this = _super.call(this) || this; _this.m_callDestructionListener = false; _this.m_destroyed = 0; _this.m_system = system; _this.m_shape = shape; _this.m_xf = xf; _this.m_callDestructionListener = callDestructionListener; _this.m_destroyed = 0; return _this; } DestroyParticlesInShapeCallback.prototype.ReportFixture = function(fixture) { return false; }; DestroyParticlesInShapeCallback.prototype.ReportParticle = function(particleSystem, index) { if (particleSystem !== this.m_system) return false; if (!this.m_system.m_positionBuffer.data) throw new Error(); if (this.m_shape.TestPoint(this.m_xf, this.m_system.m_positionBuffer.data[index])) { this.m_system.DestroyParticle(index, this.m_callDestructionListener); this.m_destroyed++; } return true; }; DestroyParticlesInShapeCallback.prototype.Destroyed = function() { return this.m_destroyed; }; return DestroyParticlesInShapeCallback; })(b2QueryCallback); b2ParticleSystem.DestroyParticlesInShapeCallback = DestroyParticlesInShapeCallback; var JoinParticleGroupsFilter = (function(_super) { __extends(JoinParticleGroupsFilter, _super); function JoinParticleGroupsFilter(threshold) { var _this = _super.call(this) || this; _this.m_threshold = 0; _this.m_threshold = threshold; return _this; } JoinParticleGroupsFilter.prototype.ShouldCreatePair = function(a, b) { return a < this.m_threshold && this.m_threshold <= b || b < this.m_threshold && this.m_threshold <= a; }; JoinParticleGroupsFilter.prototype.ShouldCreateTriad = function(a, b, c) { return (a < this.m_threshold || b < this.m_threshold || c < this.m_threshold) && (this.m_threshold <= a || this.m_threshold <= b || this.m_threshold <= c); }; return JoinParticleGroupsFilter; })(b2ParticleSystem.ConnectionFilter); b2ParticleSystem.JoinParticleGroupsFilter = JoinParticleGroupsFilter; var CompositeShape = (function(_super) { __extends(CompositeShape, _super); function CompositeShape(shapes, shapeCount) { void 0 === shapeCount && (shapeCount = shapes.length); var _this = _super.call(this, exports.b2ShapeType.e_unknown, 0) || this; _this.m_shapeCount = 0; _this.m_shapes = shapes; _this.m_shapeCount = shapeCount; return _this; } CompositeShape.prototype.Clone = function() { throw new Error(); }; CompositeShape.prototype.GetChildCount = function() { return 1; }; CompositeShape.prototype.TestPoint = function(xf, p) { for (var i = 0; i < this.m_shapeCount; i++) if (this.m_shapes[i].TestPoint(xf, p)) return true; return false; }; CompositeShape.prototype.ComputeDistance = function(xf, p, normal, childIndex) { return 0; }; CompositeShape.prototype.RayCast = function(output, input, xf, childIndex) { return false; }; CompositeShape.prototype.ComputeAABB = function(aabb, xf, childIndex) { var s_subaabb = new b2AABB(); aabb.lowerBound.x = +b2_maxFloat; aabb.lowerBound.y = +b2_maxFloat; aabb.upperBound.x = -b2_maxFloat; aabb.upperBound.y = -b2_maxFloat; for (var i = 0; i < this.m_shapeCount; i++) { var childCount = this.m_shapes[i].GetChildCount(); for (var j = 0; j < childCount; j++) { var subaabb = s_subaabb; this.m_shapes[i].ComputeAABB(subaabb, xf, j); aabb.Combine1(subaabb); } } }; CompositeShape.prototype.ComputeMass = function(massData, density) {}; CompositeShape.prototype.SetupDistanceProxy = function(proxy, index) {}; CompositeShape.prototype.ComputeSubmergedArea = function(normal, offset, xf, c) { return 0; }; CompositeShape.prototype.Dump = function(log) {}; return CompositeShape; })(b2Shape); b2ParticleSystem.CompositeShape = CompositeShape; var ReactiveFilter = (function(_super) { __extends(ReactiveFilter, _super); function ReactiveFilter(flagsBuffer) { var _this = _super.call(this) || this; _this.m_flagsBuffer = flagsBuffer; return _this; } ReactiveFilter.prototype.IsNecessary = function(index) { if (!this.m_flagsBuffer.data) throw new Error(); return 0 !== (this.m_flagsBuffer.data[index] & exports.b2ParticleFlag.b2_reactiveParticle); }; return ReactiveFilter; })(b2ParticleSystem.ConnectionFilter); b2ParticleSystem.ReactiveFilter = ReactiveFilter; var UpdateBodyContactsCallback = (function(_super) { __extends(UpdateBodyContactsCallback, _super); function UpdateBodyContactsCallback(system, contactFilter) { var _this = _super.call(this, system) || this; _this.m_contactFilter = contactFilter; return _this; } UpdateBodyContactsCallback.prototype.ShouldCollideFixtureParticle = function(fixture, particleSystem, particleIndex) { if (this.m_contactFilter) { var flags = this.m_system.GetFlagsBuffer(); if (flags[particleIndex] & exports.b2ParticleFlag.b2_fixtureContactFilterParticle) return this.m_contactFilter.ShouldCollideFixtureParticle(fixture, this.m_system, particleIndex); } return true; }; UpdateBodyContactsCallback.prototype.ReportFixtureAndParticle = function(fixture, childIndex, a) { var s_n = b2ParticleSystem.UpdateBodyContactsCallback.ReportFixtureAndParticle_s_n; var s_rp = b2ParticleSystem.UpdateBodyContactsCallback.ReportFixtureAndParticle_s_rp; if (!this.m_system.m_flagsBuffer.data) throw new Error(); if (!this.m_system.m_positionBuffer.data) throw new Error(); var ap = this.m_system.m_positionBuffer.data[a]; var n = s_n; var d = fixture.ComputeDistance(ap, n, childIndex); if (d < this.m_system.m_particleDiameter && this.ShouldCollideFixtureParticle(fixture, this.m_system, a)) { var b = fixture.GetBody(); var bp = b.GetWorldCenter(); var bm = b.GetMass(); var bI = b.GetInertia() - bm * b.GetLocalCenter().LengthSquared(); var invBm = bm > 0 ? 1 / bm : 0; var invBI = bI > 0 ? 1 / bI : 0; var invAm = this.m_system.m_flagsBuffer.data[a] & exports.b2ParticleFlag.b2_wallParticle ? 0 : this.m_system.GetParticleInvMass(); var rp = b2Vec2.SubVV(ap, bp, s_rp); var rpn = b2Vec2.CrossVV(rp, n); var invM = invAm + invBm + invBI * rpn * rpn; var contact = this.m_system.m_bodyContactBuffer.data[this.m_system.m_bodyContactBuffer.Append()]; contact.index = a; contact.body = b; contact.fixture = fixture; contact.weight = 1 - d * this.m_system.m_inverseDiameter; contact.normal.Copy(n.SelfNeg()); contact.mass = invM > 0 ? 1 / invM : 0; this.m_system.DetectStuckParticle(a); } }; UpdateBodyContactsCallback.ReportFixtureAndParticle_s_n = new b2Vec2(); UpdateBodyContactsCallback.ReportFixtureAndParticle_s_rp = new b2Vec2(); return UpdateBodyContactsCallback; })(b2FixtureParticleQueryCallback); b2ParticleSystem.UpdateBodyContactsCallback = UpdateBodyContactsCallback; var SolveCollisionCallback = (function(_super) { __extends(SolveCollisionCallback, _super); function SolveCollisionCallback(system, step) { var _this = _super.call(this, system) || this; _this.m_step = step; return _this; } SolveCollisionCallback.prototype.ReportFixtureAndParticle = function(fixture, childIndex, a) { var s_p1 = b2ParticleSystem.SolveCollisionCallback.ReportFixtureAndParticle_s_p1; var s_output = b2ParticleSystem.SolveCollisionCallback.ReportFixtureAndParticle_s_output; var s_input = b2ParticleSystem.SolveCollisionCallback.ReportFixtureAndParticle_s_input; var s_p = b2ParticleSystem.SolveCollisionCallback.ReportFixtureAndParticle_s_p; var s_v = b2ParticleSystem.SolveCollisionCallback.ReportFixtureAndParticle_s_v; var s_f = b2ParticleSystem.SolveCollisionCallback.ReportFixtureAndParticle_s_f; var body = fixture.GetBody(); if (!this.m_system.m_positionBuffer.data) throw new Error(); if (!this.m_system.m_velocityBuffer.data) throw new Error(); var ap = this.m_system.m_positionBuffer.data[a]; var av = this.m_system.m_velocityBuffer.data[a]; var output = s_output; var input = s_input; if (0 === this.m_system.m_iterationIndex) { var p1 = b2Transform.MulTXV(body.m_xf0, ap, s_p1); if (fixture.GetShape().GetType() === exports.b2ShapeType.e_circleShape) { p1.SelfSub(body.GetLocalCenter()); b2Rot.MulRV(body.m_xf0.q, p1, p1); b2Rot.MulTRV(body.m_xf.q, p1, p1); p1.SelfAdd(body.GetLocalCenter()); } b2Transform.MulXV(body.m_xf, p1, input.p1); } else input.p1.Copy(ap); b2Vec2.AddVMulSV(ap, this.m_step.dt, av, input.p2); input.maxFraction = 1; if (fixture.RayCast(output, input, childIndex)) { var n = output.normal; var p = s_p; p.x = (1 - output.fraction) * input.p1.x + output.fraction * input.p2.x + b2_linearSlop * n.x; p.y = (1 - output.fraction) * input.p1.y + output.fraction * input.p2.y + b2_linearSlop * n.y; var v = s_v; v.x = this.m_step.inv_dt * (p.x - ap.x); v.y = this.m_step.inv_dt * (p.y - ap.y); this.m_system.m_velocityBuffer.data[a].Copy(v); var f = s_f; f.x = this.m_step.inv_dt * this.m_system.GetParticleMass() * (av.x - v.x); f.y = this.m_step.inv_dt * this.m_system.GetParticleMass() * (av.y - v.y); this.m_system.ParticleApplyForce(a, f); } }; SolveCollisionCallback.prototype.ReportParticle = function(system, index) { return false; }; SolveCollisionCallback.ReportFixtureAndParticle_s_p1 = new b2Vec2(); SolveCollisionCallback.ReportFixtureAndParticle_s_output = new b2RayCastOutput(); SolveCollisionCallback.ReportFixtureAndParticle_s_input = new b2RayCastInput(); SolveCollisionCallback.ReportFixtureAndParticle_s_p = new b2Vec2(); SolveCollisionCallback.ReportFixtureAndParticle_s_v = new b2Vec2(); SolveCollisionCallback.ReportFixtureAndParticle_s_f = new b2Vec2(); return SolveCollisionCallback; })(b2FixtureParticleQueryCallback); b2ParticleSystem.SolveCollisionCallback = SolveCollisionCallback; })(exports.b2ParticleSystem || (exports.b2ParticleSystem = {})); var b2World = (function() { function b2World(gravity) { this.m_newFixture = false; this.m_locked = false; this.m_clearForces = true; this.m_contactManager = new b2ContactManager(); this.m_bodyList = null; this.m_jointList = null; this.m_particleSystemList = null; this.m_bodyCount = 0; this.m_jointCount = 0; this.m_gravity = new b2Vec2(); this.m_allowSleep = true; this.m_destructionListener = null; this.m_debugDraw = null; this.m_inv_dt0 = 0; this.m_warmStarting = true; this.m_continuousPhysics = true; this.m_subStepping = false; this.m_stepComplete = true; this.m_profile = new b2Profile(); this.m_island = new b2Island(); this.s_stack = []; this.m_controllerList = null; this.m_controllerCount = 0; this.m_gravity.Copy(gravity); } b2World.prototype.SetDestructionListener = function(listener) { this.m_destructionListener = listener; }; b2World.prototype.SetContactFilter = function(filter) { this.m_contactManager.m_contactFilter = filter; }; b2World.prototype.SetContactListener = function(listener) { this.m_contactManager.m_contactListener = listener; }; b2World.prototype.SetDebugDraw = function(debugDraw) { this.m_debugDraw = debugDraw; }; b2World.prototype.CreateBody = function(def) { void 0 === def && (def = {}); if (this.IsLocked()) throw new Error(); var b = new b2Body(def, this); b.m_prev = null; b.m_next = this.m_bodyList; this.m_bodyList && (this.m_bodyList.m_prev = b); this.m_bodyList = b; ++this.m_bodyCount; return b; }; b2World.prototype.DestroyBody = function(b) { if (this.IsLocked()) throw new Error(); var je = b.m_jointList; while (je) { var je0 = je; je = je.next; this.m_destructionListener && this.m_destructionListener.SayGoodbyeJoint(je0.joint); this.DestroyJoint(je0.joint); b.m_jointList = je; } b.m_jointList = null; var coe = b.m_controllerList; while (coe) { var coe0 = coe; coe = coe.nextController; coe0.controller.RemoveBody(b); } var ce = b.m_contactList; while (ce) { var ce0 = ce; ce = ce.next; this.m_contactManager.Destroy(ce0.contact); } b.m_contactList = null; var f = b.m_fixtureList; while (f) { var f0 = f; f = f.m_next; this.m_destructionListener && this.m_destructionListener.SayGoodbyeFixture(f0); f0.DestroyProxies(); f0.Destroy(); b.m_fixtureList = f; b.m_fixtureCount -= 1; } b.m_fixtureList = null; b.m_fixtureCount = 0; b.m_prev && (b.m_prev.m_next = b.m_next); b.m_next && (b.m_next.m_prev = b.m_prev); b === this.m_bodyList && (this.m_bodyList = b.m_next); --this.m_bodyCount; }; b2World._Joint_Create = function(def, allocator) { switch (def.type) { case exports.b2JointType.e_distanceJoint: return new b2DistanceJoint(def); case exports.b2JointType.e_mouseJoint: return new b2MouseJoint(def); case exports.b2JointType.e_prismaticJoint: return new b2PrismaticJoint(def); case exports.b2JointType.e_revoluteJoint: return new b2RevoluteJoint(def); case exports.b2JointType.e_pulleyJoint: return new b2PulleyJoint(def); case exports.b2JointType.e_gearJoint: return new b2GearJoint(def); case exports.b2JointType.e_wheelJoint: return new b2WheelJoint(def); case exports.b2JointType.e_weldJoint: return new b2WeldJoint(def); case exports.b2JointType.e_frictionJoint: return new b2FrictionJoint(def); case exports.b2JointType.e_ropeJoint: return new b2RopeJoint(def); case exports.b2JointType.e_motorJoint: return new b2MotorJoint(def); case exports.b2JointType.e_areaJoint: return new b2AreaJoint(def); } throw new Error(); }; b2World._Joint_Destroy = function(joint, allocator) {}; b2World.prototype.CreateJoint = function(def) { if (this.IsLocked()) throw new Error(); var j = b2World._Joint_Create(def, null); j.m_prev = null; j.m_next = this.m_jointList; this.m_jointList && (this.m_jointList.m_prev = j); this.m_jointList = j; ++this.m_jointCount; j.m_edgeA.prev = null; j.m_edgeA.next = j.m_bodyA.m_jointList; j.m_bodyA.m_jointList && (j.m_bodyA.m_jointList.prev = j.m_edgeA); j.m_bodyA.m_jointList = j.m_edgeA; j.m_edgeB.prev = null; j.m_edgeB.next = j.m_bodyB.m_jointList; j.m_bodyB.m_jointList && (j.m_bodyB.m_jointList.prev = j.m_edgeB); j.m_bodyB.m_jointList = j.m_edgeB; var bodyA = def.bodyA; var bodyB = def.bodyB; if (!def.collideConnected) { var edge = bodyB.GetContactList(); while (edge) { edge.other === bodyA && edge.contact.FlagForFiltering(); edge = edge.next; } } return j; }; b2World.prototype.DestroyJoint = function(j) { if (this.IsLocked()) throw new Error(); var collideConnected = j.m_collideConnected; j.m_prev && (j.m_prev.m_next = j.m_next); j.m_next && (j.m_next.m_prev = j.m_prev); j === this.m_jointList && (this.m_jointList = j.m_next); var bodyA = j.m_bodyA; var bodyB = j.m_bodyB; bodyA.SetAwake(true); bodyB.SetAwake(true); j.m_edgeA.prev && (j.m_edgeA.prev.next = j.m_edgeA.next); j.m_edgeA.next && (j.m_edgeA.next.prev = j.m_edgeA.prev); j.m_edgeA === bodyA.m_jointList && (bodyA.m_jointList = j.m_edgeA.next); j.m_edgeA.prev = null; j.m_edgeA.next = null; j.m_edgeB.prev && (j.m_edgeB.prev.next = j.m_edgeB.next); j.m_edgeB.next && (j.m_edgeB.next.prev = j.m_edgeB.prev); j.m_edgeB === bodyB.m_jointList && (bodyB.m_jointList = j.m_edgeB.next); j.m_edgeB.prev = null; j.m_edgeB.next = null; b2World._Joint_Destroy(j, null); --this.m_jointCount; if (!collideConnected) { var edge = bodyB.GetContactList(); while (edge) { edge.other === bodyA && edge.contact.FlagForFiltering(); edge = edge.next; } } }; b2World.prototype.CreateParticleSystem = function(def) { if (this.IsLocked()) throw new Error(); var p = new exports.b2ParticleSystem(def, this); p.m_prev = null; p.m_next = this.m_particleSystemList; this.m_particleSystemList && (this.m_particleSystemList.m_prev = p); this.m_particleSystemList = p; return p; }; b2World.prototype.DestroyParticleSystem = function(p) { if (this.IsLocked()) throw new Error(); p.m_prev && (p.m_prev.m_next = p.m_next); p.m_next && (p.m_next.m_prev = p.m_prev); p === this.m_particleSystemList && (this.m_particleSystemList = p.m_next); }; b2World.prototype.CalculateReasonableParticleIterations = function(timeStep) { if (null === this.m_particleSystemList) return 1; function GetSmallestRadius(world) { var smallestRadius = b2_maxFloat; for (var system = world.GetParticleSystemList(); null !== system; system = system.m_next) smallestRadius = b2Min(smallestRadius, system.GetRadius()); return smallestRadius; } return b2CalculateParticleIterations(this.m_gravity.Length(), GetSmallestRadius(this), timeStep); }; b2World.prototype.Step = function(dt, velocityIterations, positionIterations, particleIterations) { void 0 === particleIterations && (particleIterations = this.CalculateReasonableParticleIterations(dt)); var stepTimer = b2World.Step_s_stepTimer.Reset(); if (this.m_newFixture) { this.m_contactManager.FindNewContacts(); this.m_newFixture = false; } this.m_locked = true; var step = b2World.Step_s_step; step.dt = dt; step.velocityIterations = velocityIterations; step.positionIterations = positionIterations; step.particleIterations = particleIterations; step.inv_dt = dt > 0 ? 1 / dt : 0; step.dtRatio = this.m_inv_dt0 * dt; step.warmStarting = this.m_warmStarting; var timer = b2World.Step_s_timer.Reset(); this.m_contactManager.Collide(); this.m_profile.collide = timer.GetMilliseconds(); if (this.m_stepComplete && step.dt > 0) { var timer_1 = b2World.Step_s_timer.Reset(); for (var p = this.m_particleSystemList; p; p = p.m_next) p.Solve(step); this.Solve(step); this.m_profile.solve = timer_1.GetMilliseconds(); } if (this.m_continuousPhysics && step.dt > 0) { var timer_2 = b2World.Step_s_timer.Reset(); this.SolveTOI(step); this.m_profile.solveTOI = timer_2.GetMilliseconds(); } step.dt > 0 && (this.m_inv_dt0 = step.inv_dt); this.m_clearForces && this.ClearForces(); this.m_locked = false; this.m_profile.step = stepTimer.GetMilliseconds(); }; b2World.prototype.ClearForces = function() { for (var body = this.m_bodyList; body; body = body.m_next) { body.m_force.SetZero(); body.m_torque = 0; } }; b2World.prototype.DrawParticleSystem = function(system) { if (null === this.m_debugDraw) return; var particleCount = system.GetParticleCount(); if (particleCount) { var radius = system.GetRadius(); var positionBuffer = system.GetPositionBuffer(); if (system.m_colorBuffer.data) { var colorBuffer = system.GetColorBuffer(); this.m_debugDraw.DrawParticles(positionBuffer, radius, colorBuffer, particleCount); } else this.m_debugDraw.DrawParticles(positionBuffer, radius, null, particleCount); } }; b2World.prototype.DrawDebugData = function() { if (null === this.m_debugDraw) return; var flags = this.m_debugDraw.GetFlags(); var color = b2World.DrawDebugData_s_color.SetRGB(0, 0, 0); if (flags & exports.b2DrawFlags.e_shapeBit) for (var b = this.m_bodyList; b; b = b.m_next) { var xf = b.m_xf; this.m_debugDraw.PushTransform(xf); for (var f = b.GetFixtureList(); f; f = f.m_next) if (b.IsActive()) if (b.GetType() === exports.b2BodyType.b2_staticBody) { color.SetRGB(.5, .9, .5); this.DrawShape(f, color); } else if (b.GetType() === exports.b2BodyType.b2_kinematicBody) { color.SetRGB(.5, .5, .9); this.DrawShape(f, color); } else if (b.IsAwake()) { color.SetRGB(.9, .7, .7); this.DrawShape(f, color); } else { color.SetRGB(.6, .6, .6); this.DrawShape(f, color); } else { color.SetRGB(.5, .5, .3); this.DrawShape(f, color); } this.m_debugDraw.PopTransform(xf); } if (flags & exports.b2DrawFlags.e_particleBit) for (var p = this.m_particleSystemList; p; p = p.m_next) this.DrawParticleSystem(p); if (flags & exports.b2DrawFlags.e_jointBit) for (var j = this.m_jointList; j; j = j.m_next) this.DrawJoint(j); if (flags & exports.b2DrawFlags.e_aabbBit) { color.SetRGB(.9, .3, .9); var vs = b2World.DrawDebugData_s_vs; for (var b = this.m_bodyList; b; b = b.m_next) { if (!b.IsActive()) continue; for (var f = b.GetFixtureList(); f; f = f.m_next) for (var i = 0; i < f.m_proxyCount; ++i) { var proxy = f.m_proxies[i]; var aabb = proxy.treeNode.aabb; vs[0].Set(aabb.lowerBound.x, aabb.lowerBound.y); vs[1].Set(aabb.upperBound.x, aabb.lowerBound.y); vs[2].Set(aabb.upperBound.x, aabb.upperBound.y); vs[3].Set(aabb.lowerBound.x, aabb.upperBound.y); this.m_debugDraw.DrawPolygon(vs, 4, color); } } } if (flags & exports.b2DrawFlags.e_centerOfMassBit) for (var b = this.m_bodyList; b; b = b.m_next) { var xf = b2World.DrawDebugData_s_xf; xf.q.Copy(b.m_xf.q); xf.p.Copy(b.GetWorldCenter()); this.m_debugDraw.DrawTransform(xf); } if (flags & exports.b2DrawFlags.e_controllerBit) for (var c = this.m_controllerList; c; c = c.m_next) c.Draw(this.m_debugDraw); }; b2World.prototype.QueryAABB = function(callback, aabb, fn) { this.m_contactManager.m_broadPhase.Query(aabb, (function(proxy) { var fixture_proxy = proxy.userData; var fixture = fixture_proxy.fixture; if (callback) return callback.ReportFixture(fixture); if (fn) return fn(fixture); return true; })); if (callback instanceof b2QueryCallback) for (var p = this.m_particleSystemList; p; p = p.m_next) callback.ShouldQueryParticleSystem(p) && p.QueryAABB(callback, aabb); }; b2World.prototype.QueryAllAABB = function(aabb, out) { void 0 === out && (out = []); this.QueryAABB(null, aabb, (function(fixture) { out.push(fixture); return true; })); return out; }; b2World.prototype.QueryPointAABB = function(callback, point, fn) { this.m_contactManager.m_broadPhase.QueryPoint(point, (function(proxy) { var fixture_proxy = proxy.userData; var fixture = fixture_proxy.fixture; if (callback) return callback.ReportFixture(fixture); if (fn) return fn(fixture); return true; })); if (callback instanceof b2QueryCallback) for (var p = this.m_particleSystemList; p; p = p.m_next) callback.ShouldQueryParticleSystem(p) && p.QueryPointAABB(callback, point); }; b2World.prototype.QueryAllPointAABB = function(point, out) { void 0 === out && (out = []); this.QueryPointAABB(null, point, (function(fixture) { out.push(fixture); return true; })); return out; }; b2World.prototype.QueryFixtureShape = function(callback, shape, index, transform, fn) { var aabb = b2World.QueryFixtureShape_s_aabb; shape.ComputeAABB(aabb, transform, index); this.m_contactManager.m_broadPhase.Query(aabb, (function(proxy) { var fixture_proxy = proxy.userData; var fixture = fixture_proxy.fixture; if (b2TestOverlapShape(shape, index, fixture.GetShape(), fixture_proxy.childIndex, transform, fixture.GetBody().GetTransform())) { if (callback) return callback.ReportFixture(fixture); if (fn) return fn(fixture); } return true; })); if (callback instanceof b2QueryCallback) for (var p = this.m_particleSystemList; p; p = p.m_next) callback.ShouldQueryParticleSystem(p) && p.QueryAABB(callback, aabb); }; b2World.prototype.QueryAllFixtureShape = function(shape, index, transform, out) { void 0 === out && (out = []); this.QueryFixtureShape(null, shape, index, transform, (function(fixture) { out.push(fixture); return true; })); return out; }; b2World.prototype.QueryFixturePoint = function(callback, point, fn) { this.m_contactManager.m_broadPhase.QueryPoint(point, (function(proxy) { var fixture_proxy = proxy.userData; var fixture = fixture_proxy.fixture; if (fixture.TestPoint(point)) { if (callback) return callback.ReportFixture(fixture); if (fn) return fn(fixture); } return true; })); if (callback) for (var p = this.m_particleSystemList; p; p = p.m_next) callback.ShouldQueryParticleSystem(p) && p.QueryPointAABB(callback, point); }; b2World.prototype.QueryAllFixturePoint = function(point, out) { void 0 === out && (out = []); this.QueryFixturePoint(null, point, (function(fixture) { out.push(fixture); return true; })); return out; }; b2World.prototype.RayCast = function(callback, point1, point2, fn) { var input = b2World.RayCast_s_input; input.maxFraction = 1; input.p1.Copy(point1); input.p2.Copy(point2); this.m_contactManager.m_broadPhase.RayCast(input, (function(input, proxy) { var fixture_proxy = proxy.userData; var fixture = fixture_proxy.fixture; var index = fixture_proxy.childIndex; var output = b2World.RayCast_s_output; var hit = fixture.RayCast(output, input, index); if (hit) { var fraction = output.fraction; var point = b2World.RayCast_s_point; point.Set((1 - fraction) * point1.x + fraction * point2.x, (1 - fraction) * point1.y + fraction * point2.y); if (callback) return callback.ReportFixture(fixture, point, output.normal, fraction); if (fn) return fn(fixture, point, output.normal, fraction); } return input.maxFraction; })); if (callback) for (var p = this.m_particleSystemList; p; p = p.m_next) callback.ShouldQueryParticleSystem(p) && p.RayCast(callback, point1, point2); }; b2World.prototype.RayCastOne = function(point1, point2) { var result = null; var min_fraction = 1; this.RayCast(null, point1, point2, (function(fixture, point, normal, fraction) { if (fraction < min_fraction) { min_fraction = fraction; result = fixture; } return min_fraction; })); return result; }; b2World.prototype.RayCastAll = function(point1, point2, out) { void 0 === out && (out = []); this.RayCast(null, point1, point2, (function(fixture, point, normal, fraction) { out.push(fixture); return 1; })); return out; }; b2World.prototype.GetBodyList = function() { return this.m_bodyList; }; b2World.prototype.GetJointList = function() { return this.m_jointList; }; b2World.prototype.GetParticleSystemList = function() { return this.m_particleSystemList; }; b2World.prototype.GetContactList = function() { return this.m_contactManager.m_contactList; }; b2World.prototype.SetAllowSleeping = function(flag) { if (flag === this.m_allowSleep) return; this.m_allowSleep = flag; if (!this.m_allowSleep) for (var b = this.m_bodyList; b; b = b.m_next) b.SetAwake(true); }; b2World.prototype.GetAllowSleeping = function() { return this.m_allowSleep; }; b2World.prototype.SetWarmStarting = function(flag) { this.m_warmStarting = flag; }; b2World.prototype.GetWarmStarting = function() { return this.m_warmStarting; }; b2World.prototype.SetContinuousPhysics = function(flag) { this.m_continuousPhysics = flag; }; b2World.prototype.GetContinuousPhysics = function() { return this.m_continuousPhysics; }; b2World.prototype.SetSubStepping = function(flag) { this.m_subStepping = flag; }; b2World.prototype.GetSubStepping = function() { return this.m_subStepping; }; b2World.prototype.GetProxyCount = function() { return this.m_contactManager.m_broadPhase.GetProxyCount(); }; b2World.prototype.GetBodyCount = function() { return this.m_bodyCount; }; b2World.prototype.GetJointCount = function() { return this.m_jointCount; }; b2World.prototype.GetContactCount = function() { return this.m_contactManager.m_contactCount; }; b2World.prototype.GetTreeHeight = function() { return this.m_contactManager.m_broadPhase.GetTreeHeight(); }; b2World.prototype.GetTreeBalance = function() { return this.m_contactManager.m_broadPhase.GetTreeBalance(); }; b2World.prototype.GetTreeQuality = function() { return this.m_contactManager.m_broadPhase.GetTreeQuality(); }; b2World.prototype.SetGravity = function(gravity, wake) { void 0 === wake && (wake = true); if (!b2Vec2.IsEqualToV(this.m_gravity, gravity)) { this.m_gravity.Copy(gravity); if (wake) for (var b = this.m_bodyList; b; b = b.m_next) b.SetAwake(true); } }; b2World.prototype.GetGravity = function() { return this.m_gravity; }; b2World.prototype.IsLocked = function() { return this.m_locked; }; b2World.prototype.SetAutoClearForces = function(flag) { this.m_clearForces = flag; }; b2World.prototype.GetAutoClearForces = function() { return this.m_clearForces; }; b2World.prototype.ShiftOrigin = function(newOrigin) { if (this.IsLocked()) throw new Error(); for (var b = this.m_bodyList; b; b = b.m_next) { b.m_xf.p.SelfSub(newOrigin); b.m_sweep.c0.SelfSub(newOrigin); b.m_sweep.c.SelfSub(newOrigin); } for (var j = this.m_jointList; j; j = j.m_next) j.ShiftOrigin(newOrigin); this.m_contactManager.m_broadPhase.ShiftOrigin(newOrigin); }; b2World.prototype.GetContactManager = function() { return this.m_contactManager; }; b2World.prototype.GetProfile = function() { return this.m_profile; }; b2World.prototype.Dump = function(log) { if (this.m_locked) return; log("const g: b2Vec2 = new b2Vec2(%.15f, %.15f);\n", this.m_gravity.x, this.m_gravity.y); log("this.m_world.SetGravity(g);\n"); log("const bodies: b2Body[] = [];\n"); log("const joints: b2Joint[] = [];\n"); var i = 0; for (var b = this.m_bodyList; b; b = b.m_next) { b.m_islandIndex = i; b.Dump(log); ++i; } i = 0; for (var j = this.m_jointList; j; j = j.m_next) { j.m_index = i; ++i; } for (var j = this.m_jointList; j; j = j.m_next) { if (j.m_type === exports.b2JointType.e_gearJoint) continue; log("{\n"); j.Dump(log); log("}\n"); } for (var j = this.m_jointList; j; j = j.m_next) { if (j.m_type !== exports.b2JointType.e_gearJoint) continue; log("{\n"); j.Dump(log); log("}\n"); } }; b2World.prototype.DrawJoint = function(joint) { if (null === this.m_debugDraw) return; var bodyA = joint.GetBodyA(); var bodyB = joint.GetBodyB(); var xf1 = bodyA.m_xf; var xf2 = bodyB.m_xf; var x1 = xf1.p; var x2 = xf2.p; var p1 = joint.GetAnchorA(b2World.DrawJoint_s_p1); var p2 = joint.GetAnchorB(b2World.DrawJoint_s_p2); var color = b2World.DrawJoint_s_color.SetRGB(.5, .8, .8); switch (joint.m_type) { case exports.b2JointType.e_distanceJoint: this.m_debugDraw.DrawSegment(p1, p2, color); break; case exports.b2JointType.e_pulleyJoint: var pulley = joint; var s1 = pulley.GetGroundAnchorA(); var s2 = pulley.GetGroundAnchorB(); this.m_debugDraw.DrawSegment(s1, p1, color); this.m_debugDraw.DrawSegment(s2, p2, color); this.m_debugDraw.DrawSegment(s1, s2, color); break; case exports.b2JointType.e_mouseJoint: var c = b2World.DrawJoint_s_c; c.Set(0, 1, 0); this.m_debugDraw.DrawPoint(p1, 4, c); this.m_debugDraw.DrawPoint(p2, 4, c); c.Set(.8, .8, .8); this.m_debugDraw.DrawSegment(p1, p2, c); break; default: this.m_debugDraw.DrawSegment(x1, p1, color); this.m_debugDraw.DrawSegment(p1, p2, color); this.m_debugDraw.DrawSegment(x2, p2, color); } }; b2World.prototype.DrawShape = function(fixture, color) { if (null === this.m_debugDraw) return; var shape = fixture.GetShape(); switch (shape.m_type) { case exports.b2ShapeType.e_circleShape: var circle = shape; var center = circle.m_p; var radius = circle.m_radius; var axis = b2Vec2.UNITX; this.m_debugDraw.DrawSolidCircle(center, radius, axis, color); break; case exports.b2ShapeType.e_edgeShape: var edge = shape; var v1 = edge.m_vertex1; var v2 = edge.m_vertex2; this.m_debugDraw.DrawSegment(v1, v2, color); break; case exports.b2ShapeType.e_chainShape: var chain = shape; var count = chain.m_count; var vertices = chain.m_vertices; var ghostColor = b2World.DrawShape_s_ghostColor.SetRGBA(.75 * color.r, .75 * color.g, .75 * color.b, color.a); var v1 = vertices[0]; this.m_debugDraw.DrawPoint(v1, 4, color); if (chain.m_hasPrevVertex) { var vp = chain.m_prevVertex; this.m_debugDraw.DrawSegment(vp, v1, ghostColor); this.m_debugDraw.DrawCircle(vp, .1, ghostColor); } for (var i = 1; i < count; ++i) { var v2 = vertices[i]; this.m_debugDraw.DrawSegment(v1, v2, color); this.m_debugDraw.DrawPoint(v2, 4, color); v1 = v2; } if (chain.m_hasNextVertex) { var vn = chain.m_nextVertex; this.m_debugDraw.DrawSegment(vn, v1, ghostColor); this.m_debugDraw.DrawCircle(vn, .1, ghostColor); } break; case exports.b2ShapeType.e_polygonShape: var poly = shape; var vertexCount = poly.m_count; var vertices = poly.m_vertices; this.m_debugDraw.DrawSolidPolygon(vertices, vertexCount, color); } }; b2World.prototype.Solve = function(step) { for (var b = this.m_bodyList; b; b = b.m_next) b.m_xf0.Copy(b.m_xf); for (var controller = this.m_controllerList; controller; controller = controller.m_next) controller.Step(step); this.m_profile.solveInit = 0; this.m_profile.solveVelocity = 0; this.m_profile.solvePosition = 0; var island = this.m_island; island.Initialize(this.m_bodyCount, this.m_contactManager.m_contactCount, this.m_jointCount, null, this.m_contactManager.m_contactListener); for (var b = this.m_bodyList; b; b = b.m_next) b.m_islandFlag = false; for (var c = this.m_contactManager.m_contactList; c; c = c.m_next) c.m_islandFlag = false; for (var j = this.m_jointList; j; j = j.m_next) j.m_islandFlag = false; var stack = this.s_stack; for (var seed = this.m_bodyList; seed; seed = seed.m_next) { if (seed.m_islandFlag) continue; if (!seed.IsAwake() || !seed.IsActive()) continue; if (seed.GetType() === exports.b2BodyType.b2_staticBody) continue; island.Clear(); var stackCount = 0; stack[stackCount++] = seed; seed.m_islandFlag = true; while (stackCount > 0) { var b = stack[--stackCount]; if (!b) throw new Error(); island.AddBody(b); b.m_awakeFlag = true; if (b.GetType() === exports.b2BodyType.b2_staticBody) continue; for (var ce = b.m_contactList; ce; ce = ce.next) { var contact = ce.contact; if (contact.m_islandFlag) continue; if (!contact.IsEnabled() || !contact.IsTouching()) continue; var sensorA = contact.m_fixtureA.m_isSensor; var sensorB = contact.m_fixtureB.m_isSensor; if (sensorA || sensorB) continue; island.AddContact(contact); contact.m_islandFlag = true; var other = ce.other; if (!other) throw new Error(); if (other.m_islandFlag) continue; stack[stackCount++] = other; other.m_islandFlag = true; } for (var je = b.m_jointList; je; je = je.next) { if (je.joint.m_islandFlag) continue; var other = je.other; if (!other.IsActive()) continue; island.AddJoint(je.joint); je.joint.m_islandFlag = true; if (other.m_islandFlag) continue; stack[stackCount++] = other; other.m_islandFlag = true; } } var profile = new b2Profile(); island.Solve(profile, step, this.m_gravity, this.m_allowSleep); this.m_profile.solveInit += profile.solveInit; this.m_profile.solveVelocity += profile.solveVelocity; this.m_profile.solvePosition += profile.solvePosition; for (var i = 0; i < island.m_bodyCount; ++i) { var b = island.m_bodies[i]; b.GetType() === exports.b2BodyType.b2_staticBody && (b.m_islandFlag = false); } } for (var i = 0; i < stack.length; ++i) { if (!stack[i]) break; stack[i] = null; } var timer = new b2Timer(); for (var b = this.m_bodyList; b; b = b.m_next) { if (!b.m_islandFlag) continue; if (b.GetType() === exports.b2BodyType.b2_staticBody) continue; b.SynchronizeFixtures(); } this.m_contactManager.FindNewContacts(); this.m_profile.broadphase = timer.GetMilliseconds(); }; b2World.prototype.SolveTOI = function(step) { var island = this.m_island; island.Initialize(2 * b2_maxTOIContacts, b2_maxTOIContacts, 0, null, this.m_contactManager.m_contactListener); if (this.m_stepComplete) { for (var b = this.m_bodyList; b; b = b.m_next) { b.m_islandFlag = false; b.m_sweep.alpha0 = 0; } for (var c = this.m_contactManager.m_contactList; c; c = c.m_next) { c.m_toiFlag = false; c.m_islandFlag = false; c.m_toiCount = 0; c.m_toi = 1; } } for (;;) { var minContact = null; var minAlpha = 1; for (var c = this.m_contactManager.m_contactList; c; c = c.m_next) { if (!c.IsEnabled()) continue; if (c.m_toiCount > b2_maxSubSteps) continue; var alpha = 1; if (c.m_toiFlag) alpha = c.m_toi; else { var fA_1 = c.GetFixtureA(); var fB_1 = c.GetFixtureB(); if (fA_1.IsSensor() || fB_1.IsSensor()) continue; var bA_1 = fA_1.GetBody(); var bB_1 = fB_1.GetBody(); var typeA = bA_1.m_type; var typeB = bB_1.m_type; var activeA = bA_1.IsAwake() && typeA !== exports.b2BodyType.b2_staticBody; var activeB = bB_1.IsAwake() && typeB !== exports.b2BodyType.b2_staticBody; if (!activeA && !activeB) continue; var collideA = bA_1.IsBullet() || typeA !== exports.b2BodyType.b2_dynamicBody; var collideB = bB_1.IsBullet() || typeB !== exports.b2BodyType.b2_dynamicBody; if (!collideA && !collideB) continue; var alpha0 = bA_1.m_sweep.alpha0; if (bA_1.m_sweep.alpha0 < bB_1.m_sweep.alpha0) { alpha0 = bB_1.m_sweep.alpha0; bA_1.m_sweep.Advance(alpha0); } else if (bB_1.m_sweep.alpha0 < bA_1.m_sweep.alpha0) { alpha0 = bA_1.m_sweep.alpha0; bB_1.m_sweep.Advance(alpha0); } var indexA = c.GetChildIndexA(); var indexB = c.GetChildIndexB(); var input = b2World.SolveTOI_s_toi_input; input.proxyA.SetShape(fA_1.GetShape(), indexA); input.proxyB.SetShape(fB_1.GetShape(), indexB); input.sweepA.Copy(bA_1.m_sweep); input.sweepB.Copy(bB_1.m_sweep); input.tMax = 1; var output = b2World.SolveTOI_s_toi_output; b2TimeOfImpact(output, input); var beta = output.t; alpha = output.state === exports.b2TOIOutputState.e_touching ? b2Min(alpha0 + (1 - alpha0) * beta, 1) : 1; c.m_toi = alpha; c.m_toiFlag = true; } if (alpha < minAlpha) { minContact = c; minAlpha = alpha; } } if (null === minContact || 1 - 10 * b2_epsilon < minAlpha) { this.m_stepComplete = true; break; } var fA = minContact.GetFixtureA(); var fB = minContact.GetFixtureB(); var bA = fA.GetBody(); var bB = fB.GetBody(); var backup1 = b2World.SolveTOI_s_backup1.Copy(bA.m_sweep); var backup2 = b2World.SolveTOI_s_backup2.Copy(bB.m_sweep); bA.Advance(minAlpha); bB.Advance(minAlpha); minContact.Update(this.m_contactManager.m_contactListener); minContact.m_toiFlag = false; ++minContact.m_toiCount; if (!minContact.IsEnabled() || !minContact.IsTouching()) { minContact.SetEnabled(false); bA.m_sweep.Copy(backup1); bB.m_sweep.Copy(backup2); bA.SynchronizeTransform(); bB.SynchronizeTransform(); continue; } bA.SetAwake(true); bB.SetAwake(true); island.Clear(); island.AddBody(bA); island.AddBody(bB); island.AddContact(minContact); bA.m_islandFlag = true; bB.m_islandFlag = true; minContact.m_islandFlag = true; for (var i = 0; i < 2; ++i) { var body = 0 === i ? bA : bB; if (body.m_type === exports.b2BodyType.b2_dynamicBody) for (var ce = body.m_contactList; ce; ce = ce.next) { if (island.m_bodyCount === island.m_bodyCapacity) break; if (island.m_contactCount === island.m_contactCapacity) break; var contact = ce.contact; if (contact.m_islandFlag) continue; var other = ce.other; if (other.m_type === exports.b2BodyType.b2_dynamicBody && !body.IsBullet() && !other.IsBullet()) continue; var sensorA = contact.m_fixtureA.m_isSensor; var sensorB = contact.m_fixtureB.m_isSensor; if (sensorA || sensorB) continue; var backup = b2World.SolveTOI_s_backup.Copy(other.m_sweep); other.m_islandFlag || other.Advance(minAlpha); contact.Update(this.m_contactManager.m_contactListener); if (!contact.IsEnabled()) { other.m_sweep.Copy(backup); other.SynchronizeTransform(); continue; } if (!contact.IsTouching()) { other.m_sweep.Copy(backup); other.SynchronizeTransform(); continue; } contact.m_islandFlag = true; island.AddContact(contact); if (other.m_islandFlag) continue; other.m_islandFlag = true; other.m_type !== exports.b2BodyType.b2_staticBody && other.SetAwake(true); island.AddBody(other); } } var subStep = b2World.SolveTOI_s_subStep; subStep.dt = (1 - minAlpha) * step.dt; subStep.inv_dt = 1 / subStep.dt; subStep.dtRatio = 1; subStep.positionIterations = 20; subStep.velocityIterations = step.velocityIterations; subStep.particleIterations = step.particleIterations; subStep.warmStarting = false; island.SolveTOI(subStep, bA.m_islandIndex, bB.m_islandIndex); for (var i = 0; i < island.m_bodyCount; ++i) { var body = island.m_bodies[i]; body.m_islandFlag = false; if (body.m_type !== exports.b2BodyType.b2_dynamicBody) continue; body.SynchronizeFixtures(); for (var ce = body.m_contactList; ce; ce = ce.next) { ce.contact.m_toiFlag = false; ce.contact.m_islandFlag = false; } } this.m_contactManager.FindNewContacts(); if (this.m_subStepping) { this.m_stepComplete = false; break; } } }; b2World.prototype.AddController = function(controller) { controller.m_next = this.m_controllerList; controller.m_prev = null; this.m_controllerList && (this.m_controllerList.m_prev = controller); this.m_controllerList = controller; ++this.m_controllerCount; return controller; }; b2World.prototype.RemoveController = function(controller) { controller.m_prev && (controller.m_prev.m_next = controller.m_next); controller.m_next && (controller.m_next.m_prev = controller.m_prev); this.m_controllerList === controller && (this.m_controllerList = controller.m_next); --this.m_controllerCount; controller.m_prev = null; controller.m_next = null; return controller; }; b2World.Step_s_step = new b2TimeStep(); b2World.Step_s_stepTimer = new b2Timer(); b2World.Step_s_timer = new b2Timer(); b2World.DrawDebugData_s_color = new b2Color(0, 0, 0); b2World.DrawDebugData_s_vs = b2Vec2.MakeArray(4); b2World.DrawDebugData_s_xf = new b2Transform(); b2World.QueryFixtureShape_s_aabb = new b2AABB(); b2World.RayCast_s_input = new b2RayCastInput(); b2World.RayCast_s_output = new b2RayCastOutput(); b2World.RayCast_s_point = new b2Vec2(); b2World.DrawJoint_s_p1 = new b2Vec2(); b2World.DrawJoint_s_p2 = new b2Vec2(); b2World.DrawJoint_s_color = new b2Color(.5, .8, .8); b2World.DrawJoint_s_c = new b2Color(); b2World.DrawShape_s_ghostColor = new b2Color(); b2World.SolveTOI_s_subStep = new b2TimeStep(); b2World.SolveTOI_s_backup = new b2Sweep(); b2World.SolveTOI_s_backup1 = new b2Sweep(); b2World.SolveTOI_s_backup2 = new b2Sweep(); b2World.SolveTOI_s_toi_input = new b2TOIInput(); b2World.SolveTOI_s_toi_output = new b2TOIOutput(); return b2World; })(); var b2ControllerEdge = (function() { function b2ControllerEdge(controller, body) { this.prevBody = null; this.nextBody = null; this.prevController = null; this.nextController = null; this.controller = controller; this.body = body; } return b2ControllerEdge; })(); var b2Controller = (function() { function b2Controller() { this.m_bodyList = null; this.m_bodyCount = 0; this.m_prev = null; this.m_next = null; } b2Controller.prototype.GetNext = function() { return this.m_next; }; b2Controller.prototype.GetPrev = function() { return this.m_prev; }; b2Controller.prototype.GetBodyList = function() { return this.m_bodyList; }; b2Controller.prototype.AddBody = function(body) { var edge = new b2ControllerEdge(this, body); edge.nextBody = this.m_bodyList; edge.prevBody = null; this.m_bodyList && (this.m_bodyList.prevBody = edge); this.m_bodyList = edge; ++this.m_bodyCount; edge.nextController = body.m_controllerList; edge.prevController = null; body.m_controllerList && (body.m_controllerList.prevController = edge); body.m_controllerList = edge; ++body.m_controllerCount; }; b2Controller.prototype.RemoveBody = function(body) { if (this.m_bodyCount <= 0) throw new Error(); var edge = this.m_bodyList; while (edge && edge.body !== body) edge = edge.nextBody; if (null === edge) throw new Error(); edge.prevBody && (edge.prevBody.nextBody = edge.nextBody); edge.nextBody && (edge.nextBody.prevBody = edge.prevBody); this.m_bodyList === edge && (this.m_bodyList = edge.nextBody); --this.m_bodyCount; edge.nextController && (edge.nextController.prevController = edge.prevController); edge.prevController && (edge.prevController.nextController = edge.nextController); body.m_controllerList === edge && (body.m_controllerList = edge.nextController); --body.m_controllerCount; }; b2Controller.prototype.Clear = function() { while (this.m_bodyList) this.RemoveBody(this.m_bodyList.body); this.m_bodyCount = 0; }; return b2Controller; })(); var b2BuoyancyController = (function(_super) { __extends(b2BuoyancyController, _super); function b2BuoyancyController() { var _this = null !== _super && _super.apply(this, arguments) || this; _this.normal = new b2Vec2(0, 1); _this.offset = 0; _this.density = 0; _this.velocity = new b2Vec2(0, 0); _this.linearDrag = 0; _this.angularDrag = 0; _this.useDensity = false; _this.useWorldGravity = true; _this.gravity = new b2Vec2(0, 0); return _this; } b2BuoyancyController.prototype.Step = function(step) { if (!this.m_bodyList) return; this.useWorldGravity && this.gravity.Copy(this.m_bodyList.body.GetWorld().GetGravity()); for (var i = this.m_bodyList; i; i = i.nextBody) { var body = i.body; if (!body.IsAwake()) continue; var areac = new b2Vec2(); var massc = new b2Vec2(); var area = 0; var mass = 0; for (var fixture = body.GetFixtureList(); fixture; fixture = fixture.m_next) { var sc = new b2Vec2(); var sarea = fixture.GetShape().ComputeSubmergedArea(this.normal, this.offset, body.GetTransform(), sc); area += sarea; areac.x += sarea * sc.x; areac.y += sarea * sc.y; var shapeDensity = 0; shapeDensity = this.useDensity ? fixture.GetDensity() : 1; mass += sarea * shapeDensity; massc.x += sarea * sc.x * shapeDensity; massc.y += sarea * sc.y * shapeDensity; } areac.x /= area; areac.y /= area; massc.x /= mass; massc.y /= mass; if (area < b2_epsilon) continue; var buoyancyForce = this.gravity.Clone().SelfNeg(); buoyancyForce.SelfMul(this.density * area); body.ApplyForce(buoyancyForce, massc); var dragForce = body.GetLinearVelocityFromWorldPoint(areac, new b2Vec2()); dragForce.SelfSub(this.velocity); dragForce.SelfMul(-this.linearDrag * area); body.ApplyForce(dragForce, areac); body.ApplyTorque(-body.GetInertia() / body.GetMass() * area * body.GetAngularVelocity() * this.angularDrag); } }; b2BuoyancyController.prototype.Draw = function(debugDraw) { var r = 100; var p1 = new b2Vec2(); var p2 = new b2Vec2(); p1.x = this.normal.x * this.offset + this.normal.y * r; p1.y = this.normal.y * this.offset - this.normal.x * r; p2.x = this.normal.x * this.offset - this.normal.y * r; p2.y = this.normal.y * this.offset + this.normal.x * r; var color = new b2Color(0, 0, .8); debugDraw.DrawSegment(p1, p2, color); }; return b2BuoyancyController; })(b2Controller); var b2ConstantAccelController = (function(_super) { __extends(b2ConstantAccelController, _super); function b2ConstantAccelController() { var _this = null !== _super && _super.apply(this, arguments) || this; _this.A = new b2Vec2(0, 0); return _this; } b2ConstantAccelController.prototype.Step = function(step) { var dtA = b2Vec2.MulSV(step.dt, this.A, b2ConstantAccelController.Step_s_dtA); for (var i = this.m_bodyList; i; i = i.nextBody) { var body = i.body; if (!body.IsAwake()) continue; body.SetLinearVelocity(b2Vec2.AddVV(body.GetLinearVelocity(), dtA, b2Vec2.s_t0)); } }; b2ConstantAccelController.prototype.Draw = function(draw) {}; b2ConstantAccelController.Step_s_dtA = new b2Vec2(); return b2ConstantAccelController; })(b2Controller); var b2ConstantForceController = (function(_super) { __extends(b2ConstantForceController, _super); function b2ConstantForceController() { var _this = null !== _super && _super.apply(this, arguments) || this; _this.F = new b2Vec2(0, 0); return _this; } b2ConstantForceController.prototype.Step = function(step) { for (var i = this.m_bodyList; i; i = i.nextBody) { var body = i.body; if (!body.IsAwake()) continue; body.ApplyForce(this.F, body.GetWorldCenter()); } }; b2ConstantForceController.prototype.Draw = function(draw) {}; return b2ConstantForceController; })(b2Controller); var b2GravityController = (function(_super) { __extends(b2GravityController, _super); function b2GravityController() { var _this = null !== _super && _super.apply(this, arguments) || this; _this.G = 1; _this.invSqr = true; return _this; } b2GravityController.prototype.Step = function(step) { if (this.invSqr) for (var i = this.m_bodyList; i; i = i.nextBody) { var body1 = i.body; var p1 = body1.GetWorldCenter(); var mass1 = body1.GetMass(); for (var j = this.m_bodyList; j && j !== i; j = j.nextBody) { var body2 = j.body; var p2 = body2.GetWorldCenter(); var mass2 = body2.GetMass(); var dx = p2.x - p1.x; var dy = p2.y - p1.y; var r2 = dx * dx + dy * dy; if (r2 < b2_epsilon) continue; var f = b2GravityController.Step_s_f.Set(dx, dy); f.SelfMul(this.G / r2 / b2Sqrt(r2) * mass1 * mass2); body1.IsAwake() && body1.ApplyForce(f, p1); body2.IsAwake() && body2.ApplyForce(f.SelfMul(-1), p2); } } else for (var i = this.m_bodyList; i; i = i.nextBody) { var body1 = i.body; var p1 = body1.GetWorldCenter(); var mass1 = body1.GetMass(); for (var j = this.m_bodyList; j && j !== i; j = j.nextBody) { var body2 = j.body; var p2 = body2.GetWorldCenter(); var mass2 = body2.GetMass(); var dx = p2.x - p1.x; var dy = p2.y - p1.y; var r2 = dx * dx + dy * dy; if (r2 < b2_epsilon) continue; var f = b2GravityController.Step_s_f.Set(dx, dy); f.SelfMul(this.G / r2 * mass1 * mass2); body1.IsAwake() && body1.ApplyForce(f, p1); body2.IsAwake() && body2.ApplyForce(f.SelfMul(-1), p2); } } }; b2GravityController.prototype.Draw = function(draw) {}; b2GravityController.Step_s_f = new b2Vec2(); return b2GravityController; })(b2Controller); var b2TensorDampingController = (function(_super) { __extends(b2TensorDampingController, _super); function b2TensorDampingController() { var _this = null !== _super && _super.apply(this, arguments) || this; _this.T = new b2Mat22(); _this.maxTimestep = 0; return _this; } b2TensorDampingController.prototype.Step = function(step) { var timestep = step.dt; if (timestep <= b2_epsilon) return; timestep > this.maxTimestep && this.maxTimestep > 0 && (timestep = this.maxTimestep); for (var i = this.m_bodyList; i; i = i.nextBody) { var body = i.body; if (!body.IsAwake()) continue; var damping = body.GetWorldVector(b2Mat22.MulMV(this.T, body.GetLocalVector(body.GetLinearVelocity(), b2Vec2.s_t0), b2Vec2.s_t1), b2TensorDampingController.Step_s_damping); body.SetLinearVelocity(b2Vec2.AddVV(body.GetLinearVelocity(), b2Vec2.MulSV(timestep, damping, b2Vec2.s_t0), b2Vec2.s_t1)); } }; b2TensorDampingController.prototype.Draw = function(draw) {}; b2TensorDampingController.prototype.SetAxisAligned = function(xDamping, yDamping) { this.T.ex.x = -xDamping; this.T.ex.y = 0; this.T.ey.x = 0; this.T.ey.y = -yDamping; this.maxTimestep = xDamping > 0 || yDamping > 0 ? 1 / b2Max(xDamping, yDamping) : 0; }; b2TensorDampingController.Step_s_damping = new b2Vec2(); return b2TensorDampingController; })(b2Controller); var b2RopeDef = (function() { function b2RopeDef() { this.vertices = []; this.count = 0; this.masses = []; this.gravity = new b2Vec2(0, 0); this.damping = .1; this.k2 = .9; this.k3 = .1; } return b2RopeDef; })(); var b2Rope = (function() { function b2Rope() { this.m_count = 0; this.m_ps = []; this.m_p0s = []; this.m_vs = []; this.m_ims = []; this.m_Ls = []; this.m_as = []; this.m_gravity = new b2Vec2(); this.m_damping = 0; this.m_k2 = 1; this.m_k3 = .1; } b2Rope.prototype.GetVertexCount = function() { return this.m_count; }; b2Rope.prototype.GetVertices = function() { return this.m_ps; }; b2Rope.prototype.Initialize = function(def) { this.m_count = def.count; this.m_ps = b2Vec2.MakeArray(this.m_count); this.m_p0s = b2Vec2.MakeArray(this.m_count); this.m_vs = b2Vec2.MakeArray(this.m_count); this.m_ims = b2MakeNumberArray(this.m_count); for (var i = 0; i < this.m_count; ++i) { this.m_ps[i].Copy(def.vertices[i]); this.m_p0s[i].Copy(def.vertices[i]); this.m_vs[i].SetZero(); var m = def.masses[i]; this.m_ims[i] = m > 0 ? 1 / m : 0; } var count2 = this.m_count - 1; var count3 = this.m_count - 2; this.m_Ls = b2MakeNumberArray(count2); this.m_as = b2MakeNumberArray(count3); for (var i = 0; i < count2; ++i) { var p1 = this.m_ps[i]; var p2 = this.m_ps[i + 1]; this.m_Ls[i] = b2Vec2.DistanceVV(p1, p2); } for (var i = 0; i < count3; ++i) { var p1 = this.m_ps[i]; var p2 = this.m_ps[i + 1]; var p3 = this.m_ps[i + 2]; var d1 = b2Vec2.SubVV(p2, p1, b2Vec2.s_t0); var d2 = b2Vec2.SubVV(p3, p2, b2Vec2.s_t1); var a = b2Vec2.CrossVV(d1, d2); var b = b2Vec2.DotVV(d1, d2); this.m_as[i] = b2Atan2(a, b); } this.m_gravity.Copy(def.gravity); this.m_damping = def.damping; this.m_k2 = def.k2; this.m_k3 = def.k3; }; b2Rope.prototype.Step = function(h, iterations) { if (0 === h) return; var d = Math.exp(-h * this.m_damping); for (var i = 0; i < this.m_count; ++i) { this.m_p0s[i].Copy(this.m_ps[i]); this.m_ims[i] > 0 && this.m_vs[i].SelfMulAdd(h, this.m_gravity); this.m_vs[i].SelfMul(d); this.m_ps[i].SelfMulAdd(h, this.m_vs[i]); } for (var i = 0; i < iterations; ++i) { this.SolveC2(); this.SolveC3(); this.SolveC2(); } var inv_h = 1 / h; for (var i = 0; i < this.m_count; ++i) b2Vec2.MulSV(inv_h, b2Vec2.SubVV(this.m_ps[i], this.m_p0s[i], b2Vec2.s_t0), this.m_vs[i]); }; b2Rope.prototype.SolveC2 = function() { var count2 = this.m_count - 1; for (var i = 0; i < count2; ++i) { var p1 = this.m_ps[i]; var p2 = this.m_ps[i + 1]; var d = b2Vec2.SubVV(p2, p1, b2Rope.s_d); var L = d.Normalize(); var im1 = this.m_ims[i]; var im2 = this.m_ims[i + 1]; if (im1 + im2 === 0) continue; var s1 = im1 / (im1 + im2); var s2 = im2 / (im1 + im2); p1.SelfMulSub(this.m_k2 * s1 * (this.m_Ls[i] - L), d); p2.SelfMulAdd(this.m_k2 * s2 * (this.m_Ls[i] - L), d); } }; b2Rope.prototype.SetAngle = function(angle) { var count3 = this.m_count - 2; for (var i = 0; i < count3; ++i) this.m_as[i] = angle; }; b2Rope.prototype.SolveC3 = function() { var count3 = this.m_count - 2; for (var i = 0; i < count3; ++i) { var p1 = this.m_ps[i]; var p2 = this.m_ps[i + 1]; var p3 = this.m_ps[i + 2]; var m1 = this.m_ims[i]; var m2 = this.m_ims[i + 1]; var m3 = this.m_ims[i + 2]; var d1 = b2Vec2.SubVV(p2, p1, b2Rope.s_d1); var d2 = b2Vec2.SubVV(p3, p2, b2Rope.s_d2); var L1sqr = d1.LengthSquared(); var L2sqr = d2.LengthSquared(); if (L1sqr * L2sqr === 0) continue; var a = b2Vec2.CrossVV(d1, d2); var b = b2Vec2.DotVV(d1, d2); var angle = b2Atan2(a, b); var Jd1 = b2Vec2.MulSV(-1 / L1sqr, d1.SelfSkew(), b2Rope.s_Jd1); var Jd2 = b2Vec2.MulSV(1 / L2sqr, d2.SelfSkew(), b2Rope.s_Jd2); var J1 = b2Vec2.NegV(Jd1, b2Rope.s_J1); var J2 = b2Vec2.SubVV(Jd1, Jd2, b2Rope.s_J2); var J3 = Jd2; var mass = m1 * b2Vec2.DotVV(J1, J1) + m2 * b2Vec2.DotVV(J2, J2) + m3 * b2Vec2.DotVV(J3, J3); if (0 === mass) continue; mass = 1 / mass; var C = angle - this.m_as[i]; while (C > b2_pi) { angle -= 2 * b2_pi; C = angle - this.m_as[i]; } while (C < -b2_pi) { angle += 2 * b2_pi; C = angle - this.m_as[i]; } var impulse = -this.m_k3 * mass * C; p1.SelfMulAdd(m1 * impulse, J1); p2.SelfMulAdd(m2 * impulse, J2); p3.SelfMulAdd(m3 * impulse, J3); } }; b2Rope.prototype.Draw = function(draw) { var c = new b2Color(.4, .5, .7); for (var i = 0; i < this.m_count - 1; ++i) draw.DrawSegment(this.m_ps[i], this.m_ps[i + 1], c); }; b2Rope.s_d = new b2Vec2(); b2Rope.s_d1 = new b2Vec2(); b2Rope.s_d2 = new b2Vec2(); b2Rope.s_Jd1 = new b2Vec2(); b2Rope.s_Jd2 = new b2Vec2(); b2Rope.s_J1 = new b2Vec2(); b2Rope.s_J2 = new b2Vec2(); return b2Rope; })(); exports.b2Assert = b2Assert; exports.b2Maybe = b2Maybe; exports.b2_maxFloat = b2_maxFloat; exports.b2_epsilon = b2_epsilon; exports.b2_epsilon_sq = b2_epsilon_sq; exports.b2_pi = b2_pi; exports.b2_maxManifoldPoints = b2_maxManifoldPoints; exports.b2_maxPolygonVertices = b2_maxPolygonVertices; exports.b2_aabbExtension = b2_aabbExtension; exports.b2_aabbMultiplier = b2_aabbMultiplier; exports.b2_linearSlop = b2_linearSlop; exports.b2_angularSlop = b2_angularSlop; exports.b2_polygonRadius = b2_polygonRadius; exports.b2_maxSubSteps = b2_maxSubSteps; exports.b2_maxTOIContacts = b2_maxTOIContacts; exports.b2_velocityThreshold = b2_velocityThreshold; exports.b2_maxLinearCorrection = b2_maxLinearCorrection; exports.b2_maxAngularCorrection = b2_maxAngularCorrection; exports.b2_maxTranslation = b2_maxTranslation; exports.b2_maxTranslationSquared = b2_maxTranslationSquared; exports.b2_maxRotation = b2_maxRotation; exports.b2_maxRotationSquared = b2_maxRotationSquared; exports.b2_baumgarte = b2_baumgarte; exports.b2_toiBaumgarte = b2_toiBaumgarte; exports.b2_invalidParticleIndex = b2_invalidParticleIndex; exports.b2_maxParticleIndex = b2_maxParticleIndex; exports.b2_particleStride = b2_particleStride; exports.b2_minParticleWeight = b2_minParticleWeight; exports.b2_maxParticlePressure = b2_maxParticlePressure; exports.b2_maxParticleForce = b2_maxParticleForce; exports.b2_maxTriadDistance = b2_maxTriadDistance; exports.b2_maxTriadDistanceSquared = b2_maxTriadDistanceSquared; exports.b2_minParticleSystemBufferCapacity = b2_minParticleSystemBufferCapacity; exports.b2_barrierCollisionTime = b2_barrierCollisionTime; exports.b2_timeToSleep = b2_timeToSleep; exports.b2_linearSleepTolerance = b2_linearSleepTolerance; exports.b2_angularSleepTolerance = b2_angularSleepTolerance; exports.b2Alloc = b2Alloc; exports.b2Free = b2Free; exports.b2Log = b2Log; exports.b2Version = b2Version; exports.b2_version = b2_version; exports.b2_branch = b2_branch; exports.b2_commit = b2_commit; exports.b2ParseInt = b2ParseInt; exports.b2ParseUInt = b2ParseUInt; exports.b2MakeArray = b2MakeArray; exports.b2MakeNullArray = b2MakeNullArray; exports.b2MakeNumberArray = b2MakeNumberArray; exports.b2_pi_over_180 = b2_pi_over_180; exports.b2_180_over_pi = b2_180_over_pi; exports.b2_two_pi = b2_two_pi; exports.b2Abs = b2Abs; exports.b2Min = b2Min; exports.b2Max = b2Max; exports.b2Clamp = b2Clamp; exports.b2Swap = b2Swap; exports.b2IsValid = b2IsValid; exports.b2Sq = b2Sq; exports.b2InvSqrt = b2InvSqrt; exports.b2Sqrt = b2Sqrt; exports.b2Pow = b2Pow; exports.b2DegToRad = b2DegToRad; exports.b2RadToDeg = b2RadToDeg; exports.b2Cos = b2Cos; exports.b2Sin = b2Sin; exports.b2Acos = b2Acos; exports.b2Asin = b2Asin; exports.b2Atan2 = b2Atan2; exports.b2NextPowerOfTwo = b2NextPowerOfTwo; exports.b2IsPowerOfTwo = b2IsPowerOfTwo; exports.b2Random = b2Random; exports.b2RandomRange = b2RandomRange; exports.b2Vec2 = b2Vec2; exports.b2Vec2_zero = b2Vec2_zero; exports.b2Vec3 = b2Vec3; exports.b2Mat22 = b2Mat22; exports.b2Mat33 = b2Mat33; exports.b2Rot = b2Rot; exports.b2Transform = b2Transform; exports.b2Sweep = b2Sweep; exports.b2Color = b2Color; exports.b2Draw = b2Draw; exports.b2Timer = b2Timer; exports.b2Counter = b2Counter; exports.b2GrowableStack = b2GrowableStack; exports.b2BlockAllocator = b2BlockAllocator; exports.b2StackAllocator = b2StackAllocator; exports.b2ContactFeature = b2ContactFeature; exports.b2ContactID = b2ContactID; exports.b2ManifoldPoint = b2ManifoldPoint; exports.b2Manifold = b2Manifold; exports.b2WorldManifold = b2WorldManifold; exports.b2GetPointStates = b2GetPointStates; exports.b2ClipVertex = b2ClipVertex; exports.b2RayCastInput = b2RayCastInput; exports.b2RayCastOutput = b2RayCastOutput; exports.b2AABB = b2AABB; exports.b2TestOverlapAABB = b2TestOverlapAABB; exports.b2ClipSegmentToLine = b2ClipSegmentToLine; exports.b2TestOverlapShape = b2TestOverlapShape; exports.b2DistanceProxy = b2DistanceProxy; exports.b2SimplexCache = b2SimplexCache; exports.b2DistanceInput = b2DistanceInput; exports.b2DistanceOutput = b2DistanceOutput; exports.b2ShapeCastInput = b2ShapeCastInput; exports.b2ShapeCastOutput = b2ShapeCastOutput; exports.b2_gjk_reset = b2_gjk_reset; exports.b2SimplexVertex = b2SimplexVertex; exports.b2Simplex = b2Simplex; exports.b2Distance = b2Distance; exports.b2ShapeCast = b2ShapeCast; exports.b2Pair = b2Pair; exports.b2BroadPhase = b2BroadPhase; exports.b2PairLessThan = b2PairLessThan; exports.b2TreeNode = b2TreeNode; exports.b2DynamicTree = b2DynamicTree; exports.b2_toi_reset = b2_toi_reset; exports.b2TOIInput = b2TOIInput; exports.b2TOIOutput = b2TOIOutput; exports.b2SeparationFunction = b2SeparationFunction; exports.b2TimeOfImpact = b2TimeOfImpact; exports.b2CollideCircles = b2CollideCircles; exports.b2CollidePolygonAndCircle = b2CollidePolygonAndCircle; exports.b2CollidePolygons = b2CollidePolygons; exports.b2CollideEdgeAndCircle = b2CollideEdgeAndCircle; exports.b2CollideEdgeAndPolygon = b2CollideEdgeAndPolygon; exports.b2MassData = b2MassData; exports.b2Shape = b2Shape; exports.b2CircleShape = b2CircleShape; exports.b2PolygonShape = b2PolygonShape; exports.b2EdgeShape = b2EdgeShape; exports.b2ChainShape = b2ChainShape; exports.b2Filter = b2Filter; exports.b2FixtureDef = b2FixtureDef; exports.b2FixtureProxy = b2FixtureProxy; exports.b2Fixture = b2Fixture; exports.b2BodyDef = b2BodyDef; exports.b2Body = b2Body; exports.b2World = b2World; exports.b2DestructionListener = b2DestructionListener; exports.b2ContactFilter = b2ContactFilter; exports.b2ContactImpulse = b2ContactImpulse; exports.b2ContactListener = b2ContactListener; exports.b2QueryCallback = b2QueryCallback; exports.b2RayCastCallback = b2RayCastCallback; exports.b2Island = b2Island; exports.b2Profile = b2Profile; exports.b2TimeStep = b2TimeStep; exports.b2Position = b2Position; exports.b2Velocity = b2Velocity; exports.b2SolverData = b2SolverData; exports.b2ContactManager = b2ContactManager; exports.b2MixFriction = b2MixFriction; exports.b2MixRestitution = b2MixRestitution; exports.b2ContactEdge = b2ContactEdge; exports.b2Contact = b2Contact; exports.b2ContactRegister = b2ContactRegister; exports.b2ContactFactory = b2ContactFactory; exports.g_blockSolve = g_blockSolve; exports.b2VelocityConstraintPoint = b2VelocityConstraintPoint; exports.b2ContactVelocityConstraint = b2ContactVelocityConstraint; exports.b2ContactPositionConstraint = b2ContactPositionConstraint; exports.b2ContactSolverDef = b2ContactSolverDef; exports.b2PositionSolverManifold = b2PositionSolverManifold; exports.b2ContactSolver = b2ContactSolver; exports.b2CircleContact = b2CircleContact; exports.b2PolygonContact = b2PolygonContact; exports.b2PolygonAndCircleContact = b2PolygonAndCircleContact; exports.b2EdgeAndCircleContact = b2EdgeAndCircleContact; exports.b2EdgeAndPolygonContact = b2EdgeAndPolygonContact; exports.b2ChainAndCircleContact = b2ChainAndCircleContact; exports.b2ChainAndPolygonContact = b2ChainAndPolygonContact; exports.b2Jacobian = b2Jacobian; exports.b2JointEdge = b2JointEdge; exports.b2JointDef = b2JointDef; exports.b2Joint = b2Joint; exports.b2AreaJointDef = b2AreaJointDef; exports.b2AreaJoint = b2AreaJoint; exports.b2DistanceJointDef = b2DistanceJointDef; exports.b2DistanceJoint = b2DistanceJoint; exports.b2FrictionJointDef = b2FrictionJointDef; exports.b2FrictionJoint = b2FrictionJoint; exports.b2GearJointDef = b2GearJointDef; exports.b2GearJoint = b2GearJoint; exports.b2MotorJointDef = b2MotorJointDef; exports.b2MotorJoint = b2MotorJoint; exports.b2MouseJointDef = b2MouseJointDef; exports.b2MouseJoint = b2MouseJoint; exports.b2PrismaticJointDef = b2PrismaticJointDef; exports.b2PrismaticJoint = b2PrismaticJoint; exports.b2_minPulleyLength = b2_minPulleyLength; exports.b2PulleyJointDef = b2PulleyJointDef; exports.b2PulleyJoint = b2PulleyJoint; exports.b2RevoluteJointDef = b2RevoluteJointDef; exports.b2RevoluteJoint = b2RevoluteJoint; exports.b2RopeJointDef = b2RopeJointDef; exports.b2RopeJoint = b2RopeJoint; exports.b2WeldJointDef = b2WeldJointDef; exports.b2WeldJoint = b2WeldJoint; exports.b2WheelJointDef = b2WheelJointDef; exports.b2WheelJoint = b2WheelJoint; exports.b2ControllerEdge = b2ControllerEdge; exports.b2Controller = b2Controller; exports.b2BuoyancyController = b2BuoyancyController; exports.b2ConstantAccelController = b2ConstantAccelController; exports.b2ConstantForceController = b2ConstantForceController; exports.b2GravityController = b2GravityController; exports.b2TensorDampingController = b2TensorDampingController; exports.b2ParticleDef = b2ParticleDef; exports.b2CalculateParticleIterations = b2CalculateParticleIterations; exports.b2ParticleHandle = b2ParticleHandle; exports.b2ParticleGroupDef = b2ParticleGroupDef; exports.b2ParticleGroup = b2ParticleGroup; exports.b2GrowableBuffer = b2GrowableBuffer; exports.b2FixtureParticleQueryCallback = b2FixtureParticleQueryCallback; exports.b2ParticleContact = b2ParticleContact; exports.b2ParticleBodyContact = b2ParticleBodyContact; exports.b2ParticlePair = b2ParticlePair; exports.b2ParticleTriad = b2ParticleTriad; exports.b2ParticleSystemDef = b2ParticleSystemDef; exports.b2RopeDef = b2RopeDef; exports.b2Rope = b2Rope; Object.defineProperty(exports, "__esModule", { value: true }); })); }), {} ], 296: [ (function(require, module, exports) { var _global = "undefined" === (__typeofVal = typeof window, "object" === __typeofVal ? __realTypeOfObj(window) : __typeofVal) ? global : window; _global.cc = _global.cc || {}; _global._cc = _global._cc || {}; require("./predefine"); require("./polyfill/string"); require("./polyfill/misc"); require("./polyfill/array"); require("./polyfill/object"); require("./polyfill/array-buffer"); true; require("./polyfill/typescript"); require("./cocos2d/core/predefine"); true; require("./cocos2d"); require("./extends"); false; module.exports = _global.cc; }), { "./cocos2d": 262, "./cocos2d/core/predefine": 186, "./extends": 282, "./package": void 0, "./polyfill/array": 298, "./polyfill/array-buffer": 297, "./polyfill/misc": 299, "./polyfill/object": 300, "./polyfill/string": 301, "./polyfill/typescript": 302, "./predefine": 303 } ], 297: [ (function(require, module, exports) { ArrayBuffer.isView || (function() { var ArrayBufferView = Object.getPrototypeOf(Object.getPrototypeOf(new Uint8Array())).constructor; ArrayBuffer.isView = function(view) { return view instanceof ArrayBufferView; }; })(); }), {} ], 298: [ (function(require, module, exports) { Array.isArray || (Array.isArray = function(arg) { return "[object Array]" === Object.prototype.toString.call(arg); }); }), {} ], 299: [ (function(require, module, exports) { Math.sign || (Math.sign = function(x) { x = +x; if (0 === x || isNaN(x)) return x; return x > 0 ? 1 : -1; }); Number.isInteger || (Number.isInteger = function(value) { return "number" === (__typeofVal = typeof value, "object" === __typeofVal ? __realTypeOfObj(value) : __typeofVal) && isFinite(value) && Math.floor(value) === value; }); true; 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"); }; }), {} ], 300: [ (function(require, module, exports) { Object.assign || (Object.assign = function(target, source) { cc.js.mixin(target, source); }); Object.getOwnPropertyDescriptors || (Object.getOwnPropertyDescriptors = function(obj) { var descriptors = {}; var ownKeys = Object.getOwnPropertyNames(obj).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) { 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" === (__typeofVal = typeof position, "object" === __typeofVal ? __realTypeOfObj(position) : __typeofVal) || position > this.length) && (position = this.length); position -= searchString.length; var lastIndex = this.indexOf(searchString, position); return -1 !== lastIndex && lastIndex === position; }); }), {} ], 302: [ (function(require, module, exports) { 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" === (__typeofVal = typeof Object.getOwnPropertySymbols, "object" === __typeofVal ? __realTypeOfObj(Object.getOwnPropertySymbols) : __typeofVal)) for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) e.indexOf(p[i]) < 0 && (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" === (__typeofVal = typeof Reflect, "object" === __typeofVal ? __realTypeOfObj(Reflect) : __typeofVal) && "function" === (__typeofVal = typeof Reflect.decorate, "object" === __typeofVal ? __realTypeOfObj(Reflect.decorate) : __typeofVal)) 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" === (__typeofVal = typeof Reflect, "object" === __typeofVal ? __realTypeOfObj(Reflect) : __typeofVal) && "function" === (__typeofVal = typeof Reflect.metadata, "object" === __typeofVal ? __realTypeOfObj(Reflect.metadata) : __typeofVal)) return Reflect.metadata(metadataKey, metadataValue); }; window.__awaiter = function(thisArg, _arguments, P, generator) { 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) : new P(function(resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; window.__generator = function(thisArg, body) { var _ = { label: 0, sent: function() { 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" === (__typeofVal = typeof Symbol, "object" === __typeofVal ? __realTypeOfObj(Symbol) : __typeofVal) && (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 = y[2 & op[0] ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; (y = 0, t) && (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, exports) { for (var p in m) exports.hasOwnProperty(p) || (exports[p] = m[p]); }; window.__values = function(o) { var m = "function" === (__typeofVal = typeof Symbol, "object" === __typeofVal ? __realTypeOfObj(Symbol) : __typeofVal) && o[Symbol.iterator], i = 0; if (m) return m.call(o); return { next: function() { o && i >= o.length && (o = void 0); return { value: o && o[i++], done: !o }; } }; }; window.__read = function(o, n) { var m = "function" === (__typeofVal = typeof Symbol, "object" === __typeofVal ? __realTypeOfObj(Symbol) : __typeofVal) && 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.__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) { o[n] && (i[n] = function(v) { return (p = !p) ? { value: __await(o[n](v)), done: "return" === n } : f ? f(v) : v; }); } }; window.__asyncValues = function(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator]; return m ? m.call(o) : "function" === (__typeofVal = typeof __values, "object" === __typeofVal ? __realTypeOfObj(__values) : __typeofVal) ? __values(o) : o[Symbol.iterator](); }; }), {} ], 303: [ (function(require, module, exports) { var _global = "undefined" === (__typeofVal = typeof window, "object" === __typeofVal ? __realTypeOfObj(window) : __typeofVal) ? global : window; function defineMacro(name, defaultValue) { "undefined" === (__typeofVal = typeof _global[name], "object" === __typeofVal ? __realTypeOfObj(_global[name]) : __typeofVal) && (_global[name] = defaultValue); } function defined(name) { return "object" === (__typeofVal = typeof _global[name], "object" === __typeofVal ? __realTypeOfObj(_global[name]) : __typeofVal); } defineMacro("CC_BUILD", false); true; _global.CC_BUILD = true; _global.CC_TEST = false; _global.CC_EDITOR = false; _global.CC_PREVIEW = false; _global.CC_DEV = false; _global.CC_DEBUG = true; _global.CC_JSB = true; _global.CC_WECHATGAMESUB = false; _global.CC_WECHATGAME = false; _global.CC_QQPLAY = false; _global.CC_RUNTIME = false; _global.CC_SUPPORT_JIT = true; _global.CC_QQGAME = false; false; var engineVersion = "2.0.9"; _global["CocosEngine"] = cc.ENGINE_VERSION = engineVersion; }), {} ] }, {}, [ 296 ]); function __realTypeOfObj(obj) { if (obj && obj.toString && "[object CallbackConstructor]" === obj.toString()) return "function"; return "object"; } var __typeofVal = ""; })();