Файловый менеджер - Редактировать - /home/jogoso94/public_html/jogos/rocket_bot/main.js
�азад
(function(modules) { var parentJsonpFunction = window["webpackJsonp"]; window["webpackJsonp"] = function webpackJsonpCallback(chunkIds, moreModules, executeModules) { var moduleId, chunkId, i = 0, resolves = [], result; for (; i < chunkIds.length; i++) { chunkId = chunkIds[i]; if (installedChunks[chunkId]) { resolves.push(installedChunks[chunkId][0]) } installedChunks[chunkId] = 0 } for (moduleId in moreModules) { if (Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { modules[moduleId] = moreModules[moduleId] } } if (parentJsonpFunction) parentJsonpFunction(chunkIds, moreModules, executeModules); while (resolves.length) { resolves.shift()() } if (executeModules) { for (i = 0; i < executeModules.length; i++) { result = __webpack_require__(__webpack_require__.s = executeModules[i]) } } return result }; var installedModules = {}; var installedChunks = { 1: 0 }; function __webpack_require__(moduleId) { if (installedModules[moduleId]) { return installedModules[moduleId].exports } var module = installedModules[moduleId] = { i: moduleId, l: false, exports: {} }; modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); module.l = true; return module.exports } __webpack_require__.m = modules; __webpack_require__.c = installedModules; __webpack_require__.d = function(exports, name, getter) { if (!__webpack_require__.o(exports, name)) { Object.defineProperty(exports, name, { configurable: false, enumerable: true, get: getter }) } }; __webpack_require__.n = function(module) { var getter = module && module.__esModule ? function getDefault() { return module["default"] } : function getModuleExports() { return module }; __webpack_require__.d(getter, "a", getter); return getter }; __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property) }; __webpack_require__.p = ""; __webpack_require__.oe = function(err) { console.error(err); throw err }; return __webpack_require__(__webpack_require__.s = 1172) })([function(module, exports) { function hasGetterOrSetter(def) { return !!def.get && typeof def.get === "function" || !!def.set && typeof def.set === "function" } function getProperty(definition, k, isClassDescriptor) { var def = isClassDescriptor ? definition[k] : Object.getOwnPropertyDescriptor(definition, k); if (!isClassDescriptor && def.value && typeof def.value === "object") { def = def.value } if (def && hasGetterOrSetter(def)) { if (typeof def.enumerable === "undefined") { def.enumerable = true } if (typeof def.configurable === "undefined") { def.configurable = true } return def } else { return false } } function hasNonConfigurable(obj, k) { var prop = Object.getOwnPropertyDescriptor(obj, k); if (!prop) { return false } if (prop.value && typeof prop.value === "object") { prop = prop.value } if (prop.configurable === false) { return true } return false } function extend(ctor, definition, isClassDescriptor, extend) { for (var k in definition) { if (!definition.hasOwnProperty(k)) { continue } var def = getProperty(definition, k, isClassDescriptor); if (def !== false) { var parent = extend || ctor; if (hasNonConfigurable(parent.prototype, k)) { if (Class.ignoreFinals) { continue } throw new Error("cannot override final property '" + k + "', set Class.ignoreFinals = true to skip") } Object.defineProperty(ctor.prototype, k, def) } else { ctor.prototype[k] = definition[k] } } } function mixin(myClass, mixins) { if (!mixins) { return } if (!Array.isArray(mixins)) { mixins = [mixins] } for (var i = 0; i < mixins.length; i++) { extend(myClass, mixins[i].prototype || mixins[i]) } } function Class(definition) { if (!definition) { definition = {} } var initialize; var Extends; if (definition.initialize) { if (typeof definition.initialize !== "function") { throw new Error("initialize must be a function") } initialize = definition.initialize; delete definition.initialize } else if (definition.Extends) { var base = definition.Extends; initialize = function() { base.apply(this, arguments) } } else { initialize = function() {} } if (definition.Extends) { initialize.prototype = Object.create(definition.Extends.prototype); initialize.prototype.constructor = initialize; Extends = definition.Extends; delete definition.Extends } else { initialize.prototype.constructor = initialize } var mixins = null; if (definition.Mixins) { mixins = definition.Mixins; delete definition.Mixins } mixin(initialize, mixins); extend(initialize, definition, true, Extends); return initialize } Class.extend = extend; Class.mixin = mixin; Class.ignoreFinals = false; module.exports = Class }, function(module, exports) { var GetFastValue = function(source, key, defaultValue) { var t = typeof source; if (!source || t === "number" || t === "string") { return defaultValue } else if (source.hasOwnProperty(key) && source[key] !== undefined) { return source[key] } else { return defaultValue } }; module.exports = GetFastValue }, function(module, exports) { var NOOP = function() {}; module.exports = NOOP }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Vector2 = new Class({ initialize: function Vector2(x, y) { this.x = 0; this.y = 0; if (typeof x === "object") { this.x = x.x || 0; this.y = x.y || 0 } else { if (y === undefined) { y = x } this.x = x || 0; this.y = y || 0 } }, clone: function() { return new Vector2(this.x, this.y) }, copy: function(src) { this.x = src.x || 0; this.y = src.y || 0; return this }, setFromObject: function(obj) { this.x = obj.x || 0; this.y = obj.y || 0; return this }, set: function(x, y) { if (y === undefined) { y = x } this.x = x; this.y = y; return this }, setTo: function(x, y) { return this.set(x, y) }, setToPolar: function(azimuth, radius) { if (radius == null) { radius = 1 } this.x = Math.cos(azimuth) * radius; this.y = Math.sin(azimuth) * radius; return this }, equals: function(v) { return this.x === v.x && this.y === v.y }, angle: function() { var angle = Math.atan2(this.y, this.x); if (angle < 0) { angle += 2 * Math.PI } return angle }, add: function(src) { this.x += src.x; this.y += src.y; return this }, subtract: function(src) { this.x -= src.x; this.y -= src.y; return this }, multiply: function(src) { this.x *= src.x; this.y *= src.y; return this }, scale: function(value) { if (isFinite(value)) { this.x *= value; this.y *= value } else { this.x = 0; this.y = 0 } return this }, divide: function(src) { this.x /= src.x; this.y /= src.y; return this }, negate: function() { this.x = -this.x; this.y = -this.y; return this }, distance: function(src) { var dx = src.x - this.x; var dy = src.y - this.y; return Math.sqrt(dx * dx + dy * dy) }, distanceSq: function(src) { var dx = src.x - this.x; var dy = src.y - this.y; return dx * dx + dy * dy }, length: function() { var x = this.x; var y = this.y; return Math.sqrt(x * x + y * y) }, lengthSq: function() { var x = this.x; var y = this.y; return x * x + y * y }, normalize: function() { var x = this.x; var y = this.y; var len = x * x + y * y; if (len > 0) { len = 1 / Math.sqrt(len); this.x = x * len; this.y = y * len } return this }, normalizeRightHand: function() { var x = this.x; this.x = this.y * -1; this.y = x; return this }, dot: function(src) { return this.x * src.x + this.y * src.y }, cross: function(src) { return this.x * src.y - this.y * src.x }, lerp: function(src, t) { if (t === undefined) { t = 0 } var ax = this.x; var ay = this.y; this.x = ax + t * (src.x - ax); this.y = ay + t * (src.y - ay); return this }, transformMat3: function(mat) { var x = this.x; var y = this.y; var m = mat.val; this.x = m[0] * x + m[3] * y + m[6]; this.y = m[1] * x + m[4] * y + m[7]; return this }, transformMat4: function(mat) { var x = this.x; var y = this.y; var m = mat.val; this.x = m[0] * x + m[4] * y + m[12]; this.y = m[1] * x + m[5] * y + m[13]; return this }, reset: function() { this.x = 0; this.y = 0; return this } }); Vector2.ZERO = new Vector2; module.exports = Vector2 }, function(module, exports) { var GetValue = function(source, key, defaultValue) { if (!source || typeof source === "number") { return defaultValue } else if (source.hasOwnProperty(key)) { return source[key] } else if (key.indexOf(".")) { var keys = key.split("."); var parent = source; var value = defaultValue; for (var i = 0; i < keys.length; i++) { if (parent.hasOwnProperty(keys[i])) { value = parent[keys[i]]; parent = parent[keys[i]] } else { value = defaultValue; break } } return value } else { return defaultValue } }; module.exports = GetValue }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var PluginCache = __webpack_require__(15); var GameObjectFactory = new Class({ initialize: function GameObjectFactory(scene) { this.scene = scene; this.systems = scene.sys; this.displayList; this.updateList; scene.sys.events.once("boot", this.boot, this); scene.sys.events.on("start", this.start, this) }, boot: function() { this.displayList = this.systems.displayList; this.updateList = this.systems.updateList; this.systems.events.once("destroy", this.destroy, this) }, start: function() { this.systems.events.once("shutdown", this.shutdown, this) }, existing: function(child) { if (child.renderCanvas || child.renderWebGL) { this.displayList.add(child) } if (child.preUpdate) { this.updateList.add(child) } return child }, shutdown: function() { this.systems.events.off("shutdown", this.shutdown, this) }, destroy: function() { this.shutdown(); this.scene.sys.events.off("start", this.start, this); this.scene = null; this.systems = null; this.displayList = null; this.updateList = null } }); GameObjectFactory.register = function(factoryType, factoryFunction) { if (!GameObjectFactory.prototype.hasOwnProperty(factoryType)) { GameObjectFactory.prototype[factoryType] = factoryFunction } }; PluginCache.register("GameObjectFactory", GameObjectFactory, "add"); module.exports = GameObjectFactory }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Point = new Class({ initialize: function Point(x, y) { if (x === undefined) { x = 0 } if (y === undefined) { y = x } this.x = x; this.y = y }, setTo: function(x, y) { if (x === undefined) { x = 0 } if (y === undefined) { y = x } this.x = x; this.y = y; return this } }); module.exports = Point }, function(module, exports) { var IsPlainObject = function(obj) { if (typeof obj !== "object" || obj.nodeType || obj === obj.window) { return false } try { if (obj.constructor && !{}.hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf")) { return false } } catch (e) { return false } return true }; module.exports = IsPlainObject }, function(module, exports) { var types = {}; var FileTypesManager = { install: function(loader) { for (var key in types) { loader[key] = types[key] } }, register: function(key, factoryFunction) { types[key] = factoryFunction }, destroy: function() { types = {} } }; module.exports = FileTypesManager }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Contains = __webpack_require__(47); var GetPoint = __webpack_require__(146); var GetPoints = __webpack_require__(245); var Line = __webpack_require__(54); var Random = __webpack_require__(149); var Rectangle = new Class({ initialize: function Rectangle(x, y, width, height) { if (x === undefined) { x = 0 } if (y === undefined) { y = 0 } if (width === undefined) { width = 0 } if (height === undefined) { height = 0 } this.x = x; this.y = y; this.width = width; this.height = height }, contains: function(x, y) { return Contains(this, x, y) }, getPoint: function(position, output) { return GetPoint(this, position, output) }, getPoints: function(quantity, stepRate, output) { return GetPoints(this, quantity, stepRate, output) }, getRandomPoint: function(point) { return Random(this, point) }, setTo: function(x, y, width, height) { this.x = x; this.y = y; this.width = width; this.height = height; return this }, setEmpty: function() { return this.setTo(0, 0, 0, 0) }, setPosition: function(x, y) { if (y === undefined) { y = x } this.x = x; this.y = y; return this }, setSize: function(width, height) { if (height === undefined) { height = width } this.width = width; this.height = height; return this }, isEmpty: function() { return this.width <= 0 || this.height <= 0 }, getLineA: function(line) { if (line === undefined) { line = new Line } line.setTo(this.x, this.y, this.right, this.y); return line }, getLineB: function(line) { if (line === undefined) { line = new Line } line.setTo(this.right, this.y, this.right, this.bottom); return line }, getLineC: function(line) { if (line === undefined) { line = new Line } line.setTo(this.right, this.bottom, this.x, this.bottom); return line }, getLineD: function(line) { if (line === undefined) { line = new Line } line.setTo(this.x, this.bottom, this.x, this.y); return line }, left: { get: function() { return this.x }, set: function(value) { if (value >= this.right) { this.width = 0 } else { this.width = this.right - value } this.x = value } }, right: { get: function() { return this.x + this.width }, set: function(value) { if (value <= this.x) { this.width = 0 } else { this.width = value - this.x } } }, top: { get: function() { return this.y }, set: function(value) { if (value >= this.bottom) { this.height = 0 } else { this.height = this.bottom - value } this.y = value } }, bottom: { get: function() { return this.y + this.height }, set: function(value) { if (value <= this.y) { this.height = 0 } else { this.height = value - this.y } } }, centerX: { get: function() { return this.x + this.width / 2 }, set: function(value) { this.x = value - this.width / 2 } }, centerY: { get: function() { return this.y + this.height / 2 }, set: function(value) { this.y = value - this.height / 2 } } }); module.exports = Rectangle }, function(module, exports) { module.exports = { getTintFromFloats: function(r, g, b, a) { var ur = (r * 255 | 0) & 255; var ug = (g * 255 | 0) & 255; var ub = (b * 255 | 0) & 255; var ua = (a * 255 | 0) & 255; return (ua << 24 | ur << 16 | ug << 8 | ub) >>> 0 }, getTintAppendFloatAlpha: function(rgb, a) { var ua = (a * 255 | 0) & 255; return (ua << 24 | rgb) >>> 0 }, getTintAppendFloatAlphaAndSwap: function(rgb, a) { var ur = (rgb >> 16 | 0) & 255; var ug = (rgb >> 8 | 0) & 255; var ub = (rgb | 0) & 255; var ua = (a * 255 | 0) & 255; return (ua << 24 | ub << 16 | ug << 8 | ur) >>> 0 }, getFloatsFromUintRGB: function(rgb) { var ur = (rgb >> 16 | 0) & 255; var ug = (rgb >> 8 | 0) & 255; var ub = (rgb | 0) & 255; return [ur / 255, ug / 255, ub / 255] }, getComponentCount: function(attributes, glContext) { var count = 0; for (var index = 0; index < attributes.length; ++index) { var element = attributes[index]; if (element.type === glContext.FLOAT) { count += element.size } else { count += 1 } } return count } } }, function(module, exports, __webpack_require__) { "use strict"; var has = Object.prototype.hasOwnProperty, prefix = "~"; function Events() {} if (Object.create) { Events.prototype = Object.create(null); if (!(new Events).__proto__) prefix = false } function EE(fn, context, once) { this.fn = fn; this.context = context; this.once = once || false } function addListener(emitter, event, fn, context, once) { if (typeof fn !== "function") { throw new TypeError("The listener must be a function") } var listener = new EE(fn, context || emitter, once), evt = prefix ? prefix + event : event; if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); else emitter._events[evt] = [emitter._events[evt], listener]; return emitter } function clearEvent(emitter, evt) { if (--emitter._eventsCount === 0) emitter._events = new Events; else delete emitter._events[evt] } function EventEmitter() { this._events = new Events; this._eventsCount = 0 } EventEmitter.prototype.eventNames = function eventNames() { var names = [], events, name; if (this._eventsCount === 0) return names; for (name in events = this._events) { if (has.call(events, name)) names.push(prefix ? name.slice(1) : name) } if (Object.getOwnPropertySymbols) { return names.concat(Object.getOwnPropertySymbols(events)) } return names }; EventEmitter.prototype.listeners = function listeners(event) { var evt = prefix ? prefix + event : event, handlers = this._events[evt]; if (!handlers) return []; if (handlers.fn) return [handlers.fn]; for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { ee[i] = handlers[i].fn } return ee }; EventEmitter.prototype.listenerCount = function listenerCount(event) { var evt = prefix ? prefix + event : event, listeners = this._events[evt]; if (!listeners) return 0; if (listeners.fn) return 1; return listeners.length }; EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { var evt = prefix ? prefix + event : event; if (!this._events[evt]) return false; var listeners = this._events[evt], len = arguments.length, args, i; if (listeners.fn) { if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); switch (len) { case 1: return listeners.fn.call(listeners.context), true; case 2: return listeners.fn.call(listeners.context, a1), true; case 3: return listeners.fn.call(listeners.context, a1, a2), true; case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true } for (i = 1, args = new Array(len - 1); i < len; i++) { args[i - 1] = arguments[i] } listeners.fn.apply(listeners.context, args) } else { var length = listeners.length, j; for (i = 0; i < length; i++) { if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); switch (len) { case 1: listeners[i].fn.call(listeners[i].context); break; case 2: listeners[i].fn.call(listeners[i].context, a1); break; case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; default: if (!args) for (j = 1, args = new Array(len - 1); j < len; j++) { args[j - 1] = arguments[j] } listeners[i].fn.apply(listeners[i].context, args) } } } return true }; EventEmitter.prototype.on = function on(event, fn, context) { return addListener(this, event, fn, context, false) }; EventEmitter.prototype.once = function once(event, fn, context) { return addListener(this, event, fn, context, true) }; EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { var evt = prefix ? prefix + event : event; if (!this._events[evt]) return this; if (!fn) { clearEvent(this, evt); return this } var listeners = this._events[evt]; if (listeners.fn) { if (listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context)) { clearEvent(this, evt) } } else { for (var i = 0, events = [], length = listeners.length; i < length; i++) { if (listeners[i].fn !== fn || once && !listeners[i].once || context && listeners[i].context !== context) { events.push(listeners[i]) } } if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; else clearEvent(this, evt) } return this }; EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { var evt; if (event) { evt = prefix ? prefix + event : event; if (this._events[evt]) clearEvent(this, evt) } else { this._events = new Events; this._eventsCount = 0 } return this }; EventEmitter.prototype.off = EventEmitter.prototype.removeListener; EventEmitter.prototype.addListener = EventEmitter.prototype.on; EventEmitter.prefixed = prefix; EventEmitter.EventEmitter = EventEmitter; if (true) { module.exports = EventEmitter } }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var ComponentsToJSON = __webpack_require__(252); var DataManager = __webpack_require__(91); var EventEmitter = __webpack_require__(11); var GameObject = new Class({ Extends: EventEmitter, initialize: function GameObject(scene, type) { EventEmitter.call(this); this.scene = scene; this.type = type; this.parentContainer = null; this.name = ""; this.active = true; this.tabIndex = -1; this.data = null; this.renderFlags = 15; this.cameraFilter = 0; this.input = null; this.body = null; this.ignoreDestroy = false; scene.sys.queueDepthSort() }, setActive: function(value) { this.active = value; return this }, setName: function(value) { this.name = value; return this }, setDataEnabled: function() { if (!this.data) { this.data = new DataManager(this) } return this }, setData: function(key, value) { if (!this.data) { this.data = new DataManager(this) } this.data.set(key, value); return this }, getData: function(key) { if (!this.data) { this.data = new DataManager(this) } return this.data.get(key) }, setInteractive: function(shape, callback, dropZone) { this.scene.sys.input.enable(this, shape, callback, dropZone); return this }, disableInteractive: function() { if (this.input) { this.input.enabled = false } return this }, removeInteractive: function() { this.scene.sys.input.clear(this); this.input = undefined; return this }, update: function() {}, toJSON: function() { return ComponentsToJSON(this) }, willRender: function(camera) { return !(GameObject.RENDER_MASK !== this.renderFlags || this.cameraFilter > 0 && this.cameraFilter & camera.id) }, getIndexList: function() { var child = this; var parent = this.parentContainer; var indexes = []; while (parent) { indexes.unshift(parent.getIndex(child)); child = parent; if (!parent.parentContainer) { break } else { parent = parent.parentContainer } } indexes.unshift(this.scene.sys.displayList.getIndex(child)); return indexes }, destroy: function(fromScene) { if (fromScene === undefined) { fromScene = false } if (!this.scene || this.ignoreDestroy) { return } if (this.preDestroy) { this.preDestroy.call(this) } this.emit("destroy", this); var sys = this.scene.sys; if (!fromScene) { sys.displayList.remove(this); sys.updateList.remove(this) } if (this.input) { sys.input.clear(this); this.input = undefined } if (this.data) { this.data.destroy(); this.data = undefined } if (this.body) { this.body.destroy(); this.body = undefined } if (!fromScene) { sys.queueDepthSort() } this.active = false; this.visible = false; this.scene = undefined; this.parentContainer = undefined; this.removeAllListeners() } }); GameObject.RENDER_MASK = 15; module.exports = GameObject }, function(module, exports, __webpack_require__) { var MATH = __webpack_require__(18); var GetValue = __webpack_require__(4); var GetAdvancedValue = function(source, key, defaultValue) { var value = GetValue(source, key, null); if (value === null) { return defaultValue } else if (Array.isArray(value)) { return MATH.RND.pick(value) } else if (typeof value === "object") { if (value.hasOwnProperty("randInt")) { return MATH.RND.integerInRange(value.randInt[0], value.randInt[1]) } else if (value.hasOwnProperty("randFloat")) { return MATH.RND.realInRange(value.randFloat[0], value.randFloat[1]) } } else if (typeof value === "function") { return value(key) } return value }; module.exports = GetAdvancedValue }, function(module, exports, __webpack_require__) { module.exports = { Alpha: __webpack_require__(241), Animation: __webpack_require__(242), BlendMode: __webpack_require__(243), ComputedSize: __webpack_require__(489), Crop: __webpack_require__(490), Depth: __webpack_require__(244), Flip: __webpack_require__(491), GetBounds: __webpack_require__(492), Mask: __webpack_require__(248), Origin: __webpack_require__(493), Pipeline: __webpack_require__(109), ScaleMode: __webpack_require__(494), ScrollFactor: __webpack_require__(251), Size: __webpack_require__(495), Texture: __webpack_require__(496), TextureCrop: __webpack_require__(497), Tint: __webpack_require__(498), ToJSON: __webpack_require__(252), Transform: __webpack_require__(253), TransformMatrix: __webpack_require__(48), Visible: __webpack_require__(254) } }, function(module, exports) { var corePlugins = {}; var customPlugins = {}; var PluginCache = {}; PluginCache.register = function(key, plugin, mapping, custom) { if (custom === undefined) { custom = false } corePlugins[key] = { plugin: plugin, mapping: mapping, custom: custom } }; PluginCache.registerCustom = function(key, plugin, mapping, data) { customPlugins[key] = { plugin: plugin, mapping: mapping, data: data } }; PluginCache.hasCore = function(key) { return corePlugins.hasOwnProperty(key) }; PluginCache.hasCustom = function(key) { return customPlugins.hasOwnProperty(key) }; PluginCache.getCore = function(key) { return corePlugins[key] }; PluginCache.getCustom = function(key) { return customPlugins[key] }; PluginCache.getCustomClass = function(key) { return customPlugins.hasOwnProperty(key) ? customPlugins[key].plugin : null }; PluginCache.remove = function(key) { if (corePlugins.hasOwnProperty(key)) { delete corePlugins[key] } }; PluginCache.removeCustom = function(key) { if (customPlugins.hasOwnProperty(key)) { delete customPlugins[key] } }; PluginCache.destroyCorePlugins = function() { for (var key in corePlugins) { if (corePlugins.hasOwnProperty(key)) { delete corePlugins[key] } } }; PluginCache.destroyCustomPlugins = function() { for (var key in customPlugins) { if (customPlugins.hasOwnProperty(key)) { delete customPlugins[key] } } }; module.exports = PluginCache }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var PluginCache = __webpack_require__(15); var GameObjectCreator = new Class({ initialize: function GameObjectCreator(scene) { this.scene = scene; this.systems = scene.sys; this.displayList; this.updateList; scene.sys.events.once("boot", this.boot, this); scene.sys.events.on("start", this.start, this) }, boot: function() { this.displayList = this.systems.displayList; this.updateList = this.systems.updateList; this.systems.events.once("destroy", this.destroy, this) }, start: function() { this.systems.events.once("shutdown", this.shutdown, this) }, shutdown: function() { this.systems.events.off("shutdown", this.shutdown, this) }, destroy: function() { this.shutdown(); this.scene.sys.events.off("start", this.start, this); this.scene = null; this.systems = null; this.displayList = null; this.updateList = null } }); GameObjectCreator.register = function(factoryType, factoryFunction) { if (!GameObjectCreator.prototype.hasOwnProperty(factoryType)) { GameObjectCreator.prototype[factoryType] = factoryFunction } }; PluginCache.register("GameObjectCreator", GameObjectCreator, "make"); module.exports = GameObjectCreator }, function(module, exports, __webpack_require__) { (function(global) { var Common = {}; module.exports = Common; (function() { Common._nextId = 0; Common._seed = 0; Common._nowStartTime = +new Date; Common.extend = function(obj, deep) { var argsStart, args, deepClone; if (typeof deep === "boolean") { argsStart = 2; deepClone = deep } else { argsStart = 1; deepClone = true } for (var i = argsStart; i < arguments.length; i++) { var source = arguments[i]; if (source) { for (var prop in source) { if (deepClone && source[prop] && source[prop].constructor === Object) { if (!obj[prop] || obj[prop].constructor === Object) { obj[prop] = obj[prop] || {}; Common.extend(obj[prop], deepClone, source[prop]) } else { obj[prop] = source[prop] } } else { obj[prop] = source[prop] } } } } return obj }; Common.clone = function(obj, deep) { return Common.extend({}, deep, obj) }; Common.keys = function(obj) { if (Object.keys) return Object.keys(obj); var keys = []; for (var key in obj) keys.push(key); return keys }; Common.values = function(obj) { var values = []; if (Object.keys) { var keys = Object.keys(obj); for (var i = 0; i < keys.length; i++) { values.push(obj[keys[i]]) } return values } for (var key in obj) values.push(obj[key]); return values }; Common.get = function(obj, path, begin, end) { path = path.split(".").slice(begin, end); for (var i = 0; i < path.length; i += 1) { obj = obj[path[i]] } return obj }; Common.set = function(obj, path, val, begin, end) { var parts = path.split(".").slice(begin, end); Common.get(obj, path, 0, -1)[parts[parts.length - 1]] = val; return val }; Common.shuffle = function(array) { for (var i = array.length - 1; i > 0; i--) { var j = Math.floor(Common.random() * (i + 1)); var temp = array[i]; array[i] = array[j]; array[j] = temp } return array }; Common.choose = function(choices) { return choices[Math.floor(Common.random() * choices.length)] }; Common.isElement = function(obj) { if (typeof HTMLElement !== "undefined") { return obj instanceof HTMLElement } return !!(obj && obj.nodeType && obj.nodeName) }; Common.isArray = function(obj) { return Object.prototype.toString.call(obj) === "[object Array]" }; Common.isFunction = function(obj) { return typeof obj === "function" }; Common.isPlainObject = function(obj) { return typeof obj === "object" && obj.constructor === Object }; Common.isString = function(obj) { return toString.call(obj) === "[object String]" }; Common.clamp = function(value, min, max) { if (value < min) return min; if (value > max) return max; return value }; Common.sign = function(value) { return value < 0 ? -1 : 1 }; Common.now = function() { if (window.performance) { if (window.performance.now) { return window.performance.now() } else if (window.performance.webkitNow) { return window.performance.webkitNow() } } return new Date - Common._nowStartTime }; Common.random = function(min, max) { min = typeof min !== "undefined" ? min : 0; max = typeof max !== "undefined" ? max : 1; return min + _seededRandom() * (max - min) }; var _seededRandom = function() { Common._seed = (Common._seed * 9301 + 49297) % 233280; return Common._seed / 233280 }; Common.colorToNumber = function(colorString) { colorString = colorString.replace("#", ""); if (colorString.length == 3) { colorString = colorString.charAt(0) + colorString.charAt(0) + colorString.charAt(1) + colorString.charAt(1) + colorString.charAt(2) + colorString.charAt(2) } return parseInt(colorString, 16) }; Common.logLevel = 1; Common.log = function() { if (console && Common.logLevel > 0 && Common.logLevel <= 3) { console.log.apply(console, ["matter-js:"].concat(Array.prototype.slice.call(arguments))) } }; Common.info = function() { if (console && Common.logLevel > 0 && Common.logLevel <= 2) { console.info.apply(console, ["matter-js:"].concat(Array.prototype.slice.call(arguments))) } }; Common.warn = function() { if (console && Common.logLevel > 0 && Common.logLevel <= 3) { console.warn.apply(console, ["matter-js:"].concat(Array.prototype.slice.call(arguments))) } }; Common.nextId = function() { return Common._nextId++ }; Common.indexOf = function(haystack, needle) { if (haystack.indexOf) return haystack.indexOf(needle); for (var i = 0; i < haystack.length; i++) { if (haystack[i] === needle) return i } return -1 }; Common.map = function(list, func) { if (list.map) { return list.map(func) } var mapped = []; for (var i = 0; i < list.length; i += 1) { mapped.push(func(list[i])) } return mapped }; Common.topologicalSort = function(graph) { var result = [], visited = [], temp = []; for (var node in graph) { if (!visited[node] && !temp[node]) { Common._topologicalSort(node, visited, temp, graph, result) } } return result }; Common._topologicalSort = function(node, visited, temp, graph, result) { var neighbors = graph[node] || []; temp[node] = true; for (var i = 0; i < neighbors.length; i += 1) { var neighbor = neighbors[i]; if (temp[neighbor]) { continue } if (!visited[neighbor]) { Common._topologicalSort(neighbor, visited, temp, graph, result) } } temp[node] = false; visited[node] = true; result.push(node) }; Common.chain = function() { var funcs = []; for (var i = 0; i < arguments.length; i += 1) { var func = arguments[i]; if (func._chained) { funcs.push.apply(funcs, func._chained) } else { funcs.push(func) } } var chain = function() { var lastResult, args = new Array(arguments.length); for (var i = 0, l = arguments.length; i < l; i++) { args[i] = arguments[i] } for (i = 0; i < funcs.length; i += 1) { var result = funcs[i].apply(lastResult, args); if (typeof result !== "undefined") { lastResult = result } } return lastResult }; chain._chained = funcs; return chain }; Common.chainPathBefore = function(base, path, func) { return Common.set(base, path, Common.chain(func, Common.get(base, path))) }; Common.chainPathAfter = function(base, path, func) { return Common.set(base, path, Common.chain(Common.get(base, path), func)) }; Common._requireGlobal = function(globalName, moduleName) { var obj = typeof window !== "undefined" ? window[globalName] : typeof global !== "undefined" ? global[globalName] : null; return obj } })() }).call(exports, __webpack_require__(142)) }, function(module, exports, __webpack_require__) { var RND = __webpack_require__(238); var MATH_CONST = { PI2: Math.PI * 2, TAU: Math.PI * .5, EPSILON: 1e-6, DEG_TO_RAD: Math.PI / 180, RAD_TO_DEG: 180 / Math.PI, RND: new RND }; module.exports = MATH_CONST }, function(module, exports, __webpack_require__) { var IsPlainObject = __webpack_require__(7); var Extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; if (typeof target === "boolean") { deep = target; target = arguments[1] || {}; i = 2 } if (length === i) { target = this; --i } for (; i < length; i++) { if ((options = arguments[i]) != null) { for (name in options) { src = target[name]; copy = options[name]; if (target === copy) { continue } if (deep && copy && (IsPlainObject(copy) || (copyIsArray = Array.isArray(copy)))) { if (copyIsArray) { copyIsArray = false; clone = src && Array.isArray(src) ? src : [] } else { clone = src && IsPlainObject(src) ? src : {} } target[name] = Extend(deep, clone, copy) } else if (copy !== undefined) { target[name] = copy } } } } return target }; module.exports = Extend }, function(module, exports) { var FILE_CONST = { LOADER_IDLE: 0, LOADER_LOADING: 1, LOADER_PROCESSING: 2, LOADER_COMPLETE: 3, LOADER_SHUTDOWN: 4, LOADER_DESTROYED: 5, FILE_PENDING: 10, FILE_LOADING: 11, FILE_LOADED: 12, FILE_FAILED: 13, FILE_PROCESSING: 14, FILE_ERRORED: 16, FILE_COMPLETE: 17, FILE_DESTROYED: 18, FILE_POPULATED: 19 }; module.exports = FILE_CONST }, function(module, exports, __webpack_require__) { var GetFastValue = __webpack_require__(1); var GetTilesWithin = function(tileX, tileY, width, height, filteringOptions, layer) { if (tileX === undefined) { tileX = 0 } if (tileY === undefined) { tileY = 0 } if (width === undefined) { width = layer.width } if (height === undefined) { height = layer.height } var isNotEmpty = GetFastValue(filteringOptions, "isNotEmpty", false); var isColliding = GetFastValue(filteringOptions, "isColliding", false); var hasInterestingFace = GetFastValue(filteringOptions, "hasInterestingFace", false); if (tileX < 0) { width += tileX; tileX = 0 } if (tileY < 0) { height += tileY; tileY = 0 } if (tileX + width > layer.width) { width = Math.max(layer.width - tileX, 0) } if (tileY + height > layer.height) { height = Math.max(layer.height - tileY, 0) } var results = []; for (var ty = tileY; ty < tileY + height; ty++) { for (var tx = tileX; tx < tileX + width; tx++) { var tile = layer.data[ty][tx]; if (tile !== null) { if (isNotEmpty && tile.index === -1) { continue } if (isColliding && !tile.collides) { continue } if (hasInterestingFace && !tile.hasInterestingFace) { continue } results.push(tile) } } } return results }; module.exports = GetTilesWithin }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var CONST = __webpack_require__(20); var GetFastValue = __webpack_require__(1); var GetURL = __webpack_require__(199); var MergeXHRSettings = __webpack_require__(200); var XHRLoader = __webpack_require__(397); var XHRSettings = __webpack_require__(129); var File = new Class({ initialize: function File(loader, fileConfig) { this.loader = loader; this.cache = GetFastValue(fileConfig, "cache", false); this.type = GetFastValue(fileConfig, "type", false); this.key = GetFastValue(fileConfig, "key", false); var loadKey = this.key; if (loader.prefix && loader.prefix !== "") { this.key = loader.prefix + loadKey } if (!this.type || !this.key) { throw new Error("Error calling 'Loader." + this.type + "' invalid key provided.") } this.url = GetFastValue(fileConfig, "url"); if (this.url === undefined) { this.url = loader.path + loadKey + "." + GetFastValue(fileConfig, "extension", "") } else if (typeof this.url !== "function") { this.url = loader.path + this.url } this.src = ""; this.xhrSettings = XHRSettings(GetFastValue(fileConfig, "responseType", undefined)); if (GetFastValue(fileConfig, "xhrSettings", false)) { this.xhrSettings = MergeXHRSettings(this.xhrSettings, GetFastValue(fileConfig, "xhrSettings", {})) } this.xhrLoader = null; this.state = typeof this.url === "function" ? CONST.FILE_POPULATED : CONST.FILE_PENDING; this.bytesTotal = 0; this.bytesLoaded = -1; this.percentComplete = -1; this.crossOrigin = undefined; this.data = undefined; this.config = GetFastValue(fileConfig, "config", {}); this.multiFile; this.linkFile }, setLink: function(fileB) { this.linkFile = fileB; fileB.linkFile = this }, resetXHR: function() { if (this.xhrLoader) { this.xhrLoader.onload = undefined; this.xhrLoader.onerror = undefined; this.xhrLoader.onprogress = undefined } }, load: function() { if (this.state === CONST.FILE_POPULATED) { this.loader.nextFile(this, true) } else { this.src = GetURL(this, this.loader.baseURL); if (this.src.indexOf("data:") === 0) { console.warn("Local data URIs are not supported: " + this.key) } else { this.xhrLoader = XHRLoader(this, this.loader.xhr) } } }, onLoad: function(xhr, event) { var success = !(event.target && event.target.status !== 200); if (xhr.readyState === 4 && xhr.status >= 400 && xhr.status <= 599) { success = false } this.resetXHR(); this.loader.nextFile(this, success) }, onError: function() { this.resetXHR(); this.loader.nextFile(this, false) }, onProgress: function(event) { if (event.lengthComputable) { this.bytesLoaded = event.loaded; this.bytesTotal = event.total; this.percentComplete = Math.min(this.bytesLoaded / this.bytesTotal, 1); this.loader.emit("fileprogress", this, this.percentComplete) } }, onProcess: function() { this.state = CONST.FILE_PROCESSING; this.onProcessComplete() }, onProcessComplete: function() { this.state = CONST.FILE_COMPLETE; if (this.multiFile) { this.multiFile.onFileComplete(this) } this.loader.fileProcessComplete(this) }, onProcessError: function() { this.state = CONST.FILE_ERRORED; if (this.multiFile) { this.multiFile.onFileFailed(this) } this.loader.fileProcessComplete(this) }, hasCacheConflict: function() { return this.cache && this.cache.exists(this.key) }, addToCache: function() { if (this.cache) { this.cache.add(this.key, this.data) } this.pendingDestroy() }, pendingDestroy: function(data) { if (data === undefined) { data = this.data } var key = this.key; var type = this.type; this.loader.emit("filecomplete", key, type, data); this.loader.emit("filecomplete-" + type + "-" + key, key, type, data); this.loader.flagForRemoval(this) }, destroy: function() { this.loader = null; this.cache = null; this.xhrSettings = null; this.multiFile = null; this.linkFile = null; this.data = null } }); File.createObjectURL = function(image, blob, defaultType) { if (typeof URL === "function") { image.src = URL.createObjectURL(blob) } else { var reader = new FileReader; reader.onload = function() { image.removeAttribute("crossOrigin"); image.src = "data:" + (blob.type || defaultType) + ";base64," + reader.result.split(",")[1] }; reader.onerror = image.onerror; reader.readAsDataURL(blob) } }; File.revokeObjectURL = function(image) { if (typeof URL === "function") { URL.revokeObjectURL(image.src) } }; module.exports = File }, function(module, exports) { var Clamp = function(value, min, max) { return Math.max(min, Math.min(max, value)) }; module.exports = Clamp }, function(module, exports) { var SetTransform = function(renderer, ctx, src, camera, parentMatrix) { var alpha = camera.alpha * src.alpha; if (alpha <= 0) { return false } var camMatrix = renderer._tempMatrix1.copyFromArray(camera.matrix.matrix); var gameObjectMatrix = renderer._tempMatrix2.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); var calcMatrix = renderer._tempMatrix3; if (parentMatrix) { camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); gameObjectMatrix.e = src.x; gameObjectMatrix.f = src.y; camMatrix.multiply(gameObjectMatrix, calcMatrix) } else { gameObjectMatrix.e -= camera.scrollX * src.scrollFactorX; gameObjectMatrix.f -= camera.scrollY * src.scrollFactorY; camMatrix.multiply(gameObjectMatrix, calcMatrix) } ctx.globalCompositeOperation = renderer.blendModes[src.blendMode]; ctx.globalAlpha = alpha; ctx.save(); calcMatrix.setToContext(ctx); return true }; module.exports = SetTransform }, function(module, exports, __webpack_require__) { var Body = {}; module.exports = Body; var Vertices = __webpack_require__(32); var Vector = __webpack_require__(33); var Sleeping = __webpack_require__(103); var Common = __webpack_require__(17); var Bounds = __webpack_require__(34); var Axes = __webpack_require__(204); (function() { Body._inertiaScale = 4; Body._nextCollidingGroupId = 1; Body._nextNonCollidingGroupId = -1; Body._nextCategory = 1; Body.create = function(options) { var defaults = { id: Common.nextId(), type: "body", label: "Body", gameObject: null, parts: [], plugin: {}, angle: 0, vertices: Vertices.fromPath("L 0 0 L 40 0 L 40 40 L 0 40"), position: { x: 0, y: 0 }, force: { x: 0, y: 0 }, torque: 0, positionImpulse: { x: 0, y: 0 }, previousPositionImpulse: { x: 0, y: 0 }, constraintImpulse: { x: 0, y: 0, angle: 0 }, totalContacts: 0, speed: 0, angularSpeed: 0, velocity: { x: 0, y: 0 }, angularVelocity: 0, isSensor: false, isStatic: false, isSleeping: false, ignoreGravity: false, ignorePointer: false, motion: 0, sleepThreshold: 60, density: .001, restitution: 0, friction: .1, frictionStatic: .5, frictionAir: .01, collisionFilter: { category: 1, mask: 4294967295, group: 0 }, slop: .05, timeScale: 1, render: { visible: true, opacity: 1, sprite: { xScale: 1, yScale: 1, xOffset: 0, yOffset: 0 }, lineWidth: 0 }, events: null, bounds: null, chamfer: null, circleRadius: 0, positionPrev: null, anglePrev: 0, parent: null, axes: null, area: 0, mass: 0, inertia: 0, _original: null }; var body = Common.extend(defaults, options); _initProperties(body, options); return body }; Body.nextGroup = function(isNonColliding) { if (isNonColliding) return Body._nextNonCollidingGroupId--; return Body._nextCollidingGroupId++ }; Body.nextCategory = function() { Body._nextCategory = Body._nextCategory << 1; return Body._nextCategory }; var _initProperties = function(body, options) { options = options || {}; Body.set(body, { bounds: body.bounds || Bounds.create(body.vertices), positionPrev: body.positionPrev || Vector.clone(body.position), anglePrev: body.anglePrev || body.angle, vertices: body.vertices, parts: body.parts || [body], isStatic: body.isStatic, isSleeping: body.isSleeping, parent: body.parent || body }); Vertices.rotate(body.vertices, body.angle, body.position); Axes.rotate(body.axes, body.angle); Bounds.update(body.bounds, body.vertices, body.velocity); Body.set(body, { axes: options.axes || body.axes, area: options.area || body.area, mass: options.mass || body.mass, inertia: options.inertia || body.inertia }); var defaultFillStyle = body.isStatic ? "#2e2b44" : Common.choose(["#006BA6", "#0496FF", "#FFBC42", "#D81159", "#8F2D56"]), defaultStrokeStyle = "#000"; body.render.fillStyle = body.render.fillStyle || defaultFillStyle; body.render.strokeStyle = body.render.strokeStyle || defaultStrokeStyle; body.render.sprite.xOffset += -(body.bounds.min.x - body.position.x) / (body.bounds.max.x - body.bounds.min.x); body.render.sprite.yOffset += -(body.bounds.min.y - body.position.y) / (body.bounds.max.y - body.bounds.min.y) }; Body.set = function(body, settings, value) { var property; if (typeof settings === "string") { property = settings; settings = {}; settings[property] = value } for (property in settings) { if (!settings.hasOwnProperty(property)) continue; value = settings[property]; switch (property) { case "isStatic": Body.setStatic(body, value); break; case "isSleeping": Sleeping.set(body, value); break; case "mass": Body.setMass(body, value); break; case "density": Body.setDensity(body, value); break; case "inertia": Body.setInertia(body, value); break; case "vertices": Body.setVertices(body, value); break; case "position": Body.setPosition(body, value); break; case "angle": Body.setAngle(body, value); break; case "velocity": Body.setVelocity(body, value); break; case "angularVelocity": Body.setAngularVelocity(body, value); break; case "parts": Body.setParts(body, value); break; default: body[property] = value } } }; Body.setStatic = function(body, isStatic) { for (var i = 0; i < body.parts.length; i++) { var part = body.parts[i]; part.isStatic = isStatic; if (isStatic) { part._original = { restitution: part.restitution, friction: part.friction, mass: part.mass, inertia: part.inertia, density: part.density, inverseMass: part.inverseMass, inverseInertia: part.inverseInertia }; part.restitution = 0; part.friction = 1; part.mass = part.inertia = part.density = Infinity; part.inverseMass = part.inverseInertia = 0; part.positionPrev.x = part.position.x; part.positionPrev.y = part.position.y; part.anglePrev = part.angle; part.angularVelocity = 0; part.speed = 0; part.angularSpeed = 0; part.motion = 0 } else if (part._original) { part.restitution = part._original.restitution; part.friction = part._original.friction; part.mass = part._original.mass; part.inertia = part._original.inertia; part.density = part._original.density; part.inverseMass = part._original.inverseMass; part.inverseInertia = part._original.inverseInertia; part._original = null } } }; Body.setMass = function(body, mass) { var moment = body.inertia / (body.mass / 6); body.inertia = moment * (mass / 6); body.inverseInertia = 1 / body.inertia; body.mass = mass; body.inverseMass = 1 / body.mass; body.density = body.mass / body.area }; Body.setDensity = function(body, density) { Body.setMass(body, density * body.area); body.density = density }; Body.setInertia = function(body, inertia) { body.inertia = inertia; body.inverseInertia = 1 / body.inertia }; Body.setVertices = function(body, vertices) { if (vertices[0].body === body) { body.vertices = vertices } else { body.vertices = Vertices.create(vertices, body) } body.axes = Axes.fromVertices(body.vertices); body.area = Vertices.area(body.vertices); Body.setMass(body, body.density * body.area); var centre = Vertices.centre(body.vertices); Vertices.translate(body.vertices, centre, -1); Body.setInertia(body, Body._inertiaScale * Vertices.inertia(body.vertices, body.mass)); Vertices.translate(body.vertices, body.position); Bounds.update(body.bounds, body.vertices, body.velocity) }; Body.setParts = function(body, parts, autoHull) { var i; parts = parts.slice(0); body.parts.length = 0; body.parts.push(body); body.parent = body; for (i = 0; i < parts.length; i++) { var part = parts[i]; if (part !== body) { part.parent = body; body.parts.push(part) } } if (body.parts.length === 1) return; autoHull = typeof autoHull !== "undefined" ? autoHull : true; if (autoHull) { var vertices = []; for (i = 0; i < parts.length; i++) { vertices = vertices.concat(parts[i].vertices) } Vertices.clockwiseSort(vertices); var hull = Vertices.hull(vertices), hullCentre = Vertices.centre(hull); Body.setVertices(body, hull); Vertices.translate(body.vertices, hullCentre) } var total = Body._totalProperties(body); body.area = total.area; body.parent = body; body.position.x = total.centre.x; body.position.y = total.centre.y; body.positionPrev.x = total.centre.x; body.positionPrev.y = total.centre.y; Body.setMass(body, total.mass); Body.setInertia(body, total.inertia); Body.setPosition(body, total.centre) }; Body.setPosition = function(body, position) { var delta = Vector.sub(position, body.position); body.positionPrev.x += delta.x; body.positionPrev.y += delta.y; for (var i = 0; i < body.parts.length; i++) { var part = body.parts[i]; part.position.x += delta.x; part.position.y += delta.y; Vertices.translate(part.vertices, delta); Bounds.update(part.bounds, part.vertices, body.velocity) } }; Body.setAngle = function(body, angle) { var delta = angle - body.angle; body.anglePrev += delta; for (var i = 0; i < body.parts.length; i++) { var part = body.parts[i]; part.angle += delta; Vertices.rotate(part.vertices, delta, body.position); Axes.rotate(part.axes, delta); Bounds.update(part.bounds, part.vertices, body.velocity); if (i > 0) { Vector.rotateAbout(part.position, delta, body.position, part.position) } } }; Body.setVelocity = function(body, velocity) { body.positionPrev.x = body.position.x - velocity.x; body.positionPrev.y = body.position.y - velocity.y; body.velocity.x = velocity.x; body.velocity.y = velocity.y; body.speed = Vector.magnitude(body.velocity) }; Body.setAngularVelocity = function(body, velocity) { body.anglePrev = body.angle - velocity; body.angularVelocity = velocity; body.angularSpeed = Math.abs(body.angularVelocity) }; Body.translate = function(body, translation) { Body.setPosition(body, Vector.add(body.position, translation)) }; Body.rotate = function(body, rotation, point) { if (!point) { Body.setAngle(body, body.angle + rotation) } else { var cos = Math.cos(rotation), sin = Math.sin(rotation), dx = body.position.x - point.x, dy = body.position.y - point.y; Body.setPosition(body, { x: point.x + (dx * cos - dy * sin), y: point.y + (dx * sin + dy * cos) }); Body.setAngle(body, body.angle + rotation) } }; Body.scale = function(body, scaleX, scaleY, point) { var totalArea = 0, totalInertia = 0; point = point || body.position; for (var i = 0; i < body.parts.length; i++) { var part = body.parts[i]; Vertices.scale(part.vertices, scaleX, scaleY, point); part.axes = Axes.fromVertices(part.vertices); part.area = Vertices.area(part.vertices); Body.setMass(part, body.density * part.area); Vertices.translate(part.vertices, { x: -part.position.x, y: -part.position.y }); Body.setInertia(part, Body._inertiaScale * Vertices.inertia(part.vertices, part.mass)); Vertices.translate(part.vertices, { x: part.position.x, y: part.position.y }); if (i > 0) { totalArea += part.area; totalInertia += part.inertia } part.position.x = point.x + (part.position.x - point.x) * scaleX; part.position.y = point.y + (part.position.y - point.y) * scaleY; Bounds.update(part.bounds, part.vertices, body.velocity) } if (body.parts.length > 1) { body.area = totalArea; if (!body.isStatic) { Body.setMass(body, body.density * totalArea); Body.setInertia(body, totalInertia) } } if (body.circleRadius) { if (scaleX === scaleY) { body.circleRadius *= scaleX } else { body.circleRadius = null } } }; Body.update = function(body, deltaTime, timeScale, correction) { var deltaTimeSquared = Math.pow(deltaTime * timeScale * body.timeScale, 2); var frictionAir = 1 - body.frictionAir * timeScale * body.timeScale, velocityPrevX = body.position.x - body.positionPrev.x, velocityPrevY = body.position.y - body.positionPrev.y; body.velocity.x = velocityPrevX * frictionAir * correction + body.force.x / body.mass * deltaTimeSquared; body.velocity.y = velocityPrevY * frictionAir * correction + body.force.y / body.mass * deltaTimeSquared; body.positionPrev.x = body.position.x; body.positionPrev.y = body.position.y; body.position.x += body.velocity.x; body.position.y += body.velocity.y; body.angularVelocity = (body.angle - body.anglePrev) * frictionAir * correction + body.torque / body.inertia * deltaTimeSquared; body.anglePrev = body.angle; body.angle += body.angularVelocity; body.speed = Vector.magnitude(body.velocity); body.angularSpeed = Math.abs(body.angularVelocity); for (var i = 0; i < body.parts.length; i++) { var part = body.parts[i]; Vertices.translate(part.vertices, body.velocity); if (i > 0) { part.position.x += body.velocity.x; part.position.y += body.velocity.y } if (body.angularVelocity !== 0) { Vertices.rotate(part.vertices, body.angularVelocity, body.position); Axes.rotate(part.axes, body.angularVelocity); if (i > 0) { Vector.rotateAbout(part.position, body.angularVelocity, body.position, part.position) } } Bounds.update(part.bounds, part.vertices, body.velocity) } }; Body.applyForce = function(body, position, force) { body.force.x += force.x; body.force.y += force.y; var offset = { x: position.x - body.position.x, y: position.y - body.position.y }; body.torque += offset.x * force.y - offset.y * force.x }; Body._totalProperties = function(body) { var properties = { mass: 0, area: 0, inertia: 0, centre: { x: 0, y: 0 } }; for (var i = body.parts.length === 1 ? 0 : 1; i < body.parts.length; i++) { var part = body.parts[i], mass = part.mass !== Infinity ? part.mass : 1; properties.mass += mass; properties.area += part.area; properties.inertia += part.inertia; properties.centre = Vector.add(properties.centre, Vector.mult(part.position, mass)) } properties.centre = Vector.div(properties.centre, properties.mass); return properties } })() }, function(module, exports, __webpack_require__) { var CONST = { VERSION: "3.15.1", BlendModes: __webpack_require__(61), ScaleModes: __webpack_require__(89), AUTO: 0, CANVAS: 1, WEBGL: 2, HEADLESS: 3, FOREVER: -1, NONE: 4, UP: 5, DOWN: 6, LEFT: 7, RIGHT: 8 }; module.exports = CONST }, function(module, exports) { var PropertyValueSet = function(items, key, value, step, index, direction) { if (step === undefined) { step = 0 } if (index === undefined) { index = 0 } if (direction === undefined) { direction = 1 } var i; var t = 0; var end = items.length; if (direction === 1) { for (i = index; i < end; i++) { items[i][key] = value + t * step; t++ } } else { for (i = index; i >= 0; i--) { items[i][key] = value + t * step; t++ } } return items }; module.exports = PropertyValueSet }, function(module, exports, __webpack_require__) { var CONST = __webpack_require__(26); var Smoothing = __webpack_require__(112); var pool = []; var _disableContextSmoothing = false; var CanvasPool = function() { var create = function(parent, width, height, canvasType, selfParent) { if (width === undefined) { width = 1 } if (height === undefined) { height = 1 } if (canvasType === undefined) { canvasType = CONST.CANVAS } if (selfParent === undefined) { selfParent = false } var canvas; var container = first(canvasType); if (container === null) { container = { parent: parent, canvas: document.createElement("canvas"), type: canvasType }; if (canvasType === CONST.CANVAS) { pool.push(container) } canvas = container.canvas } else { container.parent = parent; canvas = container.canvas } if (selfParent) { container.parent = canvas } canvas.width = width; canvas.height = height; if (_disableContextSmoothing && canvasType === CONST.CANVAS) { Smoothing.disable(canvas.getContext("2d")) } return canvas }; var create2D = function(parent, width, height) { return create(parent, width, height, CONST.CANVAS) }; var createWebGL = function(parent, width, height) { return create(parent, width, height, CONST.WEBGL) }; var first = function(canvasType) { if (canvasType === undefined) { canvasType = CONST.CANVAS } if (canvasType === CONST.WEBGL) { return null } for (var i = 0; i < pool.length; i++) { var container = pool[i]; if (!container.parent && container.type === canvasType) { return container } } return null }; var remove = function(parent) { var isCanvas = parent instanceof HTMLCanvasElement; pool.forEach(function(container) { if (isCanvas && container.canvas === parent || !isCanvas && container.parent === parent) { container.parent = null; container.canvas.width = 1; container.canvas.height = 1 } }) }; var total = function() { var c = 0; pool.forEach(function(container) { if (container.parent) { c++ } }); return c }; var free = function() { return pool.length - total() }; var disableSmoothing = function() { _disableContextSmoothing = true }; var enableSmoothing = function() { _disableContextSmoothing = false }; return { create2D: create2D, create: create, createWebGL: createWebGL, disableSmoothing: disableSmoothing, enableSmoothing: enableSmoothing, first: first, free: free, pool: pool, remove: remove, total: total } }; module.exports = CanvasPool() }, function(module, exports, __webpack_require__) { var BlendModes = __webpack_require__(61); var GetAdvancedValue = __webpack_require__(13); var ScaleModes = __webpack_require__(89); var BuildGameObject = function(scene, gameObject, config) { gameObject.x = GetAdvancedValue(config, "x", 0); gameObject.y = GetAdvancedValue(config, "y", 0); gameObject.depth = GetAdvancedValue(config, "depth", 0); gameObject.flipX = GetAdvancedValue(config, "flipX", false); gameObject.flipY = GetAdvancedValue(config, "flipY", false); var scale = GetAdvancedValue(config, "scale", null); if (typeof scale === "number") { gameObject.setScale(scale) } else if (scale !== null) { gameObject.scaleX = GetAdvancedValue(scale, "x", 1); gameObject.scaleY = GetAdvancedValue(scale, "y", 1) } var scrollFactor = GetAdvancedValue(config, "scrollFactor", null); if (typeof scrollFactor === "number") { gameObject.setScrollFactor(scrollFactor) } else if (scrollFactor !== null) { gameObject.scrollFactorX = GetAdvancedValue(scrollFactor, "x", 1); gameObject.scrollFactorY = GetAdvancedValue(scrollFactor, "y", 1) } gameObject.rotation = GetAdvancedValue(config, "rotation", 0); var angle = GetAdvancedValue(config, "angle", null); if (angle !== null) { gameObject.angle = angle } gameObject.alpha = GetAdvancedValue(config, "alpha", 1); var origin = GetAdvancedValue(config, "origin", null); if (typeof origin === "number") { gameObject.setOrigin(origin) } else if (origin !== null) { var ox = GetAdvancedValue(origin, "x", .5); var oy = GetAdvancedValue(origin, "y", .5); gameObject.setOrigin(ox, oy) } gameObject.scaleMode = GetAdvancedValue(config, "scaleMode", ScaleModes.DEFAULT); gameObject.blendMode = GetAdvancedValue(config, "blendMode", BlendModes.NORMAL); gameObject.visible = GetAdvancedValue(config, "visible", true); var add = GetAdvancedValue(config, "add", true); if (add) { scene.sys.displayList.add(gameObject) } if (gameObject.preUpdate) { scene.sys.updateList.add(gameObject) } return gameObject }; module.exports = BuildGameObject }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Components = __webpack_require__(14); var GameObject = __webpack_require__(12); var Line = __webpack_require__(54); var Shape = new Class({ Extends: GameObject, Mixins: [Components.Alpha, Components.BlendMode, Components.ComputedSize, Components.Depth, Components.GetBounds, Components.Mask, Components.Origin, Components.Pipeline, Components.ScaleMode, Components.ScrollFactor, Components.Transform, Components.Visible], initialize: function Shape(scene, type, data) { if (type === undefined) { type = "Shape" } GameObject.call(this, scene, type); this.geom = data; this.pathData = []; this.pathIndexes = []; this.fillColor = 16777215; this.fillAlpha = 1; this.strokeColor = 16777215; this.strokeAlpha = 1; this.lineWidth = 1; this.isFilled = false; this.isStroked = false; this.closePath = true; this._tempLine = new Line; this.initPipeline() }, setFillStyle: function(color, alpha) { if (alpha === undefined) { alpha = 1 } if (color === undefined) { this.isFilled = false } else { this.fillColor = color; this.fillAlpha = alpha; this.isFilled = true } return this }, setStrokeStyle: function(lineWidth, color, alpha) { if (alpha === undefined) { alpha = 1 } if (lineWidth === undefined) { this.isStroked = false } else { this.lineWidth = lineWidth; this.strokeColor = color; this.strokeAlpha = alpha; this.isStroked = true } return this }, setClosePath: function(value) { this.closePath = value; return this }, preDestroy: function() { this.geom = null; this._tempLine = null; this.pathData = []; this.pathIndexes = [] } }); module.exports = Shape }, function(module, exports) { module.exports = { CSV: 0, TILED_JSON: 1, ARRAY_2D: 2, WELTMEISTER: 3 } }, function(module, exports, __webpack_require__) { var Vertices = {}; module.exports = Vertices; var Vector = __webpack_require__(33); var Common = __webpack_require__(17); (function() { Vertices.create = function(points, body) { var vertices = []; for (var i = 0; i < points.length; i++) { var point = points[i], vertex = { x: point.x, y: point.y, index: i, body: body, isInternal: false, contact: null }; vertex.contact = { vertex: vertex, normalImpulse: 0, tangentImpulse: 0 }; vertices.push(vertex) } return vertices }; Vertices.fromPath = function(path, body) { var pathPattern = /L?\s*([\-\d\.e]+)[\s,]*([\-\d\.e]+)*/gi, points = []; path.replace(pathPattern, function(match, x, y) { points.push({ x: parseFloat(x), y: parseFloat(y) }) }); return Vertices.create(points, body) }; Vertices.centre = function(vertices) { var area = Vertices.area(vertices, true), centre = { x: 0, y: 0 }, cross, temp, j; for (var i = 0; i < vertices.length; i++) { j = (i + 1) % vertices.length; cross = Vector.cross(vertices[i], vertices[j]); temp = Vector.mult(Vector.add(vertices[i], vertices[j]), cross); centre = Vector.add(centre, temp) } return Vector.div(centre, 6 * area) }; Vertices.mean = function(vertices) { var average = { x: 0, y: 0 }; for (var i = 0; i < vertices.length; i++) { average.x += vertices[i].x; average.y += vertices[i].y } return Vector.div(average, vertices.length) }; Vertices.area = function(vertices, signed) { var area = 0, j = vertices.length - 1; for (var i = 0; i < vertices.length; i++) { area += (vertices[j].x - vertices[i].x) * (vertices[j].y + vertices[i].y); j = i } if (signed) return area / 2; return Math.abs(area) / 2 }; Vertices.inertia = function(vertices, mass) { var numerator = 0, denominator = 0, v = vertices, cross, j; for (var n = 0; n < v.length; n++) { j = (n + 1) % v.length; cross = Math.abs(Vector.cross(v[j], v[n])); numerator += cross * (Vector.dot(v[j], v[j]) + Vector.dot(v[j], v[n]) + Vector.dot(v[n], v[n])); denominator += cross } return mass / 6 * (numerator / denominator) }; Vertices.translate = function(vertices, vector, scalar) { var i; if (scalar) { for (i = 0; i < vertices.length; i++) { vertices[i].x += vector.x * scalar; vertices[i].y += vector.y * scalar } } else { for (i = 0; i < vertices.length; i++) { vertices[i].x += vector.x; vertices[i].y += vector.y } } return vertices }; Vertices.rotate = function(vertices, angle, point) { if (angle === 0) return; var cos = Math.cos(angle), sin = Math.sin(angle); for (var i = 0; i < vertices.length; i++) { var vertice = vertices[i], dx = vertice.x - point.x, dy = vertice.y - point.y; vertice.x = point.x + (dx * cos - dy * sin); vertice.y = point.y + (dx * sin + dy * cos) } return vertices }; Vertices.contains = function(vertices, point) { for (var i = 0; i < vertices.length; i++) { var vertice = vertices[i], nextVertice = vertices[(i + 1) % vertices.length]; if ((point.x - vertice.x) * (nextVertice.y - vertice.y) + (point.y - vertice.y) * (vertice.x - nextVertice.x) > 0) { return false } } return true }; Vertices.scale = function(vertices, scaleX, scaleY, point) { if (scaleX === 1 && scaleY === 1) return vertices; point = point || Vertices.centre(vertices); var vertex, delta; for (var i = 0; i < vertices.length; i++) { vertex = vertices[i]; delta = Vector.sub(vertex, point); vertices[i].x = point.x + delta.x * scaleX; vertices[i].y = point.y + delta.y * scaleY } return vertices }; Vertices.chamfer = function(vertices, radius, quality, qualityMin, qualityMax) { if (typeof radius === "number") { radius = [radius] } else { radius = radius || [8] } quality = typeof quality !== "undefined" ? quality : -1; qualityMin = qualityMin || 2; qualityMax = qualityMax || 14; var newVertices = []; for (var i = 0; i < vertices.length; i++) { var prevVertex = vertices[i - 1 >= 0 ? i - 1 : vertices.length - 1], vertex = vertices[i], nextVertex = vertices[(i + 1) % vertices.length], currentRadius = radius[i < radius.length ? i : radius.length - 1]; if (currentRadius === 0) { newVertices.push(vertex); continue } var prevNormal = Vector.normalise({ x: vertex.y - prevVertex.y, y: prevVertex.x - vertex.x }); var nextNormal = Vector.normalise({ x: nextVertex.y - vertex.y, y: vertex.x - nextVertex.x }); var diagonalRadius = Math.sqrt(2 * Math.pow(currentRadius, 2)), radiusVector = Vector.mult(Common.clone(prevNormal), currentRadius), midNormal = Vector.normalise(Vector.mult(Vector.add(prevNormal, nextNormal), .5)), scaledVertex = Vector.sub(vertex, Vector.mult(midNormal, diagonalRadius)); var precision = quality; if (quality === -1) { precision = Math.pow(currentRadius, .32) * 1.75 } precision = Common.clamp(precision, qualityMin, qualityMax); if (precision % 2 === 1) precision += 1; var alpha = Math.acos(Vector.dot(prevNormal, nextNormal)), theta = alpha / precision; for (var j = 0; j < precision; j++) { newVertices.push(Vector.add(Vector.rotate(radiusVector, theta * j), scaledVertex)) } } return newVertices }; Vertices.clockwiseSort = function(vertices) { var centre = Vertices.mean(vertices); vertices.sort(function(vertexA, vertexB) { return Vector.angle(centre, vertexA) - Vector.angle(centre, vertexB) }); return vertices }; Vertices.isConvex = function(vertices) { var flag = 0, n = vertices.length, i, j, k, z; if (n < 3) return null; for (i = 0; i < n; i++) { j = (i + 1) % n; k = (i + 2) % n; z = (vertices[j].x - vertices[i].x) * (vertices[k].y - vertices[j].y); z -= (vertices[j].y - vertices[i].y) * (vertices[k].x - vertices[j].x); if (z < 0) { flag |= 1 } else if (z > 0) { flag |= 2 } if (flag === 3) { return false } } if (flag !== 0) { return true } else { return null } }; Vertices.hull = function(vertices) { var upper = [], lower = [], vertex, i; vertices = vertices.slice(0); vertices.sort(function(vertexA, vertexB) { var dx = vertexA.x - vertexB.x; return dx !== 0 ? dx : vertexA.y - vertexB.y }); for (i = 0; i < vertices.length; i += 1) { vertex = vertices[i]; while (lower.length >= 2 && Vector.cross3(lower[lower.length - 2], lower[lower.length - 1], vertex) <= 0) { lower.pop() } lower.push(vertex) } for (i = vertices.length - 1; i >= 0; i -= 1) { vertex = vertices[i]; while (upper.length >= 2 && Vector.cross3(upper[upper.length - 2], upper[upper.length - 1], vertex) <= 0) { upper.pop() } upper.push(vertex) } upper.pop(); lower.pop(); return upper.concat(lower) } })() }, function(module, exports) { var Vector = {}; module.exports = Vector; (function() { Vector.create = function(x, y) { return { x: x || 0, y: y || 0 } }; Vector.clone = function(vector) { return { x: vector.x, y: vector.y } }; Vector.magnitude = function(vector) { return Math.sqrt(vector.x * vector.x + vector.y * vector.y) }; Vector.magnitudeSquared = function(vector) { return vector.x * vector.x + vector.y * vector.y }; Vector.rotate = function(vector, angle, output) { var cos = Math.cos(angle), sin = Math.sin(angle); if (!output) output = {}; var x = vector.x * cos - vector.y * sin; output.y = vector.x * sin + vector.y * cos; output.x = x; return output }; Vector.rotateAbout = function(vector, angle, point, output) { var cos = Math.cos(angle), sin = Math.sin(angle); if (!output) output = {}; var x = point.x + ((vector.x - point.x) * cos - (vector.y - point.y) * sin); output.y = point.y + ((vector.x - point.x) * sin + (vector.y - point.y) * cos); output.x = x; return output }; Vector.normalise = function(vector) { var magnitude = Vector.magnitude(vector); if (magnitude === 0) return { x: 0, y: 0 }; return { x: vector.x / magnitude, y: vector.y / magnitude } }; Vector.dot = function(vectorA, vectorB) { return vectorA.x * vectorB.x + vectorA.y * vectorB.y }; Vector.cross = function(vectorA, vectorB) { return vectorA.x * vectorB.y - vectorA.y * vectorB.x }; Vector.cross3 = function(vectorA, vectorB, vectorC) { return (vectorB.x - vectorA.x) * (vectorC.y - vectorA.y) - (vectorB.y - vectorA.y) * (vectorC.x - vectorA.x) }; Vector.add = function(vectorA, vectorB, output) { if (!output) output = {}; output.x = vectorA.x + vectorB.x; output.y = vectorA.y + vectorB.y; return output }; Vector.sub = function(vectorA, vectorB, output) { if (!output) output = {}; output.x = vectorA.x - vectorB.x; output.y = vectorA.y - vectorB.y; return output }; Vector.mult = function(vector, scalar) { return { x: vector.x * scalar, y: vector.y * scalar } }; Vector.div = function(vector, scalar) { return { x: vector.x / scalar, y: vector.y / scalar } }; Vector.perp = function(vector, negate) { negate = negate === true ? -1 : 1; return { x: negate * -vector.y, y: negate * vector.x } }; Vector.neg = function(vector) { return { x: -vector.x, y: -vector.y } }; Vector.angle = function(vectorA, vectorB) { return Math.atan2(vectorB.y - vectorA.y, vectorB.x - vectorA.x) }; Vector._temp = [Vector.create(), Vector.create(), Vector.create(), Vector.create(), Vector.create(), Vector.create()] })() }, function(module, exports) { var Bounds = {}; module.exports = Bounds; (function() { Bounds.create = function(vertices) { var bounds = { min: { x: 0, y: 0 }, max: { x: 0, y: 0 } }; if (vertices) Bounds.update(bounds, vertices); return bounds }; Bounds.update = function(bounds, vertices, velocity) { bounds.min.x = Infinity; bounds.max.x = -Infinity; bounds.min.y = Infinity; bounds.max.y = -Infinity; for (var i = 0; i < vertices.length; i++) { var vertex = vertices[i]; if (vertex.x > bounds.max.x) bounds.max.x = vertex.x; if (vertex.x < bounds.min.x) bounds.min.x = vertex.x; if (vertex.y > bounds.max.y) bounds.max.y = vertex.y; if (vertex.y < bounds.min.y) bounds.min.y = vertex.y } if (velocity) { if (velocity.x > 0) { bounds.max.x += velocity.x } else { bounds.min.x += velocity.x } if (velocity.y > 0) { bounds.max.y += velocity.y } else { bounds.min.y += velocity.y } } }; Bounds.contains = function(bounds, point) { return point.x >= bounds.min.x && point.x <= bounds.max.x && point.y >= bounds.min.y && point.y <= bounds.max.y }; Bounds.overlaps = function(boundsA, boundsB) { return boundsA.min.x <= boundsB.max.x && boundsA.max.x >= boundsB.min.x && boundsA.max.y >= boundsB.min.y && boundsA.min.y <= boundsB.max.y }; Bounds.translate = function(bounds, vector) { bounds.min.x += vector.x; bounds.max.x += vector.x; bounds.min.y += vector.y; bounds.max.y += vector.y }; Bounds.shift = function(bounds, position) { var deltaX = bounds.max.x - bounds.min.x, deltaY = bounds.max.y - bounds.min.y; bounds.min.x = position.x; bounds.max.x = position.x + deltaX; bounds.min.y = position.y; bounds.max.y = position.y + deltaY } })() }, function(module, exports) { var PropertyValueInc = function(items, key, value, step, index, direction) { if (step === undefined) { step = 0 } if (index === undefined) { index = 0 } if (direction === undefined) { direction = 1 } var i; var t = 0; var end = items.length; if (direction === 1) { for (i = index; i < end; i++) { items[i][key] += value + t * step; t++ } } else { for (i = index; i >= 0; i--) { items[i][key] += value + t * step; t++ } } return items }; module.exports = PropertyValueInc }, function(module, exports, __webpack_require__) { var CONST = __webpack_require__(18); var DegToRad = function(degrees) { return degrees * CONST.DEG_TO_RAD }; module.exports = DegToRad }, function(module, exports) { var FillStyleCanvas = function(ctx, src, altColor) { var fillColor = altColor ? altColor : src.fillColor; var fillAlpha = src.fillAlpha; var red = (fillColor & 16711680) >>> 16; var green = (fillColor & 65280) >>> 8; var blue = fillColor & 255; ctx.fillStyle = "rgba(" + red + "," + green + "," + blue + "," + fillAlpha + ")" }; module.exports = FillStyleCanvas }, function(module, exports) { var GetBottom = function(gameObject) { return gameObject.y + gameObject.height - gameObject.height * gameObject.originY }; module.exports = GetBottom }, function(module, exports) { var SetBottom = function(gameObject, value) { gameObject.y = value - gameObject.height + gameObject.height * gameObject.originY; return gameObject }; module.exports = SetBottom }, function(module, exports) { var GetLeft = function(gameObject) { return gameObject.x - gameObject.width * gameObject.originX }; module.exports = GetLeft }, function(module, exports) { var SetLeft = function(gameObject, value) { gameObject.x = value + gameObject.width * gameObject.originX; return gameObject }; module.exports = SetLeft }, function(module, exports) { var GetRight = function(gameObject) { return gameObject.x + gameObject.width - gameObject.width * gameObject.originX }; module.exports = GetRight }, function(module, exports) { var SetRight = function(gameObject, value) { gameObject.x = value - gameObject.width + gameObject.width * gameObject.originX; return gameObject }; module.exports = SetRight }, function(module, exports) { var GetTop = function(gameObject) { return gameObject.y - gameObject.height * gameObject.originY }; module.exports = GetTop }, function(module, exports) { var SetTop = function(gameObject, value) { gameObject.y = value + gameObject.height * gameObject.originY; return gameObject }; module.exports = SetTop }, function(module, exports) { var Contains = function(circle, x, y) { if (circle.radius > 0 && x >= circle.left && x <= circle.right && y >= circle.top && y <= circle.bottom) { var dx = (circle.x - x) * (circle.x - x); var dy = (circle.y - y) * (circle.y - y); return dx + dy <= circle.radius * circle.radius } else { return false } }; module.exports = Contains }, function(module, exports) { var Contains = function(rect, x, y) { if (rect.width <= 0 || rect.height <= 0) { return false } return rect.x <= x && rect.x + rect.width >= x && rect.y <= y && rect.y + rect.height >= y }; module.exports = Contains }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Vector2 = __webpack_require__(3); var TransformMatrix = new Class({ initialize: function TransformMatrix(a, b, c, d, tx, ty) { if (a === undefined) { a = 1 } if (b === undefined) { b = 0 } if (c === undefined) { c = 0 } if (d === undefined) { d = 1 } if (tx === undefined) { tx = 0 } if (ty === undefined) { ty = 0 } this.matrix = new Float32Array([a, b, c, d, tx, ty, 0, 0, 1]); this.decomposedMatrix = { translateX: 0, translateY: 0, scaleX: 1, scaleY: 1, rotation: 0 } }, a: { get: function() { return this.matrix[0] }, set: function(value) { this.matrix[0] = value } }, b: { get: function() { return this.matrix[1] }, set: function(value) { this.matrix[1] = value } }, c: { get: function() { return this.matrix[2] }, set: function(value) { this.matrix[2] = value } }, d: { get: function() { return this.matrix[3] }, set: function(value) { this.matrix[3] = value } }, e: { get: function() { return this.matrix[4] }, set: function(value) { this.matrix[4] = value } }, f: { get: function() { return this.matrix[5] }, set: function(value) { this.matrix[5] = value } }, tx: { get: function() { return this.matrix[4] }, set: function(value) { this.matrix[4] = value } }, ty: { get: function() { return this.matrix[5] }, set: function(value) { this.matrix[5] = value } }, rotation: { get: function() { return Math.acos(this.a / this.scaleX) * (Math.atan(-this.c / this.a) < 0 ? -1 : 1) } }, scaleX: { get: function() { return Math.sqrt(this.a * this.a + this.c * this.c) } }, scaleY: { get: function() { return Math.sqrt(this.b * this.b + this.d * this.d) } }, loadIdentity: function() { var matrix = this.matrix; matrix[0] = 1; matrix[1] = 0; matrix[2] = 0; matrix[3] = 1; matrix[4] = 0; matrix[5] = 0; return this }, translate: function(x, y) { var matrix = this.matrix; matrix[4] = matrix[0] * x + matrix[2] * y + matrix[4]; matrix[5] = matrix[1] * x + matrix[3] * y + matrix[5]; return this }, scale: function(x, y) { var matrix = this.matrix; matrix[0] *= x; matrix[1] *= x; matrix[2] *= y; matrix[3] *= y; return this }, rotate: function(angle) { var sin = Math.sin(angle); var cos = Math.cos(angle); var matrix = this.matrix; var a = matrix[0]; var b = matrix[1]; var c = matrix[2]; var d = matrix[3]; matrix[0] = a * cos + c * sin; matrix[1] = b * cos + d * sin; matrix[2] = a * -sin + c * cos; matrix[3] = b * -sin + d * cos; return this }, multiply: function(rhs, out) { var matrix = this.matrix; var source = rhs.matrix; var localA = matrix[0]; var localB = matrix[1]; var localC = matrix[2]; var localD = matrix[3]; var localE = matrix[4]; var localF = matrix[5]; var sourceA = source[0]; var sourceB = source[1]; var sourceC = source[2]; var sourceD = source[3]; var sourceE = source[4]; var sourceF = source[5]; var destinationMatrix = out === undefined ? this : out; destinationMatrix.a = sourceA * localA + sourceB * localC; destinationMatrix.b = sourceA * localB + sourceB * localD; destinationMatrix.c = sourceC * localA + sourceD * localC; destinationMatrix.d = sourceC * localB + sourceD * localD; destinationMatrix.e = sourceE * localA + sourceF * localC + localE; destinationMatrix.f = sourceE * localB + sourceF * localD + localF; return destinationMatrix }, multiplyWithOffset: function(src, offsetX, offsetY) { var matrix = this.matrix; var otherMatrix = src.matrix; var a0 = matrix[0]; var b0 = matrix[1]; var c0 = matrix[2]; var d0 = matrix[3]; var tx0 = matrix[4]; var ty0 = matrix[5]; var pse = offsetX * a0 + offsetY * c0 + tx0; var psf = offsetX * b0 + offsetY * d0 + ty0; var a1 = otherMatrix[0]; var b1 = otherMatrix[1]; var c1 = otherMatrix[2]; var d1 = otherMatrix[3]; var tx1 = otherMatrix[4]; var ty1 = otherMatrix[5]; matrix[0] = a1 * a0 + b1 * c0; matrix[1] = a1 * b0 + b1 * d0; matrix[2] = c1 * a0 + d1 * c0; matrix[3] = c1 * b0 + d1 * d0; matrix[4] = tx1 * a0 + ty1 * c0 + pse; matrix[5] = tx1 * b0 + ty1 * d0 + psf; return this }, transform: function(a, b, c, d, tx, ty) { var matrix = this.matrix; var a0 = matrix[0]; var b0 = matrix[1]; var c0 = matrix[2]; var d0 = matrix[3]; var tx0 = matrix[4]; var ty0 = matrix[5]; matrix[0] = a * a0 + b * c0; matrix[1] = a * b0 + b * d0; matrix[2] = c * a0 + d * c0; matrix[3] = c * b0 + d * d0; matrix[4] = tx * a0 + ty * c0 + tx0; matrix[5] = tx * b0 + ty * d0 + ty0; return this }, transformPoint: function(x, y, point) { if (point === undefined) { point = { x: 0, y: 0 } } var matrix = this.matrix; var a = matrix[0]; var b = matrix[1]; var c = matrix[2]; var d = matrix[3]; var tx = matrix[4]; var ty = matrix[5]; point.x = x * a + y * c + tx; point.y = x * b + y * d + ty; return point }, invert: function() { var matrix = this.matrix; var a = matrix[0]; var b = matrix[1]; var c = matrix[2]; var d = matrix[3]; var tx = matrix[4]; var ty = matrix[5]; var n = a * d - b * c; matrix[0] = d / n; matrix[1] = -b / n; matrix[2] = -c / n; matrix[3] = a / n; matrix[4] = (c * ty - d * tx) / n; matrix[5] = -(a * ty - b * tx) / n; return this }, copyFrom: function(src) { var matrix = this.matrix; matrix[0] = src.a; matrix[1] = src.b; matrix[2] = src.c; matrix[3] = src.d; matrix[4] = src.e; matrix[5] = src.f; return this }, copyFromArray: function(src) { var matrix = this.matrix; matrix[0] = src[0]; matrix[1] = src[1]; matrix[2] = src[2]; matrix[3] = src[3]; matrix[4] = src[4]; matrix[5] = src[5]; return this }, copyToContext: function(ctx) { var matrix = this.matrix; ctx.transform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]); return ctx }, setToContext: function(ctx) { var matrix = this.matrix; ctx.setTransform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]); return ctx }, copyToArray: function(out) { var matrix = this.matrix; if (out === undefined) { out = [matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]] } else { out[0] = matrix[0]; out[1] = matrix[1]; out[2] = matrix[2]; out[3] = matrix[3]; out[4] = matrix[4]; out[5] = matrix[5] } return out }, setTransform: function(a, b, c, d, tx, ty) { var matrix = this.matrix; matrix[0] = a; matrix[1] = b; matrix[2] = c; matrix[3] = d; matrix[4] = tx; matrix[5] = ty; return this }, decomposeMatrix: function() { var decomposedMatrix = this.decomposedMatrix; var matrix = this.matrix; var a = matrix[0]; var b = matrix[1]; var c = matrix[2]; var d = matrix[3]; var a2 = a * a; var b2 = b * b; var c2 = c * c; var d2 = d * d; var sx = Math.sqrt(a2 + c2); var sy = Math.sqrt(b2 + d2); decomposedMatrix.translateX = matrix[4]; decomposedMatrix.translateY = matrix[5]; decomposedMatrix.scaleX = sx; decomposedMatrix.scaleY = sy; decomposedMatrix.rotation = Math.acos(a / sx) * (Math.atan(-c / a) < 0 ? -1 : 1); return decomposedMatrix }, applyITRS: function(x, y, rotation, scaleX, scaleY) { var matrix = this.matrix; var radianSin = Math.sin(rotation); var radianCos = Math.cos(rotation); matrix[4] = x; matrix[5] = y; matrix[0] = radianCos * scaleX; matrix[1] = radianSin * scaleX; matrix[2] = -radianSin * scaleY; matrix[3] = radianCos * scaleY; return this }, applyInverse: function(x, y, output) { if (output === undefined) { output = new Vector2 } var matrix = this.matrix; var a = matrix[0]; var b = matrix[1]; var c = matrix[2]; var d = matrix[3]; var tx = matrix[4]; var ty = matrix[5]; var id = 1 / (a * d + c * -b); output.x = d * id * x + -c * id * y + (ty * c - tx * d) * id; output.y = a * id * y + -b * id * x + (-ty * a + tx * b) * id; return output }, getX: function(x, y) { return x * this.a + y * this.c + this.e }, getY: function(x, y) { return x * this.b + y * this.d + this.f }, getCSSMatrix: function() { var m = this.matrix; return "matrix(" + m[0] + "," + m[1] + "," + m[2] + "," + m[3] + "," + m[4] + "," + m[5] + ")" }, destroy: function() { this.matrix = null; this.decomposedMatrix = null } }); module.exports = TransformMatrix }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var GetColor = __webpack_require__(160); var GetColor32 = __webpack_require__(267); var HSVToRGB = __webpack_require__(161); var RGBToHSV = __webpack_require__(268); var Color = new Class({ initialize: function Color(red, green, blue, alpha) { if (red === undefined) { red = 0 } if (green === undefined) { green = 0 } if (blue === undefined) { blue = 0 } if (alpha === undefined) { alpha = 255 } this.r = 0; this.g = 0; this.b = 0; this.a = 255; this._h = 0; this._s = 0; this._v = 0; this._locked = false; this.gl = [0, 0, 0, 1]; this._color = 0; this._color32 = 0; this._rgba = ""; this.setTo(red, green, blue, alpha) }, transparent: function() { this._locked = true; this.red = 0; this.green = 0; this.blue = 0; this.alpha = 0; this._locked = false; return this.update(true) }, setTo: function(red, green, blue, alpha, updateHSV) { if (alpha === undefined) { alpha = 255 } if (updateHSV === undefined) { updateHSV = true } this._locked = true; this.red = red; this.green = green; this.blue = blue; this.alpha = alpha; this._locked = false; return this.update(updateHSV) }, setGLTo: function(red, green, blue, alpha) { if (alpha === undefined) { alpha = 1 } this._locked = true; this.redGL = red; this.greenGL = green; this.blueGL = blue; this.alphaGL = alpha; this._locked = false; return this.update(true) }, setFromRGB: function(color) { this._locked = true; this.red = color.r; this.green = color.g; this.blue = color.b; if (color.hasOwnProperty("a")) { this.alpha = color.a } this._locked = false; return this.update(true) }, setFromHSV: function(h, s, v) { return HSVToRGB(h, s, v, this) }, update: function(updateHSV) { if (updateHSV === undefined) { updateHSV = false } if (this._locked) { return this } var r = this.r; var g = this.g; var b = this.b; var a = this.a; this._color = GetColor(r, g, b); this._color32 = GetColor32(r, g, b, a); this._rgba = "rgba(" + r + "," + g + "," + b + "," + a / 255 + ")"; if (updateHSV) { RGBToHSV(r, g, b, this) } return this }, updateHSV: function() { var r = this.r; var g = this.g; var b = this.b; RGBToHSV(r, g, b, this); return this }, clone: function() { return new Color(this.r, this.g, this.b, this.a) }, gray: function(shade) { return this.setTo(shade, shade, shade) }, random: function(min, max) { if (min === undefined) { min = 0 } if (max === undefined) { max = 255 } var r = Math.floor(min + Math.random() * (max - min)); var g = Math.floor(min + Math.random() * (max - min)); var b = Math.floor(min + Math.random() * (max - min)); return this.setTo(r, g, b) }, randomGray: function(min, max) { if (min === undefined) { min = 0 } if (max === undefined) { max = 255 } var s = Math.floor(min + Math.random() * (max - min)); return this.setTo(s, s, s) }, saturate: function(amount) { this.s += amount / 100; return this }, desaturate: function(amount) { this.s -= amount / 100; return this }, lighten: function(amount) { this.v += amount / 100; return this }, darken: function(amount) { this.v -= amount / 100; return this }, brighten: function(amount) { var r = this.r; var g = this.g; var b = this.b; r = Math.max(0, Math.min(255, r - Math.round(255 * -(amount / 100)))); g = Math.max(0, Math.min(255, g - Math.round(255 * -(amount / 100)))); b = Math.max(0, Math.min(255, b - Math.round(255 * -(amount / 100)))); return this.setTo(r, g, b) }, color: { get: function() { return this._color } }, color32: { get: function() { return this._color32 } }, rgba: { get: function() { return this._rgba } }, redGL: { get: function() { return this.gl[0] }, set: function(value) { this.gl[0] = Math.min(Math.abs(value), 1); this.r = Math.floor(this.gl[0] * 255); this.update(true) } }, greenGL: { get: function() { return this.gl[1] }, set: function(value) { this.gl[1] = Math.min(Math.abs(value), 1); this.g = Math.floor(this.gl[1] * 255); this.update(true) } }, blueGL: { get: function() { return this.gl[2] }, set: function(value) { this.gl[2] = Math.min(Math.abs(value), 1); this.b = Math.floor(this.gl[2] * 255); this.update(true) } }, alphaGL: { get: function() { return this.gl[3] }, set: function(value) { this.gl[3] = Math.min(Math.abs(value), 1); this.a = Math.floor(this.gl[3] * 255); this.update() } }, red: { get: function() { return this.r }, set: function(value) { value = Math.floor(Math.abs(value)); this.r = Math.min(value, 255); this.gl[0] = value / 255; this.update(true) } }, green: { get: function() { return this.g }, set: function(value) { value = Math.floor(Math.abs(value)); this.g = Math.min(value, 255); this.gl[1] = value / 255; this.update(true) } }, blue: { get: function() { return this.b }, set: function(value) { value = Math.floor(Math.abs(value)); this.b = Math.min(value, 255); this.gl[2] = value / 255; this.update(true) } }, alpha: { get: function() { return this.a }, set: function(value) { value = Math.floor(Math.abs(value)); this.a = Math.min(value, 255); this.gl[3] = value / 255; this.update() } }, h: { get: function() { return this._h }, set: function(value) { this._h = value; HSVToRGB(value, this._s, this._v, this) } }, s: { get: function() { return this._s }, set: function(value) { this._s = value; HSVToRGB(this._h, value, this._v, this) } }, v: { get: function() { return this._v }, set: function(value) { this._v = value; HSVToRGB(this._h, this._s, value, this) } } }); module.exports = Color }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Components = __webpack_require__(14); var GameObject = __webpack_require__(12); var SpriteRender = __webpack_require__(711); var Sprite = new Class({ Extends: GameObject, Mixins: [Components.Alpha, Components.BlendMode, Components.Depth, Components.Flip, Components.GetBounds, Components.Mask, Components.Origin, Components.Pipeline, Components.ScaleMode, Components.ScrollFactor, Components.Size, Components.TextureCrop, Components.Tint, Components.Transform, Components.Visible, SpriteRender], initialize: function Sprite(scene, x, y, texture, frame) { GameObject.call(this, scene, "Sprite"); this._crop = this.resetCropObject(); this.anims = new Components.Animation(this); this.setTexture(texture, frame); this.setPosition(x, y); this.setSizeToFrame(); this.setOriginFromFrame(); this.initPipeline() }, preUpdate: function(time, delta) { this.anims.update(time, delta) }, play: function(key, ignoreIfPlaying, startFrame) { this.anims.play(key, ignoreIfPlaying, startFrame); return this }, toJSON: function() { var data = Components.ToJSON(this); return data }, preDestroy: function() { this.anims.destroy(); this.anims = undefined } }); module.exports = Sprite }, function(module, exports) { var LineStyleCanvas = function(ctx, src) { var strokeColor = src.strokeColor; var strokeAlpha = src.strokeAlpha; var red = (strokeColor & 16711680) >>> 16; var green = (strokeColor & 65280) >>> 8; var blue = strokeColor & 255; ctx.strokeStyle = "rgba(" + red + "," + green + "," + blue + "," + strokeAlpha + ")"; ctx.lineWidth = src.lineWidth }; module.exports = LineStyleCanvas }, function(module, exports) { var CONST = { DYNAMIC_BODY: 0, STATIC_BODY: 1, GROUP: 2, TILEMAPLAYER: 3, FACING_NONE: 10, FACING_UP: 11, FACING_DOWN: 12, FACING_LEFT: 13, FACING_RIGHT: 14 }; module.exports = CONST }, function(module, exports, __webpack_require__) { var GetTileAt = __webpack_require__(134); var GetTilesWithin = __webpack_require__(21); var CalculateFacesWithin = function(tileX, tileY, width, height, layer) { var above = null; var below = null; var left = null; var right = null; var tiles = GetTilesWithin(tileX, tileY, width, height, null, layer); for (var i = 0; i < tiles.length; i++) { var tile = tiles[i]; if (tile) { if (tile.collides) { above = GetTileAt(tile.x, tile.y - 1, true, layer); below = GetTileAt(tile.x, tile.y + 1, true, layer); left = GetTileAt(tile.x - 1, tile.y, true, layer); right = GetTileAt(tile.x + 1, tile.y, true, layer); tile.faceTop = above && above.collides ? false : true; tile.faceBottom = below && below.collides ? false : true; tile.faceLeft = left && left.collides ? false : true; tile.faceRight = right && right.collides ? false : true } else { tile.resetFaces() } } } }; module.exports = CalculateFacesWithin }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var GetPoint = __webpack_require__(246); var GetPoints = __webpack_require__(147); var Random = __webpack_require__(148); var Vector2 = __webpack_require__(3); var Line = new Class({ initialize: function Line(x1, y1, x2, y2) { if (x1 === undefined) { x1 = 0 } if (y1 === undefined) { y1 = 0 } if (x2 === undefined) { x2 = 0 } if (y2 === undefined) { y2 = 0 } this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2 }, getPoint: function(position, output) { return GetPoint(this, position, output) }, getPoints: function(quantity, stepRate, output) { return GetPoints(this, quantity, stepRate, output) }, getRandomPoint: function(point) { return Random(this, point) }, setTo: function(x1, y1, x2, y2) { if (x1 === undefined) { x1 = 0 } if (y1 === undefined) { y1 = 0 } if (x2 === undefined) { x2 = 0 } if (y2 === undefined) { y2 = 0 } this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; return this }, getPointA: function(vec2) { if (vec2 === undefined) { vec2 = new Vector2 } vec2.set(this.x1, this.y1); return vec2 }, getPointB: function(vec2) { if (vec2 === undefined) { vec2 = new Vector2 } vec2.set(this.x2, this.y2); return vec2 }, left: { get: function() { return Math.min(this.x1, this.x2) }, set: function(value) { if (this.x1 <= this.x2) { this.x1 = value } else { this.x2 = value } } }, right: { get: function() { return Math.max(this.x1, this.x2) }, set: function(value) { if (this.x1 > this.x2) { this.x1 = value } else { this.x2 = value } } }, top: { get: function() { return Math.min(this.y1, this.y2) }, set: function(value) { if (this.y1 <= this.y2) { this.y1 = value } else { this.y2 = value } } }, bottom: { get: function() { return Math.max(this.y1, this.y2) }, set: function(value) { if (this.y1 > this.y2) { this.y1 = value } else { this.y2 = value } } } }); module.exports = Line }, function(module, exports) { var Wrap = function(value, min, max) { var range = max - min; return min + ((value - min) % range + range) % range }; module.exports = Wrap }, function(module, exports) { var DistanceBetween = function(x1, y1, x2, y2) { var dx = x1 - x2; var dy = y1 - y2; return Math.sqrt(dx * dx + dy * dy) }; module.exports = DistanceBetween }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var CONST = __webpack_require__(20); var File = __webpack_require__(22); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(1); var GetValue = __webpack_require__(4); var IsPlainObject = __webpack_require__(7); var JSONFile = new Class({ Extends: File, initialize: function JSONFile(loader, key, url, xhrSettings, dataKey) { var extension = "json"; if (IsPlainObject(key)) { var config = key; key = GetFastValue(config, "key"); url = GetFastValue(config, "url"); xhrSettings = GetFastValue(config, "xhrSettings"); extension = GetFastValue(config, "extension", extension); dataKey = GetFastValue(config, "dataKey", dataKey) } var fileConfig = { type: "json", cache: loader.cacheManager.json, extension: extension, responseType: "text", key: key, url: url, xhrSettings: xhrSettings, config: dataKey }; File.call(this, loader, fileConfig); if (IsPlainObject(url)) { if (dataKey) { this.data = GetValue(url, dataKey) } else { this.data = url } this.state = CONST.FILE_POPULATED } }, onProcess: function() { if (this.state !== CONST.FILE_POPULATED) { this.state = CONST.FILE_PROCESSING; var json = JSON.parse(this.xhrLoader.responseText); var key = this.config; if (typeof key === "string") { this.data = GetValue(json, key, json) } else { this.data = json } } this.onProcessComplete() } }); FileTypesManager.register("json", function(key, url, dataKey, xhrSettings) { if (Array.isArray(key)) { for (var i = 0; i < key.length; i++) { this.addFile(new JSONFile(this, key[i])) } } else { this.addFile(new JSONFile(this, key, url, xhrSettings, dataKey)) } return this }); module.exports = JSONFile }, function(module, exports, __webpack_require__) { var Bodies = {}; module.exports = Bodies; var Vertices = __webpack_require__(32); var Common = __webpack_require__(17); var Body = __webpack_require__(25); var Bounds = __webpack_require__(34); var Vector = __webpack_require__(33); var decomp = __webpack_require__(437); (function() { Bodies.rectangle = function(x, y, width, height, options) { options = options || {}; var rectangle = { label: "Rectangle Body", position: { x: x, y: y }, vertices: Vertices.fromPath("L 0 0 L " + width + " 0 L " + width + " " + height + " L 0 " + height) }; if (options.chamfer) { var chamfer = options.chamfer; rectangle.vertices = Vertices.chamfer(rectangle.vertices, chamfer.radius, chamfer.quality, chamfer.qualityMin, chamfer.qualityMax); delete options.chamfer } return Body.create(Common.extend({}, rectangle, options)) }; Bodies.trapezoid = function(x, y, width, height, slope, options) { options = options || {}; slope *= .5; var roof = (1 - slope * 2) * width; var x1 = width * slope, x2 = x1 + roof, x3 = x2 + x1, verticesPath; if (slope < .5) { verticesPath = "L 0 0 L " + x1 + " " + -height + " L " + x2 + " " + -height + " L " + x3 + " 0" } else { verticesPath = "L 0 0 L " + x2 + " " + -height + " L " + x3 + " 0" } var trapezoid = { label: "Trapezoid Body", position: { x: x, y: y }, vertices: Vertices.fromPath(verticesPath) }; if (options.chamfer) { var chamfer = options.chamfer; trapezoid.vertices = Vertices.chamfer(trapezoid.vertices, chamfer.radius, chamfer.quality, chamfer.qualityMin, chamfer.qualityMax); delete options.chamfer } return Body.create(Common.extend({}, trapezoid, options)) }; Bodies.circle = function(x, y, radius, options, maxSides) { options = options || {}; var circle = { label: "Circle Body", circleRadius: radius }; maxSides = maxSides || 25; var sides = Math.ceil(Math.max(10, Math.min(maxSides, radius))); if (sides % 2 === 1) sides += 1; return Bodies.polygon(x, y, sides, radius, Common.extend({}, circle, options)) }; Bodies.polygon = function(x, y, sides, radius, options) { options = options || {}; if (sides < 3) return Bodies.circle(x, y, radius, options); var theta = 2 * Math.PI / sides, path = "", offset = theta * .5; for (var i = 0; i < sides; i += 1) { var angle = offset + i * theta, xx = Math.cos(angle) * radius, yy = Math.sin(angle) * radius; path += "L " + xx.toFixed(3) + " " + yy.toFixed(3) + " " } var polygon = { label: "Polygon Body", position: { x: x, y: y }, vertices: Vertices.fromPath(path) }; if (options.chamfer) { var chamfer = options.chamfer; polygon.vertices = Vertices.chamfer(polygon.vertices, chamfer.radius, chamfer.quality, chamfer.qualityMin, chamfer.qualityMax); delete options.chamfer } return Body.create(Common.extend({}, polygon, options)) }; Bodies.fromVertices = function(x, y, vertexSets, options, flagInternal, removeCollinear, minimumArea) { var body, parts, isConvex, vertices, i, j, k, v, z; options = options || {}; parts = []; flagInternal = typeof flagInternal !== "undefined" ? flagInternal : false; removeCollinear = typeof removeCollinear !== "undefined" ? removeCollinear : .01; minimumArea = typeof minimumArea !== "undefined" ? minimumArea : 10; if (!decomp) { Common.warn("Bodies.fromVertices: poly-decomp.js required. Could not decompose vertices. Fallback to convex hull.") } if (!Common.isArray(vertexSets[0])) { vertexSets = [vertexSets] } for (v = 0; v < vertexSets.length; v += 1) { vertices = vertexSets[v]; isConvex = Vertices.isConvex(vertices); if (isConvex || !decomp) { if (isConvex) { vertices = Vertices.clockwiseSort(vertices) } else { vertices = Vertices.hull(vertices) } parts.push({ position: { x: x, y: y }, vertices: vertices }) } else { var concave = vertices.map(function(vertex) { return [vertex.x, vertex.y] }); decomp.makeCCW(concave); if (removeCollinear !== false) decomp.removeCollinearPoints(concave, removeCollinear); var decomposed = decomp.quickDecomp(concave); for (i = 0; i < decomposed.length; i++) { var chunk = decomposed[i]; var chunkVertices = chunk.map(function(vertices) { return { x: vertices[0], y: vertices[1] } }); if (minimumArea > 0 && Vertices.area(chunkVertices) < minimumArea) continue; parts.push({ position: Vertices.centre(chunkVertices), vertices: chunkVertices }) } } } for (i = 0; i < parts.length; i++) { parts[i] = Body.create(Common.extend(parts[i], options)) } if (flagInternal) { var coincident_max_dist = 5; for (i = 0; i < parts.length; i++) { var partA = parts[i]; for (j = i + 1; j < parts.length; j++) { var partB = parts[j]; if (Bounds.overlaps(partA.bounds, partB.bounds)) { var pav = partA.vertices, pbv = partB.vertices; for (k = 0; k < partA.vertices.length; k++) { for (z = 0; z < partB.vertices.length; z++) { var da = Vector.magnitudeSquared(Vector.sub(pav[(k + 1) % pav.length], pbv[z])), db = Vector.magnitudeSquared(Vector.sub(pav[k], pbv[(z + 1) % pbv.length])); if (da < coincident_max_dist && db < coincident_max_dist) { pav[k].isInternal = true; pbv[z].isInternal = true } } } } } } } if (parts.length > 1) { body = Body.create(Common.extend({ parts: parts.slice(0) }, options)); Body.setPosition(body, { x: x, y: y }); return body } else { return parts[0] } } })() }, function(module, exports) { var WorldToTileX = function(worldX, snapToFloor, camera, layer) { if (snapToFloor === undefined) { snapToFloor = true } var tileWidth = layer.baseTileWidth; var tilemapLayer = layer.tilemapLayer; if (tilemapLayer) { if (camera === undefined) { camera = tilemapLayer.scene.cameras.main } worldX = worldX - (tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX)); tileWidth *= tilemapLayer.scaleX } return snapToFloor ? Math.floor(worldX / tileWidth) : worldX / tileWidth }; module.exports = WorldToTileX }, function(module, exports) { var WorldToTileY = function(worldY, snapToFloor, camera, layer) { if (snapToFloor === undefined) { snapToFloor = true } var tileHeight = layer.baseTileHeight; var tilemapLayer = layer.tilemapLayer; if (tilemapLayer) { if (camera === undefined) { camera = tilemapLayer.scene.cameras.main } worldY = worldY - (tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY)); tileHeight *= tilemapLayer.scaleY } return snapToFloor ? Math.floor(worldY / tileHeight) : worldY / tileHeight }; module.exports = WorldToTileY }, function(module, exports) { module.exports = { SKIP_CHECK: -1, NORMAL: 0, ADD: 1, MULTIPLY: 2, SCREEN: 3, OVERLAY: 4, DARKEN: 5, LIGHTEN: 6, COLOR_DODGE: 7, COLOR_BURN: 8, HARD_LIGHT: 9, SOFT_LIGHT: 10, DIFFERENCE: 11, EXCLUSION: 12, HUE: 13, SATURATION: 14, COLOR: 15, LUMINOSITY: 16 } }, function(module, exports) { var Length = function(line) { return Math.sqrt((line.x2 - line.x1) * (line.x2 - line.x1) + (line.y2 - line.y1) * (line.y2 - line.y1)) }; module.exports = Length }, function(module, exports, __webpack_require__) { "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; if (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]; if (x < minX) minX = x; if (y < minY) minY = y; if (x > maxX) maxX = x; if (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; if (!end) end = start; var p = start, again; do { again = false; if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { removeNode(p); p = end = p.prev; if (p === p.next) return null; again = true } else { p = p.next } } while (again || p !== end); return end } function earcutLinked(ear, triangles, dim, minX, minY, size, pass) { if (!ear) return; if (!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) { earcutLinked(filterPoints(ear), triangles, dim, minX, minY, size, 1) } else if (pass === 1) { ear = cureLocalIntersections(ear, triangles, dim); earcutLinked(ear, triangles, dim, minX, minY, size, 2) } else if (pass === 2) { splitEarcut(ear, triangles, dim, minX, minY, size) } 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); if (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 && p.next.y !== p.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 && hx !== p.x && 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 { if (p.z === null) 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 (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) { e = p; p = p.nextZ; pSize-- } else { e = q; q = q.nextZ; qSize-- } if (tail) tail.nextZ = e; else 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 = (x | x << 8) & 16711935; x = (x | x << 4) & 252645135; x = (x | x << 2) & 858993459; x = (x | x << 1) & 1431655765; y = (y | y << 8) & 16711935; y = (y | y << 4) & 252645135; y = (y | y << 2) & 858993459; y = (y | y << 1) & 1431655765; return x | y << 1 } function getLeftmost(start) { var p = start, leftmost = start; do { if (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 { if (p.y > py !== p.next.y > py && p.next.y !== p.y && 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.prev = p; p.next = p } else { p.next = last.next; p.prev = last; last.next.prev = p; last.next = p } return p } function removeNode(p) { p.next.prev = p.prev; p.prev.next = p.next; if (p.prevZ) p.prevZ.nextZ = p.nextZ; if (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 polygonArea === 0 && trianglesArea === 0 ? 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 } }, function(module, exports) { var Clone = function(obj) { var clone = {}; for (var key in obj) { if (Array.isArray(obj[key])) { clone[key] = obj[key].slice(0) } else { clone[key] = obj[key] } } return clone }; module.exports = Clone }, function(module, exports) { var SafeRange = function(array, startIndex, endIndex, throwError) { var len = array.length; if (startIndex < 0 || startIndex > len || startIndex >= endIndex || endIndex > len || startIndex + endIndex > len) { if (throwError) { throw new Error("Range Error: Values outside acceptable range") } return false } else { return true } }; module.exports = SafeRange }, function(module, exports, __webpack_require__) { var Utils = __webpack_require__(10); var StrokePathWebGL = function(pipeline, src, alpha, dx, dy) { var strokeTint = pipeline.strokeTint; var strokeTintColor = Utils.getTintAppendFloatAlphaAndSwap(src.strokeColor, src.strokeAlpha * alpha); strokeTint.TL = strokeTintColor; strokeTint.TR = strokeTintColor; strokeTint.BL = strokeTintColor; strokeTint.BR = strokeTintColor; var path = src.pathData; var pathLength = path.length - 1; var lineWidth = src.lineWidth; var halfLineWidth = lineWidth / 2; var px1 = path[0] - dx; var py1 = path[1] - dy; if (!src.closePath) { pathLength -= 2 } for (var i = 2; i < pathLength; i += 2) { var px2 = path[i] - dx; var py2 = path[i + 1] - dy; pipeline.setTexture2D(); pipeline.batchLine(px1, py1, px2, py2, halfLineWidth, halfLineWidth, lineWidth, i - 2, src.closePath ? i === pathLength - 1 : false); px1 = px2; py1 = py2 } }; module.exports = StrokePathWebGL }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Contains = __webpack_require__(84); var GetPoint = __webpack_require__(371); var GetPoints = __webpack_require__(372); var Line = __webpack_require__(54); var Random = __webpack_require__(153); var Triangle = new Class({ initialize: function Triangle(x1, y1, x2, y2, x3, y3) { if (x1 === undefined) { x1 = 0 } if (y1 === undefined) { y1 = 0 } if (x2 === undefined) { x2 = 0 } if (y2 === undefined) { y2 = 0 } if (x3 === undefined) { x3 = 0 } if (y3 === undefined) { y3 = 0 } this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; this.x3 = x3; this.y3 = y3 }, contains: function(x, y) { return Contains(this, x, y) }, getPoint: function(position, output) { return GetPoint(this, position, output) }, getPoints: function(quantity, stepRate, output) { return GetPoints(this, quantity, stepRate, output) }, getRandomPoint: function(point) { return Random(this, point) }, setTo: function(x1, y1, x2, y2, x3, y3) { if (x1 === undefined) { x1 = 0 } if (y1 === undefined) { y1 = 0 } if (x2 === undefined) { x2 = 0 } if (y2 === undefined) { y2 = 0 } if (x3 === undefined) { x3 = 0 } if (y3 === undefined) { y3 = 0 } this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; this.x3 = x3; this.y3 = y3; return this }, getLineA: function(line) { if (line === undefined) { line = new Line } line.setTo(this.x1, this.y1, this.x2, this.y2); return line }, getLineB: function(line) { if (line === undefined) { line = new Line } line.setTo(this.x2, this.y2, this.x3, this.y3); return line }, getLineC: function(line) { if (line === undefined) { line = new Line } line.setTo(this.x3, this.y3, this.x1, this.y1); return line }, left: { get: function() { return Math.min(this.x1, this.x2, this.x3) }, set: function(value) { var diff = 0; if (this.x1 <= this.x2 && this.x1 <= this.x3) { diff = this.x1 - value } else if (this.x2 <= this.x1 && this.x2 <= this.x3) { diff = this.x2 - value } else { diff = this.x3 - value } this.x1 -= diff; this.x2 -= diff; this.x3 -= diff } }, right: { get: function() { return Math.max(this.x1, this.x2, this.x3) }, set: function(value) { var diff = 0; if (this.x1 >= this.x2 && this.x1 >= this.x3) { diff = this.x1 - value } else if (this.x2 >= this.x1 && this.x2 >= this.x3) { diff = this.x2 - value } else { diff = this.x3 - value } this.x1 -= diff; this.x2 -= diff; this.x3 -= diff } }, top: { get: function() { return Math.min(this.y1, this.y2, this.y3) }, set: function(value) { var diff = 0; if (this.y1 <= this.y2 && this.y1 <= this.y3) { diff = this.y1 - value } else if (this.y2 <= this.y1 && this.y2 <= this.y3) { diff = this.y2 - value } else { diff = this.y3 - value } this.y1 -= diff; this.y2 -= diff; this.y3 -= diff } }, bottom: { get: function() { return Math.max(this.y1, this.y2, this.y3) }, set: function(value) { var diff = 0; if (this.y1 >= this.y2 && this.y1 >= this.y3) { diff = this.y1 - value } else if (this.y2 >= this.y1 && this.y2 >= this.y3) { diff = this.y2 - value } else { diff = this.y3 - value } this.y1 -= diff; this.y2 -= diff; this.y3 -= diff } } }); module.exports = Triangle }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var CONST = __webpack_require__(20); var File = __webpack_require__(22); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(1); var IsPlainObject = __webpack_require__(7); var ImageFile = new Class({ Extends: File, initialize: function ImageFile(loader, key, url, xhrSettings, frameConfig) { var extension = "png"; var normalMapURL; if (IsPlainObject(key)) { var config = key; key = GetFastValue(config, "key"); url = GetFastValue(config, "url"); normalMapURL = GetFastValue(config, "normalMap"); xhrSettings = GetFastValue(config, "xhrSettings"); extension = GetFastValue(config, "extension", extension); frameConfig = GetFastValue(config, "frameConfig") } if (Array.isArray(url)) { normalMapURL = url[1]; url = url[0] } var fileConfig = { type: "image", cache: loader.textureManager, extension: extension, responseType: "blob", key: key, url: url, xhrSettings: xhrSettings, config: frameConfig }; File.call(this, loader, fileConfig); if (normalMapURL) { var normalMap = new ImageFile(loader, this.key, normalMapURL, xhrSettings, frameConfig); normalMap.type = "normalMap"; this.setLink(normalMap); loader.addFile(normalMap) } }, onProcess: function() { this.state = CONST.FILE_PROCESSING; this.data = new Image; this.data.crossOrigin = this.crossOrigin; var _this = this; this.data.onload = function() { File.revokeObjectURL(_this.data); _this.onProcessComplete() }; this.data.onerror = function() { File.revokeObjectURL(_this.data); _this.onProcessError() }; File.createObjectURL(this.data, this.xhrLoader.response, "image/png") }, addToCache: function() { var texture; var linkFile = this.linkFile; if (linkFile && linkFile.state === CONST.FILE_COMPLETE) { if (this.type === "image") { texture = this.cache.addImage(this.key, this.data, linkFile.data) } else { texture = this.cache.addImage(linkFile.key, linkFile.data, this.data) } this.pendingDestroy(texture); linkFile.pendingDestroy(texture) } else if (!linkFile) { texture = this.cache.addImage(this.key, this.data); this.pendingDestroy(texture) } } }); FileTypesManager.register("image", function(key, url, xhrSettings) { if (Array.isArray(key)) { for (var i = 0; i < key.length; i++) { this.addFile(new ImageFile(this, key[i])) } } else { this.addFile(new ImageFile(this, key, url, xhrSettings)) } return this }); module.exports = ImageFile }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var MultiFile = new Class({ initialize: function MultiFile(loader, type, key, files) { this.loader = loader; this.type = type; this.key = key; this.files = files; this.complete = false; this.pending = files.length; this.failed = 0; this.config = {}; for (var i = 0; i < files.length; i++) { files[i].multiFile = this } }, isReadyToProcess: function() { return this.pending === 0 && this.failed === 0 && !this.complete }, addToMultiFile: function(file) { this.files.push(file); file.multiFile = this; this.pending++; this.complete = false; return this }, onFileComplete: function(file) { var index = this.files.indexOf(file); if (index !== -1) { this.pending-- } }, onFileFailed: function(file) { var index = this.files.indexOf(file); if (index !== -1) { this.failed++ } } }); module.exports = MultiFile }, function(module, exports, __webpack_require__) { var Composite = {}; module.exports = Composite; var Events = __webpack_require__(87); var Common = __webpack_require__(17); var Bounds = __webpack_require__(34); var Body = __webpack_require__(25); (function() { Composite.create = function(options) { return Common.extend({ id: Common.nextId(), type: "composite", parent: null, isModified: false, bodies: [], constraints: [], composites: [], label: "Composite", plugin: {} }, options) }; Composite.setModified = function(composite, isModified, updateParents, updateChildren) { composite.isModified = isModified; if (updateParents && composite.parent) { Composite.setModified(composite.parent, isModified, updateParents, updateChildren) } if (updateChildren) { for (var i = 0; i < composite.composites.length; i++) { var childComposite = composite.composites[i]; Composite.setModified(childComposite, isModified, updateParents, updateChildren) } } }; Composite.add = function(composite, object) { var objects = [].concat(object); Events.trigger(composite, "beforeAdd", { object: object }); for (var i = 0; i < objects.length; i++) { var obj = objects[i]; switch (obj.type) { case "body": if (obj.parent !== obj) { Common.warn("Composite.add: skipped adding a compound body part (you must add its parent instead)"); break } Composite.addBody(composite, obj); break; case "constraint": Composite.addConstraint(composite, obj); break; case "composite": Composite.addComposite(composite, obj); break; case "mouseConstraint": Composite.addConstraint(composite, obj.constraint); break } } Events.trigger(composite, "afterAdd", { object: object }); return composite }; Composite.remove = function(composite, object, deep) { var objects = [].concat(object); Events.trigger(composite, "beforeRemove", { object: object }); for (var i = 0; i < objects.length; i++) { var obj = objects[i]; switch (obj.type) { case "body": Composite.removeBody(composite, obj, deep); break; case "constraint": Composite.removeConstraint(composite, obj, deep); break; case "composite": Composite.removeComposite(composite, obj, deep); break; case "mouseConstraint": Composite.removeConstraint(composite, obj.constraint); break } } Events.trigger(composite, "afterRemove", { object: object }); return composite }; Composite.addComposite = function(compositeA, compositeB) { compositeA.composites.push(compositeB); compositeB.parent = compositeA; Composite.setModified(compositeA, true, true, false); return compositeA }; Composite.removeComposite = function(compositeA, compositeB, deep) { var position = compositeA.composites.indexOf(compositeB); if (position !== -1) { Composite.removeCompositeAt(compositeA, position); Composite.setModified(compositeA, true, true, false) } if (deep) { for (var i = 0; i < compositeA.composites.length; i++) { Composite.removeComposite(compositeA.composites[i], compositeB, true) } } return compositeA }; Composite.removeCompositeAt = function(composite, position) { composite.composites.splice(position, 1); Composite.setModified(composite, true, true, false); return composite }; Composite.addBody = function(composite, body) { composite.bodies.push(body); Composite.setModified(composite, true, true, false); return composite }; Composite.removeBody = function(composite, body, deep) { var position = composite.bodies.indexOf(body); if (position !== -1) { Composite.removeBodyAt(composite, position); Composite.setModified(composite, true, true, false) } if (deep) { for (var i = 0; i < composite.composites.length; i++) { Composite.removeBody(composite.composites[i], body, true) } } return composite }; Composite.removeBodyAt = function(composite, position) { composite.bodies.splice(position, 1); Composite.setModified(composite, true, true, false); return composite }; Composite.addConstraint = function(composite, constraint) { composite.constraints.push(constraint); Composite.setModified(composite, true, true, false); return composite }; Composite.removeConstraint = function(composite, constraint, deep) { var position = composite.constraints.indexOf(constraint); if (position !== -1) { Composite.removeConstraintAt(composite, position) } if (deep) { for (var i = 0; i < composite.composites.length; i++) { Composite.removeConstraint(composite.composites[i], constraint, true) } } return composite }; Composite.removeConstraintAt = function(composite, position) { composite.constraints.splice(position, 1); Composite.setModified(composite, true, true, false); return composite }; Composite.clear = function(composite, keepStatic, deep) { if (deep) { for (var i = 0; i < composite.composites.length; i++) { Composite.clear(composite.composites[i], keepStatic, true) } } if (keepStatic) { composite.bodies = composite.bodies.filter(function(body) { return body.isStatic }) } else { composite.bodies.length = 0 } composite.constraints.length = 0; composite.composites.length = 0; Composite.setModified(composite, true, true, false); return composite }; Composite.allBodies = function(composite) { var bodies = [].concat(composite.bodies); for (var i = 0; i < composite.composites.length; i++) bodies = bodies.concat(Composite.allBodies(composite.composites[i])); return bodies }; Composite.allConstraints = function(composite) { var constraints = [].concat(composite.constraints); for (var i = 0; i < composite.composites.length; i++) constraints = constraints.concat(Composite.allConstraints(composite.composites[i])); return constraints }; Composite.allComposites = function(composite) { var composites = [].concat(composite.composites); for (var i = 0; i < composite.composites.length; i++) composites = composites.concat(Composite.allComposites(composite.composites[i])); return composites }; Composite.get = function(composite, id, type) { var objects, object; switch (type) { case "body": objects = Composite.allBodies(composite); break; case "constraint": objects = Composite.allConstraints(composite); break; case "composite": objects = Composite.allComposites(composite).concat(composite); break } if (!objects) return null; object = objects.filter(function(object) { return object.id.toString() === id.toString() }); return object.length === 0 ? null : object[0] }; Composite.move = function(compositeA, objects, compositeB) { Composite.remove(compositeA, objects); Composite.add(compositeB, objects); return compositeA }; Composite.rebase = function(composite) { var objects = Composite.allBodies(composite).concat(Composite.allConstraints(composite)).concat(Composite.allComposites(composite)); for (var i = 0; i < objects.length; i++) { objects[i].id = Common.nextId() } Composite.setModified(composite, true, true, false); return composite }; Composite.translate = function(composite, translation, recursive) { var bodies = recursive ? Composite.allBodies(composite) : composite.bodies; for (var i = 0; i < bodies.length; i++) { Body.translate(bodies[i], translation) } Composite.setModified(composite, true, true, false); return composite }; Composite.rotate = function(composite, rotation, point, recursive) { var cos = Math.cos(rotation), sin = Math.sin(rotation), bodies = recursive ? Composite.allBodies(composite) : composite.bodies; for (var i = 0; i < bodies.length; i++) { var body = bodies[i], dx = body.position.x - point.x, dy = body.position.y - point.y; Body.setPosition(body, { x: point.x + (dx * cos - dy * sin), y: point.y + (dx * sin + dy * cos) }); Body.rotate(body, rotation) } Composite.setModified(composite, true, true, false); return composite }; Composite.scale = function(composite, scaleX, scaleY, point, recursive) { var bodies = recursive ? Composite.allBodies(composite) : composite.bodies; for (var i = 0; i < bodies.length; i++) { var body = bodies[i], dx = body.position.x - point.x, dy = body.position.y - point.y; Body.setPosition(body, { x: point.x + dx * scaleX, y: point.y + dy * scaleY }); Body.scale(body, scaleX, scaleY) } Composite.setModified(composite, true, true, false); return composite }; Composite.bounds = function(composite) { var bodies = Composite.allBodies(composite), vertices = []; for (var i = 0; i < bodies.length; i += 1) { var body = bodies[i]; vertices.push(body.bounds.min, body.bounds.max) } return Bounds.create(vertices) } })() }, function(module, exports) { var SetTileCollision = function(tile, collides) { if (collides) { tile.setCollision(true, true, true, true, false) } else { tile.resetCollision(false) } }; module.exports = SetTileCollision }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Components = __webpack_require__(14); var Rectangle = __webpack_require__(386); var Tile = new Class({ Mixins: [Components.Alpha, Components.Flip, Components.Visible], initialize: function Tile(layer, index, x, y, width, height, baseWidth, baseHeight) { this.layer = layer; this.index = index; this.x = x; this.y = y; this.width = width; this.height = height; this.baseWidth = baseWidth !== undefined ? baseWidth : width; this.baseHeight = baseHeight !== undefined ? baseHeight : height; this.pixelX = 0; this.pixelY = 0; this.updatePixelXY(); this.properties = {}; this.rotation = 0; this.collideLeft = false; this.collideRight = false; this.collideUp = false; this.collideDown = false; this.faceLeft = false; this.faceRight = false; this.faceTop = false; this.faceBottom = false; this.collisionCallback = null; this.collisionCallbackContext = this; this.tint = 16777215; this.physics = {} }, containsPoint: function(x, y) { return !(x < this.pixelX || y < this.pixelY || x > this.right || y > this.bottom) }, copy: function(tile) { this.index = tile.index; this.alpha = tile.alpha; this.properties = tile.properties; this.visible = tile.visible; this.setFlip(tile.flipX, tile.flipY); this.tint = tile.tint; this.rotation = tile.rotation; this.collideUp = tile.collideUp; this.collideDown = tile.collideDown; this.collideLeft = tile.collideLeft; this.collideRight = tile.collideRight; this.collisionCallback = tile.collisionCallback; this.collisionCallbackContext = tile.collisionCallbackContext; return this }, getCollisionGroup: function() { return this.tileset ? this.tileset.getTileCollisionGroup(this.index) : null }, getTileData: function() { return this.tileset ? this.tileset.getTileData(this.index) : null }, getLeft: function(camera) { var tilemapLayer = this.tilemapLayer; return tilemapLayer ? tilemapLayer.tileToWorldX(this.x, camera) : this.x * this.baseWidth }, getRight: function(camera) { var tilemapLayer = this.tilemapLayer; return tilemapLayer ? this.getLeft(camera) + this.width * tilemapLayer.scaleX : this.getLeft(camera) + this.width }, getTop: function(camera) { var tilemapLayer = this.tilemapLayer; return tilemapLayer ? tilemapLayer.tileToWorldY(this.y, camera) - (this.height - this.baseHeight) * tilemapLayer.scaleY : this.y * this.baseHeight - (this.height - this.baseHeight) }, getBottom: function(camera) { var tilemapLayer = this.tilemapLayer; return tilemapLayer ? this.getTop(camera) + this.height * tilemapLayer.scaleY : this.getTop(camera) + this.height }, getBounds: function(camera, output) { if (output === undefined) { output = new Rectangle } output.x = this.getLeft(); output.y = this.getTop(); output.width = this.getRight() - output.x; output.height = this.getBottom() - output.y; return output }, getCenterX: function(camera) { return this.getLeft(camera) + this.width / 2 }, getCenterY: function(camera) { return this.getTop(camera) + this.height / 2 }, destroy: function() { this.collisionCallback = undefined; this.collisionCallbackContext = undefined; this.properties = undefined }, intersects: function(x, y, right, bottom) { return !(right <= this.pixelX || bottom <= this.pixelY || x >= this.right || y >= this.bottom) }, isInteresting: function(collides, faces) { if (collides && faces) { return this.canCollide || this.hasInterestingFace } else if (collides) { return this.collides } else if (faces) { return this.hasInterestingFace } return false }, resetCollision: function(recalculateFaces) { if (recalculateFaces === undefined) { recalculateFaces = true } this.collideLeft = false; this.collideRight = false; this.collideUp = false; this.collideDown = false; this.faceTop = false; this.faceBottom = false; this.faceLeft = false; this.faceRight = false; if (recalculateFaces) { var tilemapLayer = this.tilemapLayer; if (tilemapLayer) { this.tilemapLayer.calculateFacesAt(this.x, this.y) } } return this }, resetFaces: function() { this.faceTop = false; this.faceBottom = false; this.faceLeft = false; this.faceRight = false; return this }, setCollision: function(left, right, up, down, recalculateFaces) { if (right === undefined) { right = left } if (up === undefined) { up = left } if (down === undefined) { down = left } if (recalculateFaces === undefined) { recalculateFaces = true } this.collideLeft = left; this.collideRight = right; this.collideUp = up; this.collideDown = down; this.faceLeft = left; this.faceRight = right; this.faceTop = up; this.faceBottom = down; if (recalculateFaces) { var tilemapLayer = this.tilemapLayer; if (tilemapLayer) { this.tilemapLayer.calculateFacesAt(this.x, this.y) } } return this }, setCollisionCallback: function(callback, context) { if (callback === null) { this.collisionCallback = undefined; this.collisionCallbackContext = undefined } else { this.collisionCallback = callback; this.collisionCallbackContext = context } return this }, setSize: function(tileWidth, tileHeight, baseWidth, baseHeight) { if (tileWidth !== undefined) { this.width = tileWidth } if (tileHeight !== undefined) { this.height = tileHeight } if (baseWidth !== undefined) { this.baseWidth = baseWidth } if (baseHeight !== undefined) { this.baseHeight = baseHeight } this.updatePixelXY(); return this }, updatePixelXY: function() { this.pixelX = this.x * this.baseWidth; this.pixelY = this.y * this.baseHeight - (this.height - this.baseHeight); return this }, canCollide: { get: function() { return this.collideLeft || this.collideRight || this.collideUp || this.collideDown || this.collisionCallback } }, collides: { get: function() { return this.collideLeft || this.collideRight || this.collideUp || this.collideDown } }, hasInterestingFace: { get: function() { return this.faceTop || this.faceBottom || this.faceLeft || this.faceRight } }, tileset: { get: function() { var tilemapLayer = this.tilemapLayer; return tilemapLayer ? tilemapLayer.tileset : null } }, tilemapLayer: { get: function() { return this.layer.tilemapLayer } }, tilemap: { get: function() { var tilemapLayer = this.tilemapLayer; return tilemapLayer ? tilemapLayer.tilemap : null } } }); module.exports = Tile }, , function(module, exports) { var GetCenterX = function(gameObject) { return gameObject.x - gameObject.width * gameObject.originX + gameObject.width * .5 }; module.exports = GetCenterX }, function(module, exports) { var SetCenterX = function(gameObject, x) { var offsetX = gameObject.width * gameObject.originX; gameObject.x = x + offsetX - gameObject.width * .5; return gameObject }; module.exports = SetCenterX }, function(module, exports) { var SetCenterY = function(gameObject, y) { var offsetY = gameObject.height * gameObject.originY; gameObject.y = y + offsetY - gameObject.height * .5; return gameObject }; module.exports = SetCenterY }, function(module, exports) { var GetCenterY = function(gameObject) { return gameObject.y - gameObject.height * gameObject.originY + gameObject.height * .5 }; module.exports = GetCenterY }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Contains = __webpack_require__(46); var GetPoint = __webpack_require__(237); var GetPoints = __webpack_require__(239); var Random = __webpack_require__(145); var Circle = new Class({ initialize: function Circle(x, y, radius) { if (x === undefined) { x = 0 } if (y === undefined) { y = 0 } if (radius === undefined) { radius = 0 } this.x = x; this.y = y; this._radius = radius; this._diameter = radius * 2 }, contains: function(x, y) { return Contains(this, x, y) }, getPoint: function(position, point) { return GetPoint(this, position, point) }, getPoints: function(quantity, stepRate, output) { return GetPoints(this, quantity, stepRate, output) }, getRandomPoint: function(point) { return Random(this, point) }, setTo: function(x, y, radius) { this.x = x; this.y = y; this._radius = radius; this._diameter = radius * 2; return this }, setEmpty: function() { this._radius = 0; this._diameter = 0; return this }, setPosition: function(x, y) { if (y === undefined) { y = x } this.x = x; this.y = y; return this }, isEmpty: function() { return this._radius <= 0 }, radius: { get: function() { return this._radius }, set: function(value) { this._radius = value; this._diameter = value * 2 } }, diameter: { get: function() { return this._diameter }, set: function(value) { this._diameter = value; this._radius = value * .5 } }, left: { get: function() { return this.x - this._radius }, set: function(value) { this.x = value + this._radius } }, right: { get: function() { return this.x + this._radius }, set: function(value) { this.x = value - this._radius } }, top: { get: function() { return this.y - this._radius }, set: function(value) { this.y = value + this._radius } }, bottom: { get: function() { return this.y + this._radius }, set: function(value) { this.y = value - this._radius } } }); module.exports = Circle }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var FromPoints = __webpack_require__(164); var Rectangle = __webpack_require__(9); var Vector2 = __webpack_require__(3); var Curve = new Class({ initialize: function Curve(type) { this.type = type; this.defaultDivisions = 5; this.arcLengthDivisions = 100; this.cacheArcLengths = []; this.needsUpdate = true; this.active = true; this._tmpVec2A = new Vector2; this._tmpVec2B = new Vector2 }, draw: function(graphics, pointsTotal) { if (pointsTotal === undefined) { pointsTotal = 32 } return graphics.strokePoints(this.getPoints(pointsTotal)) }, getBounds: function(out, accuracy) { if (!out) { out = new Rectangle } if (accuracy === undefined) { accuracy = 16 } var len = this.getLength(); if (accuracy > len) { accuracy = len / 2 } var spaced = Math.max(1, Math.round(len / accuracy)); return FromPoints(this.getSpacedPoints(spaced), out) }, getDistancePoints: function(distance) { var len = this.getLength(); var spaced = Math.max(1, len / distance); return this.getSpacedPoints(spaced) }, getEndPoint: function(out) { if (out === undefined) { out = new Vector2 } return this.getPointAt(1, out) }, getLength: function() { var lengths = this.getLengths(); return lengths[lengths.length - 1] }, getLengths: function(divisions) { if (divisions === undefined) { divisions = this.arcLengthDivisions } if (this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) { return this.cacheArcLengths } this.needsUpdate = false; var cache = []; var current; var last = this.getPoint(0, this._tmpVec2A); var sum = 0; cache.push(0); for (var p = 1; p <= divisions; p++) { current = this.getPoint(p / divisions, this._tmpVec2B); sum += current.distance(last); cache.push(sum); last.copy(current) } this.cacheArcLengths = cache; return cache }, getPointAt: function(u, out) { var t = this.getUtoTmapping(u); return this.getPoint(t, out) }, getPoints: function(divisions) { if (divisions === undefined) { divisions = this.defaultDivisions } var points = []; for (var d = 0; d <= divisions; d++) { points.push(this.getPoint(d / divisions)) } return points }, getRandomPoint: function(out) { if (out === undefined) { out = new Vector2 } return this.getPoint(Math.random(), out) }, getSpacedPoints: function(divisions) { if (divisions === undefined) { divisions = this.defaultDivisions } var points = []; for (var d = 0; d <= divisions; d++) { var t = this.getUtoTmapping(d / divisions, null, divisions); points.push(this.getPoint(t)) } return points }, getStartPoint: function(out) { if (out === undefined) { out = new Vector2 } return this.getPointAt(0, out) }, getTangent: function(t, out) { if (out === undefined) { out = new Vector2 } var delta = 1e-4; var t1 = t - delta; var t2 = t + delta; if (t1 < 0) { t1 = 0 } if (t2 > 1) { t2 = 1 } this.getPoint(t1, this._tmpVec2A); this.getPoint(t2, out); return out.subtract(this._tmpVec2A).normalize() }, getTangentAt: function(u, out) { var t = this.getUtoTmapping(u); return this.getTangent(t, out) }, getTFromDistance: function(distance, divisions) { if (distance <= 0) { return 0 } return this.getUtoTmapping(0, distance, divisions) }, getUtoTmapping: function(u, distance, divisions) { var arcLengths = this.getLengths(divisions); var i = 0; var il = arcLengths.length; var targetArcLength; if (distance) { targetArcLength = Math.min(distance, arcLengths[il - 1]) } else { targetArcLength = u * arcLengths[il - 1] } var low = 0; var high = il - 1; var comparison; while (low <= high) { i = Math.floor(low + (high - low) / 2); comparison = arcLengths[i] - targetArcLength; if (comparison < 0) { low = i + 1 } else if (comparison > 0) { high = i - 1 } else { high = i; break } } i = high; if (arcLengths[i] === targetArcLength) { return i / (il - 1) } var lengthBefore = arcLengths[i]; var lengthAfter = arcLengths[i + 1]; var segmentLength = lengthAfter - lengthBefore; var segmentFraction = (targetArcLength - lengthBefore) / segmentLength; return (i + segmentFraction) / (il - 1) }, updateArcLengths: function() { this.needsUpdate = true; this.getLengths() } }); module.exports = Curve }, function(module, exports, __webpack_require__) { var Clone = __webpack_require__(64); var Merge = function(obj1, obj2) { var clone = Clone(obj1); for (var key in obj2) { if (!clone.hasOwnProperty(key)) { clone[key] = obj2[key] } } return clone }; module.exports = Merge }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Set = new Class({ initialize: function Set(elements) { this.entries = []; if (Array.isArray(elements)) { for (var i = 0; i < elements.length; i++) { this.set(elements[i]) } } }, set: function(value) { if (this.entries.indexOf(value) === -1) { this.entries.push(value) } return this }, get: function(property, value) { for (var i = 0; i < this.entries.length; i++) { var entry = this.entries[i]; if (entry[property] === value) { return entry } } }, getArray: function() { return this.entries.slice(0) }, delete: function(value) { var index = this.entries.indexOf(value); if (index > -1) { this.entries.splice(index, 1) } return this }, dump: function() { console.group("Set"); for (var i = 0; i < this.entries.length; i++) { var entry = this.entries[i]; console.log(entry) } console.groupEnd() }, each: function(callback, callbackScope) { var i; var temp = this.entries.slice(); var len = temp.length; if (callbackScope) { for (i = 0; i < len; i++) { if (callback.call(callbackScope, temp[i], i) === false) { break } } } else { for (i = 0; i < len; i++) { if (callback(temp[i], i) === false) { break } } } return this }, iterate: function(callback, callbackScope) { var i; var len = this.entries.length; if (callbackScope) { for (i = 0; i < len; i++) { if (callback.call(callbackScope, this.entries[i], i) === false) { break } } } else { for (i = 0; i < len; i++) { if (callback(this.entries[i], i) === false) { break } } } return this }, iterateLocal: function(callbackKey) { var i; var args = []; for (i = 1; i < arguments.length; i++) { args.push(arguments[i]) } var len = this.entries.length; for (i = 0; i < len; i++) { var entry = this.entries[i]; entry[callbackKey].apply(entry, args) } return this }, clear: function() { this.entries.length = 0; return this }, contains: function(value) { return this.entries.indexOf(value) > -1 }, union: function(set) { var newSet = new Set; set.entries.forEach(function(value) { newSet.set(value) }); this.entries.forEach(function(value) { newSet.set(value) }); return newSet }, intersect: function(set) { var newSet = new Set; this.entries.forEach(function(value) { if (set.contains(value)) { newSet.set(value) } }); return newSet }, difference: function(set) { var newSet = new Set; this.entries.forEach(function(value) { if (!set.contains(value)) { newSet.set(value) } }); return newSet }, size: { get: function() { return this.entries.length }, set: function(value) { if (value < this.entries.length) { return this.entries.length = value } else { return this.entries.length } } } }); module.exports = Set }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Components = __webpack_require__(14); var GameObject = __webpack_require__(12); var ImageRender = __webpack_require__(714); var Image = new Class({ Extends: GameObject, Mixins: [Components.Alpha, Components.BlendMode, Components.Depth, Components.Flip, Components.GetBounds, Components.Mask, Components.Origin, Components.Pipeline, Components.ScaleMode, Components.ScrollFactor, Components.Size, Components.TextureCrop, Components.Tint, Components.Transform, Components.Visible, ImageRender], initialize: function Image(scene, x, y, texture, frame) { GameObject.call(this, scene, "Image"); this._crop = this.resetCropObject(); this.setTexture(texture, frame); this.setPosition(x, y); this.setSizeToFrame(); this.setOriginFromFrame(); this.initPipeline() } }); module.exports = Image }, function(module, exports) { var HasValue = function(source, key) { return source.hasOwnProperty(key) }; module.exports = HasValue }, function(module, exports) { var Contains = function(triangle, x, y) { var v0x = triangle.x3 - triangle.x1; var v0y = triangle.y3 - triangle.y1; var v1x = triangle.x2 - triangle.x1; var v1y = triangle.y2 - triangle.y1; var v2x = x - triangle.x1; var v2y = y - triangle.y1; var dot00 = v0x * v0x + v0y * v0y; var dot01 = v0x * v1x + v0y * v1y; var dot02 = v0x * v2x + v0y * v2y; var dot11 = v1x * v1x + v1y * v1y; var dot12 = v1x * v2x + v1y * v2y; var b = dot00 * dot11 - dot01 * dot01; var inv = b === 0 ? 0 : 1 / b; var u = (dot11 * dot02 - dot01 * dot12) * inv; var v = (dot00 * dot12 - dot01 * dot02) * inv; return u >= 0 && v >= 0 && u + v < 1 }; module.exports = Contains }, function(module, exports) { var Angle = function(line) { return Math.atan2(line.y2 - line.y1, line.x2 - line.x1) }; module.exports = Angle }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Vector3 = new Class({ initialize: function Vector3(x, y, z) { this.x = 0; this.y = 0; this.z = 0; if (typeof x === "object") { this.x = x.x || 0; this.y = x.y || 0; this.z = x.z || 0 } else { this.x = x || 0; this.y = y || 0; this.z = z || 0 } }, up: function() { this.x = 0; this.y = 1; this.z = 0; return this }, clone: function() { return new Vector3(this.x, this.y, this.z) }, crossVectors: function(a, b) { var ax = a.x; var ay = a.y; var az = a.z; var bx = b.x; var by = b.y; var bz = b.z; this.x = ay * bz - az * by; this.y = az * bx - ax * bz; this.z = ax * by - ay * bx; return this }, equals: function(v) { return this.x === v.x && this.y === v.y && this.z === v.z }, copy: function(src) { this.x = src.x; this.y = src.y; this.z = src.z || 0; return this }, set: function(x, y, z) { if (typeof x === "object") { this.x = x.x || 0; this.y = x.y || 0; this.z = x.z || 0 } else { this.x = x || 0; this.y = y || 0; this.z = z || 0 } return this }, add: function(v) { this.x += v.x; this.y += v.y; this.z += v.z || 0; return this }, subtract: function(v) { this.x -= v.x; this.y -= v.y; this.z -= v.z || 0; return this }, multiply: function(v) { this.x *= v.x; this.y *= v.y; this.z *= v.z || 1; return this }, scale: function(scale) { if (isFinite(scale)) { this.x *= scale; this.y *= scale; this.z *= scale } else { this.x = 0; this.y = 0; this.z = 0 } return this }, divide: function(v) { this.x /= v.x; this.y /= v.y; this.z /= v.z || 1; return this }, negate: function() { this.x = -this.x; this.y = -this.y; this.z = -this.z; return this }, distance: function(v) { var dx = v.x - this.x; var dy = v.y - this.y; var dz = v.z - this.z || 0; return Math.sqrt(dx * dx + dy * dy + dz * dz) }, distanceSq: function(v) { var dx = v.x - this.x; var dy = v.y - this.y; var dz = v.z - this.z || 0; return dx * dx + dy * dy + dz * dz }, length: function() { var x = this.x; var y = this.y; var z = this.z; return Math.sqrt(x * x + y * y + z * z) }, lengthSq: function() { var x = this.x; var y = this.y; var z = this.z; return x * x + y * y + z * z }, normalize: function() { var x = this.x; var y = this.y; var z = this.z; var len = x * x + y * y + z * z; if (len > 0) { len = 1 / Math.sqrt(len); this.x = x * len; this.y = y * len; this.z = z * len } return this }, dot: function(v) { return this.x * v.x + this.y * v.y + this.z * v.z }, cross: function(v) { var ax = this.x; var ay = this.y; var az = this.z; var bx = v.x; var by = v.y; var bz = v.z; this.x = ay * bz - az * by; this.y = az * bx - ax * bz; this.z = ax * by - ay * bx; return this }, lerp: function(v, t) { if (t === undefined) { t = 0 } var ax = this.x; var ay = this.y; var az = this.z; this.x = ax + t * (v.x - ax); this.y = ay + t * (v.y - ay); this.z = az + t * (v.z - az); return this }, transformMat3: function(mat) { var x = this.x; var y = this.y; var z = this.z; var m = mat.val; this.x = x * m[0] + y * m[3] + z * m[6]; this.y = x * m[1] + y * m[4] + z * m[7]; this.z = x * m[2] + y * m[5] + z * m[8]; return this }, transformMat4: function(mat) { var x = this.x; var y = this.y; var z = this.z; var m = mat.val; this.x = m[0] * x + m[4] * y + m[8] * z + m[12]; this.y = m[1] * x + m[5] * y + m[9] * z + m[13]; this.z = m[2] * x + m[6] * y + m[10] * z + m[14]; return this }, transformCoordinates: function(mat) { var x = this.x; var y = this.y; var z = this.z; var m = mat.val; var tx = x * m[0] + y * m[4] + z * m[8] + m[12]; var ty = x * m[1] + y * m[5] + z * m[9] + m[13]; var tz = x * m[2] + y * m[6] + z * m[10] + m[14]; var tw = x * m[3] + y * m[7] + z * m[11] + m[15]; this.x = tx / tw; this.y = ty / tw; this.z = tz / tw; return this }, transformQuat: function(q) { var x = this.x; var y = this.y; var z = this.z; var qx = q.x; var qy = q.y; var qz = q.z; var 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; this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy; this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz; this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx; return this }, project: function(mat) { var x = this.x; var y = this.y; var z = this.z; var m = mat.val; var a00 = m[0]; var a01 = m[1]; var a02 = m[2]; var a03 = m[3]; var a10 = m[4]; var a11 = m[5]; var a12 = m[6]; var a13 = m[7]; var a20 = m[8]; var a21 = m[9]; var a22 = m[10]; var a23 = m[11]; var a30 = m[12]; var a31 = m[13]; var a32 = m[14]; var a33 = m[15]; var lw = 1 / (x * a03 + y * a13 + z * a23 + a33); this.x = (x * a00 + y * a10 + z * a20 + a30) * lw; this.y = (x * a01 + y * a11 + z * a21 + a31) * lw; this.z = (x * a02 + y * a12 + z * a22 + a32) * lw; return this }, unproject: function(viewport, invProjectionView) { var viewX = viewport.x; var viewY = viewport.y; var viewWidth = viewport.z; var viewHeight = viewport.w; var x = this.x - viewX; var y = viewHeight - this.y - 1 - viewY; var z = this.z; this.x = 2 * x / viewWidth - 1; this.y = 2 * y / viewHeight - 1; this.z = 2 * z - 1; return this.project(invProjectionView) }, reset: function() { this.x = 0; this.y = 0; this.z = 0; return this } }); module.exports = Vector3 }, function(module, exports, __webpack_require__) { var Events = {}; module.exports = Events; var Common = __webpack_require__(17); (function() { Events.on = function(object, eventNames, callback) { var names = eventNames.split(" "), name; for (var i = 0; i < names.length; i++) { name = names[i]; object.events = object.events || {}; object.events[name] = object.events[name] || []; object.events[name].push(callback) } return callback }; Events.off = function(object, eventNames, callback) { if (!eventNames) { object.events = {}; return } if (typeof eventNames === "function") { callback = eventNames; eventNames = Common.keys(object.events).join(" ") } var names = eventNames.split(" "); for (var i = 0; i < names.length; i++) { var callbacks = object.events[names[i]], newCallbacks = []; if (callback && callbacks) { for (var j = 0; j < callbacks.length; j++) { if (callbacks[j] !== callback) newCallbacks.push(callbacks[j]) } } object.events[names[i]] = newCallbacks } }; Events.trigger = function(object, eventNames, event) { var names, name, callbacks, eventClone; var events = object.events; if (events && Common.keys(events).length > 0) { if (!event) event = {}; names = eventNames.split(" "); for (var i = 0; i < names.length; i++) { name = names[i]; callbacks = events[name]; if (callbacks) { eventClone = Common.clone(event, false); eventClone.name = name; eventClone.source = object; for (var j = 0; j < callbacks.length; j++) { callbacks[j].apply(object, [eventClone]) } } } } } })() }, function(module, exports, __webpack_require__) { var Constraint = {}; module.exports = Constraint; var Vertices = __webpack_require__(32); var Vector = __webpack_require__(33); var Sleeping = __webpack_require__(103); var Bounds = __webpack_require__(34); var Axes = __webpack_require__(204); var Common = __webpack_require__(17); (function() { Constraint._warming = .4; Constraint._torqueDampen = 1; Constraint._minLength = 1e-6; Constraint.create = function(options) { var constraint = options; if (constraint.bodyA && !constraint.pointA) constraint.pointA = { x: 0, y: 0 }; if (constraint.bodyB && !constraint.pointB) constraint.pointB = { x: 0, y: 0 }; var initialPointA = constraint.bodyA ? Vector.add(constraint.bodyA.position, constraint.pointA) : constraint.pointA, initialPointB = constraint.bodyB ? Vector.add(constraint.bodyB.position, constraint.pointB) : constraint.pointB, length = Vector.magnitude(Vector.sub(initialPointA, initialPointB)); constraint.length = typeof constraint.length !== "undefined" ? constraint.length : length; constraint.id = constraint.id || Common.nextId(); constraint.label = constraint.label || "Constraint"; constraint.type = "constraint"; constraint.stiffness = constraint.stiffness || (constraint.length > 0 ? 1 : .7); constraint.damping = constraint.damping || 0; constraint.angularStiffness = constraint.angularStiffness || 0; constraint.angleA = constraint.bodyA ? constraint.bodyA.angle : constraint.angleA; constraint.angleB = constraint.bodyB ? constraint.bodyB.angle : constraint.angleB; constraint.plugin = {}; var render = { visible: true, lineWidth: 2, strokeStyle: "#ffffff", type: "line", anchors: true }; if (constraint.length === 0 && constraint.stiffness > .1) { render.type = "pin"; render.anchors = false } else if (constraint.stiffness < .9) { render.type = "spring" } constraint.render = Common.extend(render, constraint.render); return constraint }; Constraint.preSolveAll = function(bodies) { for (var i = 0; i < bodies.length; i += 1) { var body = bodies[i], impulse = body.constraintImpulse; if (body.isStatic || impulse.x === 0 && impulse.y === 0 && impulse.angle === 0) { continue } body.position.x += impulse.x; body.position.y += impulse.y; body.angle += impulse.angle } }; Constraint.solveAll = function(constraints, timeScale) { for (var i = 0; i < constraints.length; i += 1) { var constraint = constraints[i], fixedA = !constraint.bodyA || constraint.bodyA && constraint.bodyA.isStatic, fixedB = !constraint.bodyB || constraint.bodyB && constraint.bodyB.isStatic; if (fixedA || fixedB) { Constraint.solve(constraints[i], timeScale) } } for (i = 0; i < constraints.length; i += 1) { constraint = constraints[i]; fixedA = !constraint.bodyA || constraint.bodyA && constraint.bodyA.isStatic; fixedB = !constraint.bodyB || constraint.bodyB && constraint.bodyB.isStatic; if (!fixedA && !fixedB) { Constraint.solve(constraints[i], timeScale) } } }; Constraint.solve = function(constraint, timeScale) { var bodyA = constraint.bodyA, bodyB = constraint.bodyB, pointA = constraint.pointA, pointB = constraint.pointB; if (!bodyA && !bodyB) return; if (bodyA && !bodyA.isStatic) { Vector.rotate(pointA, bodyA.angle - constraint.angleA, pointA); constraint.angleA = bodyA.angle } if (bodyB && !bodyB.isStatic) { Vector.rotate(pointB, bodyB.angle - constraint.angleB, pointB); constraint.angleB = bodyB.angle } var pointAWorld = pointA, pointBWorld = pointB; if (bodyA) pointAWorld = Vector.add(bodyA.position, pointA); if (bodyB) pointBWorld = Vector.add(bodyB.position, pointB); if (!pointAWorld || !pointBWorld) return; var delta = Vector.sub(pointAWorld, pointBWorld), currentLength = Vector.magnitude(delta); if (currentLength < Constraint._minLength) { currentLength = Constraint._minLength } var difference = (currentLength - constraint.length) / currentLength, stiffness = constraint.stiffness < 1 ? constraint.stiffness * timeScale : constraint.stiffness, force = Vector.mult(delta, difference * stiffness), massTotal = (bodyA ? bodyA.inverseMass : 0) + (bodyB ? bodyB.inverseMass : 0), inertiaTotal = (bodyA ? bodyA.inverseInertia : 0) + (bodyB ? bodyB.inverseInertia : 0), resistanceTotal = massTotal + inertiaTotal, torque, share, normal, normalVelocity, relativeVelocity; if (constraint.damping) { var zero = Vector.create(); normal = Vector.div(delta, currentLength); relativeVelocity = Vector.sub(bodyB && Vector.sub(bodyB.position, bodyB.positionPrev) || zero, bodyA && Vector.sub(bodyA.position, bodyA.positionPrev) || zero); normalVelocity = Vector.dot(normal, relativeVelocity) } if (bodyA && !bodyA.isStatic) { share = bodyA.inverseMass / massTotal; bodyA.constraintImpulse.x -= force.x * share; bodyA.constraintImpulse.y -= force.y * share; bodyA.position.x -= force.x * share; bodyA.position.y -= force.y * share; if (constraint.damping) { bodyA.positionPrev.x -= constraint.damping * normal.x * normalVelocity * share; bodyA.positionPrev.y -= constraint.damping * normal.y * normalVelocity * share } torque = Vector.cross(pointA, force) / resistanceTotal * Constraint._torqueDampen * bodyA.inverseInertia * (1 - constraint.angularStiffness); bodyA.constraintImpulse.angle -= torque; bodyA.angle -= torque } if (bodyB && !bodyB.isStatic) { share = bodyB.inverseMass / massTotal; bodyB.constraintImpulse.x += force.x * share; bodyB.constraintImpulse.y += force.y * share; bodyB.position.x += force.x * share; bodyB.position.y += force.y * share; if (constraint.damping) { bodyB.positionPrev.x += constraint.damping * normal.x * normalVelocity * share; bodyB.positionPrev.y += constraint.damping * normal.y * normalVelocity * share } torque = Vector.cross(pointB, force) / resistanceTotal * Constraint._torqueDampen * bodyB.inverseInertia * (1 - constraint.angularStiffness); bodyB.constraintImpulse.angle += torque; bodyB.angle += torque } }; Constraint.postSolveAll = function(bodies) { for (var i = 0; i < bodies.length; i++) { var body = bodies[i], impulse = body.constraintImpulse; if (body.isStatic || impulse.x === 0 && impulse.y === 0 && impulse.angle === 0) { continue } Sleeping.set(body, false); for (var j = 0; j < body.parts.length; j++) { var part = body.parts[j]; Vertices.translate(part.vertices, impulse); if (j > 0) { part.position.x += impulse.x; part.position.y += impulse.y } if (impulse.angle !== 0) { Vertices.rotate(part.vertices, impulse.angle, body.position); Axes.rotate(part.axes, impulse.angle); if (j > 0) { Vector.rotateAbout(part.position, impulse.angle, body.position, part.position) } } Bounds.update(part.bounds, part.vertices, body.velocity) } impulse.angle *= Constraint._warming; impulse.x *= Constraint._warming; impulse.y *= Constraint._warming } } })() }, function(module, exports) { module.exports = { DEFAULT: 0, LINEAR: 0, NEAREST: 1 } }, function(module, exports, __webpack_require__) { var Clamp = __webpack_require__(23); var FromPercent = function(percent, min, max) { percent = Clamp(percent, 0, 1); return (max - min) * percent }; module.exports = FromPercent }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var DataManager = new Class({ initialize: function DataManager(parent, eventEmitter) { this.parent = parent; this.events = eventEmitter; if (!eventEmitter) { this.events = parent.events ? parent.events : parent } this.list = {}; this.values = {}; this._frozen = false; if (!parent.hasOwnProperty("sys") && this.events) { this.events.once("destroy", this.destroy, this) } }, get: function(key) { var list = this.list; if (Array.isArray(key)) { var output = []; for (var i = 0; i < key.length; i++) { output.push(list[key[i]]) } return output } else { return list[key] } }, getAll: function() { var results = {}; for (var key in this.list) { if (this.list.hasOwnProperty(key)) { results[key] = this.list[key] } } return results }, query: function(search) { var results = {}; for (var key in this.list) { if (this.list.hasOwnProperty(key) && key.match(search)) { results[key] = this.list[key] } } return results }, set: function(key, data) { if (this._frozen) { return this } if (typeof key === "string") { return this.setValue(key, data) } else { for (var entry in key) { this.setValue(entry, key[entry]) } } return this }, setValue: function(key, data) { if (this._frozen) { return this } if (this.has(key)) { this.values[key] = data } else { var _this = this; var list = this.list; var events = this.events; var parent = this.parent; Object.defineProperty(this.values, key, { enumerable: true, configurable: true, get: function() { return list[key] }, set: function(value) { if (!_this._frozen) { var previousValue = list[key]; list[key] = value; events.emit("changedata", parent, key, value, previousValue); events.emit("changedata_" + key, parent, value, previousValue) } } }); list[key] = data; events.emit("setdata", parent, key, data) } return this }, each: function(callback, context) { var args = [this.parent, null, undefined]; for (var i = 1; i < arguments.length; i++) { args.push(arguments[i]) } for (var key in this.list) { args[1] = key; args[2] = this.list[key]; callback.apply(context, args) } return this }, merge: function(data, overwrite) { if (overwrite === undefined) { overwrite = true } for (var key in data) { if (data.hasOwnProperty(key) && (overwrite || !overwrite && !this.has(key))) { this.setValue(key, data[key]) } } return this }, remove: function(key) { if (this._frozen) { return this } if (Array.isArray(key)) { for (var i = 0; i < key.length; i++) { this.removeValue(key[i]) } } else { return this.removeValue(key) } return this }, removeValue: function(key) { if (this.has(key)) { var data = this.list[key]; delete this.list[key]; delete this.values[key]; this.events.emit("removedata", this.parent, key, data) } return this }, pop: function(key) { var data = undefined; if (!this._frozen && this.has(key)) { data = this.list[key]; delete this.list[key]; delete this.values[key]; this.events.emit("removedata", this, key, data) } return data }, has: function(key) { return this.list.hasOwnProperty(key) }, setFreeze: function(value) { this._frozen = value; return this }, reset: function() { for (var key in this.list) { delete this.list[key]; delete this.values[key] } this._frozen = false; return this }, destroy: function() { this.reset(); this.events.off("changedata"); this.events.off("setdata"); this.events.off("removedata"); this.parent = null }, freeze: { get: function() { return this._frozen }, set: function(value) { this._frozen = value ? true : false } }, count: { get: function() { var i = 0; for (var key in this.list) { if (this.list[key] !== undefined) { i++ } } return i } } }); module.exports = DataManager }, function(module, exports, __webpack_require__) { (function(process) { var OS = { android: false, chromeOS: false, cocoonJS: false, cocoonJSApp: false, cordova: false, crosswalk: false, desktop: false, ejecta: false, electron: false, iOS: false, iOSVersion: 0, iPad: false, iPhone: false, kindle: false, linux: false, macOS: false, node: false, nodeWebkit: false, pixelRatio: 1, webApp: false, windows: false, windowsPhone: false }; function init() { var ua = navigator.userAgent; if (/Windows/.test(ua)) { OS.windows = true } else if (/Mac OS/.test(ua) && !/like Mac OS/.test(ua)) { OS.macOS = true } else if (/Android/.test(ua)) { OS.android = true } else if (/Linux/.test(ua)) { OS.linux = true } else if (/iP[ao]d|iPhone/i.test(ua)) { OS.iOS = true; navigator.appVersion.match(/OS (\d+)/); OS.iOSVersion = parseInt(RegExp.$1, 10); OS.iPhone = ua.toLowerCase().indexOf("iphone") !== -1; OS.iPad = ua.toLowerCase().indexOf("ipad") !== -1 } else if (/Kindle/.test(ua) || /\bKF[A-Z][A-Z]+/.test(ua) || /Silk.*Mobile Safari/.test(ua)) { OS.kindle = true } else if (/CrOS/.test(ua)) { OS.chromeOS = true } if (/Windows Phone/i.test(ua) || /IEMobile/i.test(ua)) { OS.android = false; OS.iOS = false; OS.macOS = false; OS.windows = true; OS.windowsPhone = true } var silk = /Silk/.test(ua); if (OS.windows || OS.macOS || OS.linux && !silk || OS.chromeOS) { OS.desktop = true } if (OS.windowsPhone || /Windows NT/i.test(ua) && /Touch/i.test(ua)) { OS.desktop = false } if (navigator.standalone) { OS.webApp = true } if (window.cordova !== undefined) { OS.cordova = true } if (typeof process !== "undefined" && process.versions && process.versions.node) { OS.node = true } if (OS.node && typeof process.versions === "object") { OS.nodeWebkit = !!process.versions["node-webkit"]; OS.electron = !!process.versions.electron } if (navigator.isCocoonJS) { OS.cocoonJS = true; try { OS.cocoonJSApp = typeof CocoonJS !== "undefined" } catch (error) { OS.cocoonJSApp = false } } if (window.ejecta !== undefined) { OS.ejecta = true } if (/Crosswalk/.test(ua)) { OS.crosswalk = true } OS.pixelRatio = window["devicePixelRatio"] || 1; return OS } module.exports = init() }).call(exports, __webpack_require__(627)) }, function(module, exports) { var SpliceOne = function(array, index) { if (index >= array.length) { return } var len = array.length - 1; var item = array[index]; for (var i = index; i < len; i++) { array[i] = array[i + 1] } array.length = len; return item }; module.exports = SpliceOne }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Contains = __webpack_require__(95); var GetPoint = __webpack_require__(341); var GetPoints = __webpack_require__(342); var Random = __webpack_require__(152); var Ellipse = new Class({ initialize: function Ellipse(x, y, width, height) { if (x === undefined) { x = 0 } if (y === undefined) { y = 0 } if (width === undefined) { width = 0 } if (height === undefined) { height = 0 } this.x = x; this.y = y; this.width = width; this.height = height }, contains: function(x, y) { return Contains(this, x, y) }, getPoint: function(position, point) { return GetPoint(this, position, point) }, getPoints: function(quantity, stepRate, output) { return GetPoints(this, quantity, stepRate, output) }, getRandomPoint: function(point) { return Random(this, point) }, setTo: function(x, y, width, height) { this.x = x; this.y = y; this.width = width; this.height = height; return this }, setEmpty: function() { this.width = 0; this.height = 0; return this }, setPosition: function(x, y) { if (y === undefined) { y = x } this.x = x; this.y = y; return this }, setSize: function(width, height) { if (height === undefined) { height = width } this.width = width; this.height = height; return this }, isEmpty: function() { return this.width <= 0 || this.height <= 0 }, getMinorRadius: function() { return Math.min(this.width, this.height) / 2 }, getMajorRadius: function() { return Math.max(this.width, this.height) / 2 }, left: { get: function() { return this.x - this.width / 2 }, set: function(value) { this.x = value + this.width / 2 } }, right: { get: function() { return this.x + this.width / 2 }, set: function(value) { this.x = value - this.width / 2 } }, top: { get: function() { return this.y - this.height / 2 }, set: function(value) { this.y = value + this.height / 2 } }, bottom: { get: function() { return this.y + this.height / 2 }, set: function(value) { this.y = value - this.height / 2 } } }); module.exports = Ellipse }, function(module, exports) { var Contains = function(ellipse, x, y) { if (ellipse.width <= 0 || ellipse.height <= 0) { return false } var normx = (x - ellipse.x) / ellipse.width; var normy = (y - ellipse.y) / ellipse.height; normx *= normx; normy *= normy; return normx + normy < .25 }; module.exports = Contains }, function(module, exports, __webpack_require__) { var Actions = __webpack_require__(225); var Class = __webpack_require__(0); var GetFastValue = __webpack_require__(1); var GetValue = __webpack_require__(4); var IsPlainObject = __webpack_require__(7); var Range = __webpack_require__(338); var Set = __webpack_require__(81); var Sprite = __webpack_require__(50); var Group = new Class({ initialize: function Group(scene, children, config) { if (config) { if (children && !Array.isArray(children)) { children = [children] } } else if (Array.isArray(children)) { if (IsPlainObject(children[0])) { config = children; children = null } } else if (IsPlainObject(children)) { config = children; children = null } this.scene = scene; this.children = new Set(children); this.isParent = true; this.classType = GetFastValue(config, "classType", Sprite); this.active = GetFastValue(config, "active", true); this.maxSize = GetFastValue(config, "maxSize", -1); this.defaultKey = GetFastValue(config, "defaultKey", null); this.defaultFrame = GetFastValue(config, "defaultFrame", null); this.runChildUpdate = GetFastValue(config, "runChildUpdate", false); this.createCallback = GetFastValue(config, "createCallback", null); this.removeCallback = GetFastValue(config, "removeCallback", null); this.createMultipleCallback = GetFastValue(config, "createMultipleCallback", null); if (config) { this.createMultiple(config) } }, create: function(x, y, key, frame, visible, active) { if (x === undefined) { x = 0 } if (y === undefined) { y = 0 } if (key === undefined) { key = this.defaultKey } if (frame === undefined) { frame = this.defaultFrame } if (visible === undefined) { visible = true } if (active === undefined) { active = true } if (this.isFull()) { return null } var child = new this.classType(this.scene, x, y, key, frame); this.scene.sys.displayList.add(child); if (child.preUpdate) { this.scene.sys.updateList.add(child) } child.visible = visible; child.setActive(active); this.add(child); return child }, createMultiple: function(config) { if (this.isFull()) { return [] } if (!Array.isArray(config)) { config = [config] } var output = []; if (config[0].key) { for (var i = 0; i < config.length; i++) { var entries = this.createFromConfig(config[i]); output = output.concat(entries) } } return output }, createFromConfig: function(options) { if (this.isFull()) { return [] } this.classType = GetFastValue(options, "classType", this.classType); var key = GetFastValue(options, "key", undefined); var frame = GetFastValue(options, "frame", null); var visible = GetFastValue(options, "visible", true); var active = GetFastValue(options, "active", true); var entries = []; if (key === undefined) { return entries } else { if (!Array.isArray(key)) { key = [key] } if (!Array.isArray(frame)) { frame = [frame] } } var repeat = GetFastValue(options, "repeat", 0); var randomKey = GetFastValue(options, "randomKey", false); var randomFrame = GetFastValue(options, "randomFrame", false); var yoyo = GetFastValue(options, "yoyo", false); var quantity = GetFastValue(options, "frameQuantity", 1); var max = GetFastValue(options, "max", 0); var range = Range(key, frame, { max: max, qty: quantity, random: randomKey, randomB: randomFrame, repeat: repeat, yoyo: yoyo }); for (var c = 0; c < range.length; c++) { var created = this.create(0, 0, range[c].a, range[c].b, visible, active); if (!created) { break } entries.push(created) } var x = GetValue(options, "setXY.x", 0); var y = GetValue(options, "setXY.y", 0); var stepX = GetValue(options, "setXY.stepX", 0); var stepY = GetValue(options, "setXY.stepY", 0); Actions.SetXY(entries, x, y, stepX, stepY); var rotation = GetValue(options, "setRotation.value", 0); var stepRotation = GetValue(options, "setRotation.step", 0); Actions.SetRotation(entries, rotation, stepRotation); var scaleX = GetValue(options, "setScale.x", 1); var scaleY = GetValue(options, "setScale.y", scaleX); var stepScaleX = GetValue(options, "setScale.stepX", 0); var stepScaleY = GetValue(options, "setScale.stepY", 0); Actions.SetScale(entries, scaleX, scaleY, stepScaleX, stepScaleY); var alpha = GetValue(options, "setAlpha.value", 1); var stepAlpha = GetValue(options, "setAlpha.step", 0); Actions.SetAlpha(entries, alpha, stepAlpha); var hitArea = GetFastValue(options, "hitArea", null); var hitAreaCallback = GetFastValue(options, "hitAreaCallback", null); if (hitArea) { Actions.SetHitArea(entries, hitArea, hitAreaCallback) } var grid = GetFastValue(options, "gridAlign", false); if (grid) { Actions.GridAlign(entries, grid) } if (this.createMultipleCallback) { this.createMultipleCallback.call(this, entries) } return entries }, preUpdate: function(time, delta) { if (!this.runChildUpdate || this.children.size === 0) { return } var temp = this.children.entries.slice(); for (var i = 0; i < temp.length; i++) { var item = temp[i]; if (item.active) { item.update(time, delta) } } }, add: function(child, addToScene) { if (addToScene === undefined) { addToScene = false } if (this.isFull()) { return this } this.children.set(child); if (this.createCallback) { this.createCallback.call(this, child) } if (addToScene) { this.scene.sys.displayList.add(child); if (child.preUpdate) { this.scene.sys.updateList.add(child) } } child.on("destroy", this.remove, this); return this }, addMultiple: function(children, addToScene) { if (addToScene === undefined) { addToScene = false } if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { this.add(children[i], addToScene) } } return this }, remove: function(child, removeFromScene, destroyChild) { if (removeFromScene === undefined) { removeFromScene = false } if (destroyChild === undefined) { destroyChild = false } if (!this.children.contains(child)) { return this } this.children.delete(child); if (this.removeCallback) { this.removeCallback.call(this, child) } child.off("destroy", this.remove, this); if (destroyChild) { child.destroy() } else if (removeFromScene) { child.scene.sys.displayList.remove(child); if (child.preUpdate) { child.scene.sys.updateList.remove(child) } } return this }, clear: function(removeFromScene, destroyChild) { if (removeFromScene === undefined) { removeFromScene = false } if (destroyChild === undefined) { destroyChild = false } var children = this.children; for (var i = 0; i < children.size; i++) { var gameObject = children.entries[i]; gameObject.off("destroy", this.remove, this); if (destroyChild) { gameObject.destroy() } else if (removeFromScene) { gameObject.scene.sys.displayList.remove(gameObject); if (gameObject.preUpdate) { gameObject.scene.sys.updateList.remove(gameObject) } } } this.children.clear(); return this }, contains: function(child) { return this.children.contains(child) }, getChildren: function() { return this.children.entries }, getLength: function() { return this.children.size }, getFirst: function(state, createIfNull, x, y, key, frame, visible) { return this.getHandler(true, 1, state, createIfNull, x, y, key, frame, visible) }, getFirstNth: function(nth, state, createIfNull, x, y, key, frame, visible) { return this.getHandler(true, nth, state, createIfNull, x, y, key, frame, visible) }, getLast: function(state, createIfNull, x, y, key, frame, visible) { return this.getHandler(false, 1, state, createIfNull, x, y, key, frame, visible) }, getLastNth: function(nth, state, createIfNull, x, y, key, frame, visible) { return this.getHandler(false, nth, state, createIfNull, x, y, key, frame, visible) }, getHandler: function(forwards, nth, state, createIfNull, x, y, key, frame, visible) { if (state === undefined) { state = false } if (createIfNull === undefined) { createIfNull = false } var gameObject; var i; var total = 0; var children = this.children.entries; if (forwards) { for (i = 0; i < children.length; i++) { gameObject = children[i]; if (gameObject.active === state) { total++; if (total === nth) { break } } else { gameObject = null } } } else { for (i = children.length - 1; i >= 0; i--) { gameObject = children[i]; if (gameObject.active === state) { total++; if (total === nth) { break } } else { gameObject = null } } } if (gameObject) { if (typeof x === "number") { gameObject.x = x } if (typeof y === "number") { gameObject.y = y } return gameObject } if (createIfNull) { return this.create(x, y, key, frame, visible) } else { return null } }, get: function(x, y, key, frame, visible) { return this.getFirst(false, true, x, y, key, frame, visible) }, getFirstAlive: function(createIfNull, x, y, key, frame, visible) { return this.getFirst(true, createIfNull, x, y, key, frame, visible) }, getFirstDead: function(createIfNull, x, y, key, frame, visible) { return this.getFirst(false, createIfNull, x, y, key, frame, visible) }, playAnimation: function(key, startFrame) { Actions.PlayAnimation(this.children.entries, key, startFrame); return this }, isFull: function() { if (this.maxSize === -1) { return false } else { return this.children.size >= this.maxSize } }, countActive: function(value) { if (value === undefined) { value = true } var total = 0; for (var i = 0; i < this.children.size; i++) { if (this.children.entries[i].active === value) { total++ } } return total }, getTotalUsed: function() { return this.countActive() }, getTotalFree: function() { var used = this.getTotalUsed(); var capacity = this.maxSize === -1 ? 999999999999 : this.maxSize; return capacity - used }, setDepth: function(value, step) { Actions.SetDepth(this.children.entries, value, step); return this }, kill: function(gameObject) { if (this.children.contains(gameObject)) { gameObject.setActive(false) } }, killAndHide: function(gameObject) { if (this.children.contains(gameObject)) { gameObject.setActive(false); gameObject.setVisible(false) } }, toggleVisible: function() { Actions.ToggleVisible(this.children.entries); return this }, destroy: function(destroyChildren) { if (destroyChildren === undefined) { destroyChildren = false } if (!this.scene || this.ignoreDestroy) { return } if (destroyChildren) { var children = this.children; for (var i = 0; i < children.size; i++) { var gameObject = children.entries[i]; gameObject.off("destroy", this.remove, this); gameObject.destroy() } } this.children.clear(); this.scene = undefined; this.children = undefined } }); module.exports = Group }, function(module, exports, __webpack_require__) { var EaseMap = __webpack_require__(163); var GetEaseFunction = function(ease, easeParams) { if (typeof ease === "string" && EaseMap.hasOwnProperty(ease)) { if (easeParams) { var cloneParams = easeParams.slice(0); cloneParams.unshift(0); return function(v) { cloneParams[0] = v; return EaseMap[ease].apply(this, cloneParams) } } else { return EaseMap[ease] } } else if (typeof ease === "function") { return ease } else if (Array.isArray(ease) && ease.length === 4) {} return EaseMap.Power0 }; module.exports = GetEaseFunction }, function(module, exports) { var GetBoolean = function(source, key, defaultValue) { if (!source) { return defaultValue } else if (source.hasOwnProperty(key)) { return source[key] } else { return defaultValue } }; module.exports = GetBoolean }, function(module, exports) { var TWEEN_CONST = { CREATED: 0, INIT: 1, DELAY: 2, OFFSET_DELAY: 3, PENDING_RENDER: 4, PLAYING_FORWARD: 5, PLAYING_BACKWARD: 6, HOLD_DELAY: 7, REPEAT_DELAY: 8, COMPLETE: 9, PENDING_ADD: 20, PAUSED: 21, LOOP_DELAY: 22, ACTIVE: 23, COMPLETE_DELAY: 24, PENDING_REMOVE: 25, REMOVED: 26 }; module.exports = TWEEN_CONST }, function(module, exports, __webpack_require__) { var Utils = __webpack_require__(10); var FillPathWebGL = function(pipeline, calcMatrix, src, alpha, dx, dy) { var fillTintColor = Utils.getTintAppendFloatAlphaAndSwap(src.fillColor, src.fillAlpha * alpha); var path = src.pathData; var pathIndexes = src.pathIndexes; for (var i = 0; i < pathIndexes.length; i += 3) { var p0 = pathIndexes[i] * 2; var p1 = pathIndexes[i + 1] * 2; var p2 = pathIndexes[i + 2] * 2; var x0 = path[p0 + 0] - dx; var y0 = path[p0 + 1] - dy; var x1 = path[p1 + 0] - dx; var y1 = path[p1 + 1] - dy; var x2 = path[p2 + 0] - dx; var y2 = path[p2 + 1] - dy; var tx0 = calcMatrix.getX(x0, y0); var ty0 = calcMatrix.getY(x0, y0); var tx1 = calcMatrix.getX(x1, y1); var ty1 = calcMatrix.getY(x1, y1); var tx2 = calcMatrix.getX(x2, y2); var ty2 = calcMatrix.getY(x2, y2); pipeline.setTexture2D(); pipeline.batchTri(tx0, ty0, tx1, ty1, tx2, ty2, 0, 0, 1, 1, fillTintColor, fillTintColor, fillTintColor, pipeline.tintEffect) } }; module.exports = FillPathWebGL }, function(module, exports) { module.exports = { NEVER: 0, LITE: 1, PASSIVE: 2, ACTIVE: 4, FIXED: 8 } }, function(module, exports) { module.exports = { NONE: 0, A: 1, B: 2, BOTH: 3 } }, function(module, exports, __webpack_require__) { var Sleeping = {}; module.exports = Sleeping; var Events = __webpack_require__(87); (function() { Sleeping._motionWakeThreshold = .18; Sleeping._motionSleepThreshold = .08; Sleeping._minBias = .9; Sleeping.update = function(bodies, timeScale) { var timeFactor = timeScale * timeScale * timeScale; for (var i = 0; i < bodies.length; i++) { var body = bodies[i], motion = body.speed * body.speed + body.angularSpeed * body.angularSpeed; if (body.force.x !== 0 || body.force.y !== 0) { Sleeping.set(body, false); continue } var minMotion = Math.min(body.motion, motion), maxMotion = Math.max(body.motion, motion); body.motion = Sleeping._minBias * minMotion + (1 - Sleeping._minBias) * maxMotion; if (body.sleepThreshold > 0 && body.motion < Sleeping._motionSleepThreshold * timeFactor) { body.sleepCounter += 1; if (body.sleepCounter >= body.sleepThreshold) Sleeping.set(body, true) } else if (body.sleepCounter > 0) { body.sleepCounter -= 1 } } }; Sleeping.afterCollisions = function(pairs, timeScale) { var timeFactor = timeScale * timeScale * timeScale; for (var i = 0; i < pairs.length; i++) { var pair = pairs[i]; if (!pair.isActive) continue; var collision = pair.collision, bodyA = collision.bodyA.parent, bodyB = collision.bodyB.parent; if (bodyA.isSleeping && bodyB.isSleeping || bodyA.isStatic || bodyB.isStatic) continue; if (bodyA.isSleeping || bodyB.isSleeping) { var sleepingBody = bodyA.isSleeping && !bodyA.isStatic ? bodyA : bodyB, movingBody = sleepingBody === bodyA ? bodyB : bodyA; if (!sleepingBody.isStatic && movingBody.motion > Sleeping._motionWakeThreshold * timeFactor) { Sleeping.set(sleepingBody, false) } } } }; Sleeping.set = function(body, isSleeping) { var wasSleeping = body.isSleeping; if (isSleeping) { body.isSleeping = true; body.sleepCounter = body.sleepThreshold; body.positionImpulse.x = 0; body.positionImpulse.y = 0; body.positionPrev.x = body.position.x; body.positionPrev.y = body.position.y; body.anglePrev = body.angle; body.speed = 0; body.angularSpeed = 0; body.motion = 0; if (!wasSleeping) { Events.trigger(body, "sleepStart") } } else { body.isSleeping = false; body.sleepCounter = 0; if (wasSleeping) { Events.trigger(body, "sleepEnd") } } } })() }, function(module, exports) { var IsInLayerBounds = function(tileX, tileY, layer) { return tileX >= 0 && tileX < layer.width && tileY >= 0 && tileY < layer.height }; module.exports = IsInLayerBounds }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var GetFastValue = __webpack_require__(1); var LayerData = new Class({ initialize: function LayerData(config) { if (config === undefined) { config = {} } this.name = GetFastValue(config, "name", "layer"); this.x = GetFastValue(config, "x", 0); this.y = GetFastValue(config, "y", 0); this.width = GetFastValue(config, "width", 0); this.height = GetFastValue(config, "height", 0); this.tileWidth = GetFastValue(config, "tileWidth", 0); this.tileHeight = GetFastValue(config, "tileHeight", 0); this.baseTileWidth = GetFastValue(config, "baseTileWidth", this.tileWidth); this.baseTileHeight = GetFastValue(config, "baseTileHeight", this.tileHeight); this.widthInPixels = GetFastValue(config, "widthInPixels", this.width * this.baseTileWidth); this.heightInPixels = GetFastValue(config, "heightInPixels", this.height * this.baseTileHeight); this.alpha = GetFastValue(config, "alpha", 1); this.visible = GetFastValue(config, "visible", true); this.properties = GetFastValue(config, "properties", {}); this.indexes = GetFastValue(config, "indexes", []); this.collideIndexes = GetFastValue(config, "collideIndexes", []); this.callbacks = GetFastValue(config, "callbacks", []); this.bodies = GetFastValue(config, "bodies", []); this.data = GetFastValue(config, "data", []); this.tilemapLayer = GetFastValue(config, "tilemapLayer", null) } }); module.exports = LayerData }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var GetFastValue = __webpack_require__(1); var MapData = new Class({ initialize: function MapData(config) { if (config === undefined) { config = {} } this.name = GetFastValue(config, "name", "map"); this.width = GetFastValue(config, "width", 0); this.height = GetFastValue(config, "height", 0); this.tileWidth = GetFastValue(config, "tileWidth", 0); this.tileHeight = GetFastValue(config, "tileHeight", 0); this.widthInPixels = GetFastValue(config, "widthInPixels", this.width * this.tileWidth); this.heightInPixels = GetFastValue(config, "heightInPixels", this.height * this.tileHeight); this.format = GetFastValue(config, "format", null); this.orientation = GetFastValue(config, "orientation", "orthogonal"); this.renderOrder = GetFastValue(config, "renderOrder", "right-down"); this.version = GetFastValue(config, "version", "1"); this.properties = GetFastValue(config, "properties", {}); this.layers = GetFastValue(config, "layers", []); this.images = GetFastValue(config, "images", []); this.objects = GetFastValue(config, "objects", {}); this.collision = GetFastValue(config, "collision", {}); this.tilesets = GetFastValue(config, "tilesets", []); this.imageCollections = GetFastValue(config, "imageCollections", []); this.tiles = GetFastValue(config, "tiles", []) } }); module.exports = MapData }, function(module, exports, __webpack_require__) { var BlendModes = __webpack_require__(61); var Circle = __webpack_require__(78); var CircleContains = __webpack_require__(46); var Class = __webpack_require__(0); var Components = __webpack_require__(14); var GameObject = __webpack_require__(12); var Rectangle = __webpack_require__(9); var RectangleContains = __webpack_require__(47); var Zone = new Class({ Extends: GameObject, Mixins: [Components.Depth, Components.GetBounds, Components.Origin, Components.ScaleMode, Components.Transform, Components.ScrollFactor, Components.Visible], initialize: function Zone(scene, x, y, width, height) { if (width === undefined) { width = 1 } if (height === undefined) { height = width } GameObject.call(this, scene, "Zone"); this.setPosition(x, y); this.width = width; this.height = height; this.blendMode = BlendModes.NORMAL; this.updateDisplayOrigin() }, displayWidth: { get: function() { return this.scaleX * this.width }, set: function(value) { this.scaleX = value / this.width } }, displayHeight: { get: function() { return this.scaleY * this.height }, set: function(value) { this.scaleY = value / this.height } }, setSize: function(width, height, resizeInput) { if (resizeInput === undefined) { resizeInput = true } this.width = width; this.height = height; if (resizeInput && this.input && this.input.hitArea instanceof Rectangle) { this.input.hitArea.width = width; this.input.hitArea.height = height } return this }, setDisplaySize: function(width, height) { this.displayWidth = width; this.displayHeight = height; return this }, setCircleDropZone: function(radius) { return this.setDropZone(new Circle(0, 0, radius), CircleContains) }, setRectangleDropZone: function(width, height) { return this.setDropZone(new Rectangle(0, 0, width, height), RectangleContains) }, setDropZone: function(shape, callback) { if (shape === undefined) { this.setRectangleDropZone(this.width, this.height) } else if (!this.input) { this.setInteractive(shape, callback, true) } return this }, setAlpha: function() {}, renderCanvas: function() {}, renderWebGL: function() {} }); module.exports = Zone }, function(module, exports) { var Perimeter = function(rect) { return 2 * (rect.width + rect.height) }; module.exports = Perimeter }, function(module, exports) { var Pipeline = { defaultPipeline: null, pipeline: null, initPipeline: function(pipelineName) { if (pipelineName === undefined) { pipelineName = "TextureTintPipeline" } var renderer = this.scene.sys.game.renderer; if (renderer && renderer.gl && renderer.hasPipeline(pipelineName)) { this.defaultPipeline = renderer.getPipeline(pipelineName); this.pipeline = this.defaultPipeline; return true } return false }, setPipeline: function(pipelineName) { var renderer = this.scene.sys.game.renderer; if (renderer && renderer.gl && renderer.hasPipeline(pipelineName)) { this.pipeline = renderer.getPipeline(pipelineName) } return this }, resetPipeline: function() { this.pipeline = this.defaultPipeline; return this.pipeline !== null }, getPipelineName: function() { return this.pipeline.name } }; module.exports = Pipeline }, function(module, exports) { var Shuffle = function(array) { for (var i = array.length - 1; i > 0; i--) { var j = Math.floor(Math.random() * (i + 1)); var temp = array[i]; array[i] = array[j]; array[j] = temp } return array }; module.exports = Shuffle }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Components = __webpack_require__(14); var DegToRad = __webpack_require__(36); var EventEmitter = __webpack_require__(11); var Rectangle = __webpack_require__(9); var TransformMatrix = __webpack_require__(48); var ValueToColor = __webpack_require__(159); var Vector2 = __webpack_require__(3); var BaseCamera = new Class({ Extends: EventEmitter, Mixins: [Components.Alpha, Components.Visible], initialize: function BaseCamera(x, y, width, height) { if (x === undefined) { x = 0 } if (y === undefined) { y = 0 } if (width === undefined) { width = 0 } if (height === undefined) { height = 0 } EventEmitter.call(this); this.scene; this.sceneManager; this.config; this.id = 0; this.name = ""; this.resolution = 1; this.roundPixels = false; this.useBounds = false; this.worldView = new Rectangle; this.dirty = true; this._x = x; this._y = y; this._cx = 0; this._cy = 0; this._cw = 0; this._ch = 0; this._width = width; this._height = height; this._bounds = new Rectangle; this._scrollX = 0; this._scrollY = 0; this._zoom = 1; this._rotation = 0; this.matrix = new TransformMatrix; this.transparent = true; this.backgroundColor = ValueToColor("rgba(0,0,0,0)"); this.disableCull = false; this.culledObjects = []; this.midPoint = new Vector2(width / 2, height / 2); this.originX = .5; this.originY = .5; this._customViewport = false }, setOrigin: function(x, y) { if (x === undefined) { x = .5 } if (y === undefined) { y = x } this.originX = x; this.originY = y; return this }, getScroll: function(x, y, out) { if (out === undefined) { out = new Vector2 } var originX = this.width * .5; var originY = this.height * .5; out.x = x - originX; out.y = y - originY; if (this.useBounds) { out.x = this.clampX(out.x); out.y = this.clampY(out.y) } return out }, centerOn: function(x, y) { var originX = this.width * .5; var originY = this.height * .5; this.midPoint.set(x, y); this.scrollX = x - originX; this.scrollY = y - originY; if (this.useBounds) { this.scrollX = this.clampX(this.scrollX); this.scrollY = this.clampY(this.scrollY) } return this }, centerToBounds: function() { if (this.useBounds) { var bounds = this._bounds; var originX = this.width * .5; var originY = this.height * .5; this.midPoint.set(bounds.centerX, bounds.centerY); this.scrollX = bounds.centerX - originX; this.scrollY = bounds.centerY - originY } return this }, centerToSize: function() { this.scrollX = this.width * .5; this.scrollY = this.height * .5; return this }, cull: function(renderableObjects) { if (this.disableCull) { return renderableObjects } var cameraMatrix = this.matrix.matrix; var mva = cameraMatrix[0]; var mvb = cameraMatrix[1]; var mvc = cameraMatrix[2]; var mvd = cameraMatrix[3]; var determinant = mva * mvd - mvb * mvc; if (!determinant) { return renderableObjects } var mve = cameraMatrix[4]; var mvf = cameraMatrix[5]; var scrollX = this.scrollX; var scrollY = this.scrollY; var cameraW = this.width; var cameraH = this.height; var culledObjects = this.culledObjects; var length = renderableObjects.length; determinant = 1 / determinant; culledObjects.length = 0; for (var index = 0; index < length; ++index) { var object = renderableObjects[index]; if (!object.hasOwnProperty("width") || object.parentContainer) { culledObjects.push(object); continue } var objectW = object.width; var objectH = object.height; var objectX = object.x - scrollX * object.scrollFactorX - objectW * object.originX; var objectY = object.y - scrollY * object.scrollFactorY - objectH * object.originY; var tx = objectX * mva + objectY * mvc + mve; var ty = objectX * mvb + objectY * mvd + mvf; var tw = (objectX + objectW) * mva + (objectY + objectH) * mvc + mve; var th = (objectX + objectW) * mvb + (objectY + objectH) * mvd + mvf; var cullW = cameraW + objectW; var cullH = cameraH + objectH; if (tx > -objectW && ty > -objectH && tx < cullW && ty < cullH && tw > -objectW && th > -objectH && tw < cullW && th < cullH) { culledObjects.push(object) } } return culledObjects }, getWorldPoint: function(x, y, output) { if (output === undefined) { output = new Vector2 } var cameraMatrix = this.matrix.matrix; var mva = cameraMatrix[0]; var mvb = cameraMatrix[1]; var mvc = cameraMatrix[2]; var mvd = cameraMatrix[3]; var mve = cameraMatrix[4]; var mvf = cameraMatrix[5]; var determinant = mva * mvd - mvb * mvc; if (!determinant) { output.x = x; output.y = y; return output } determinant = 1 / determinant; var ima = mvd * determinant; var imb = -mvb * determinant; var imc = -mvc * determinant; var imd = mva * determinant; var ime = (mvc * mvf - mvd * mve) * determinant; var imf = (mvb * mve - mva * mvf) * determinant; var c = Math.cos(this.rotation); var s = Math.sin(this.rotation); var zoom = this.zoom; var res = this.resolution; var scrollX = this.scrollX; var scrollY = this.scrollY; var sx = x + (scrollX * c - scrollY * s) * zoom; var sy = y + (scrollX * s + scrollY * c) * zoom; output.x = (sx * ima + sy * imc) * res + ime; output.y = (sx * imb + sy * imd) * res + imf; return output }, ignore: function(entries) { var id = this.id; if (!Array.isArray(entries)) { entries = [entries] } for (var i = 0; i < entries.length; i++) { var entry = entries[i]; if (Array.isArray(entry)) { this.ignore(entry) } else if (entry.isParent) { this.ignore(entry.getChildren()) } else { entry.cameraFilter |= id } } return this }, preRender: function(baseScale, resolution) { var width = this.width; var height = this.height; var halfWidth = width * .5; var halfHeight = height * .5; var zoom = this.zoom * baseScale; var matrix = this.matrix; var originX = width * this.originX; var originY = height * this.originY; var sx = this.scrollX; var sy = this.scrollY; if (this.useBounds) { sx = this.clampX(sx); sy = this.clampY(sy) } if (this.roundPixels) { originX = Math.round(originX); originY = Math.round(originY) } this.scrollX = sx; this.scrollY = sy; var midX = sx + halfWidth; var midY = sy + halfHeight; this.midPoint.set(midX, midY); var displayWidth = width / zoom; var displayHeight = height / zoom; this.worldView.setTo(midX - displayWidth / 2, midY - displayHeight / 2, displayWidth, displayHeight); matrix.loadIdentity(); matrix.scale(resolution, resolution); matrix.translate(this.x + originX, this.y + originY); matrix.rotate(this.rotation); matrix.scale(zoom, zoom); matrix.translate(-originX, -originY) }, clampX: function(x) { var bounds = this._bounds; var dw = this.displayWidth; var bx = bounds.x + (dw - this.width) / 2; var bw = Math.max(bx, bx + bounds.width - dw); if (x < bx) { x = bx } else if (x > bw) { x = bw } return x }, clampY: function(y) { var bounds = this._bounds; var dh = this.displayHeight; var by = bounds.y + (dh - this.height) / 2; var bh = Math.max(by, by + bounds.height - dh); if (y < by) { y = by } else if (y > bh) { y = bh } return y }, removeBounds: function() { this.useBounds = false; this.dirty = true; this._bounds.setEmpty(); return this }, setAngle: function(value) { if (value === undefined) { value = 0 } this.rotation = DegToRad(value); return this }, setBackgroundColor: function(color) { if (color === undefined) { color = "rgba(0,0,0,0)" } this.backgroundColor = ValueToColor(color); this.transparent = this.backgroundColor.alpha === 0; return this }, setBounds: function(x, y, width, height, centerOn) { this._bounds.setTo(x, y, width, height); this.dirty = true; this.useBounds = true; if (centerOn) { this.centerToBounds() } else { this.scrollX = this.clampX(this.scrollX); this.scrollY = this.clampY(this.scrollY) } return this }, setName: function(value) { if (value === undefined) { value = "" } this.name = value; return this }, setPosition: function(x, y) { if (y === undefined) { y = x } this.x = x; this.y = y; return this }, setRotation: function(value) { if (value === undefined) { value = 0 } this.rotation = value; return this }, setRoundPixels: function(value) { this.roundPixels = value; return this }, setScene: function(scene) { if (this.scene && this._customViewport) { this.sceneManager.customViewports-- } this.scene = scene; this.config = scene.sys.game.config; this.sceneManager = scene.sys.game.scene; var res = this.config.resolution; this.resolution = res; this._cx = this._x * res; this._cy = this._y * res; this._cw = this._width * res; this._ch = this._height * res; this.updateSystem(); return this }, setScroll: function(x, y) { if (y === undefined) { y = x } this.scrollX = x; this.scrollY = y; return this }, setSize: function(width, height) { if (height === undefined) { height = width } this.width = width; this.height = height; return this }, setViewport: function(x, y, width, height) { this.x = x; this.y = y; this.width = width; this.height = height; return this }, setZoom: function(value) { if (value === undefined) { value = 1 } if (value === 0) { value = .001 } this.zoom = value; return this }, toJSON: function() { var output = { name: this.name, x: this.x, y: this.y, width: this.width, height: this.height, zoom: this.zoom, rotation: this.rotation, roundPixels: this.roundPixels, scrollX: this.scrollX, scrollY: this.scrollY, backgroundColor: this.backgroundColor.rgba }; if (this.useBounds) { output["bounds"] = { x: this._bounds.x, y: this._bounds.y, width: this._bounds.width, height: this._bounds.height } } return output }, update: function() {}, updateSystem: function() { if (!this.config) { return } var custom = this._x !== 0 || this._y !== 0 || this.config.width !== this._width || this.config.height !== this._height; var sceneManager = this.sceneManager; if (custom && !this._customViewport) { sceneManager.customViewports++ } else if (!custom && this._customViewport) { sceneManager.customViewports-- } this.dirty = true; this._customViewport = custom }, destroy: function() { this.emit("cameradestroy", this); this.removeAllListeners(); this.matrix.destroy(); this.culledObjects = []; if (this._customViewport) { this.sceneManager.customViewports-- } this._bounds = null; this.scene = null; this.config = null; this.sceneManager = null }, x: { get: function() { return this._x }, set: function(value) { this._x = value; this._cx = value * this.resolution; this.updateSystem() } }, y: { get: function() { return this._y }, set: function(value) { this._y = value; this._cy = value * this.resolution; this.updateSystem() } }, width: { get: function() { return this._width }, set: function(value) { this._width = value; this._cw = value * this.resolution; this.updateSystem() } }, height: { get: function() { return this._height }, set: function(value) { this._height = value; this._ch = value * this.resolution; this.updateSystem() } }, scrollX: { get: function() { return this._scrollX }, set: function(value) { this._scrollX = value; this.dirty = true } }, scrollY: { get: function() { return this._scrollY }, set: function(value) { this._scrollY = value; this.dirty = true } }, zoom: { get: function() { return this._zoom }, set: function(value) { this._zoom = value; this.dirty = true } }, rotation: { get: function() { return this._rotation }, set: function(value) { this._rotation = value; this.dirty = true } }, centerX: { get: function() { return this.x + .5 * this.width } }, centerY: { get: function() { return this.y + .5 * this.height } }, displayWidth: { get: function() { return this.width / this.zoom } }, displayHeight: { get: function() { return this.height / this.zoom } } }); module.exports = BaseCamera }, function(module, exports) { var prefix = ""; var Smoothing = function() { var getPrefix = function(context) { var vendors = ["i", "webkitI", "msI", "mozI", "oI"]; for (var i = 0; i < vendors.length; i++) { var s = vendors[i] + "mageSmoothingEnabled"; if (s in context) { return s } } return null }; var enable = function(context) { if (prefix === "") { prefix = getPrefix(context) } if (prefix) { context[prefix] = true } return context }; var disable = function(context) { if (prefix === "") { prefix = getPrefix(context) } if (prefix) { context[prefix] = false } return context }; var isEnabled = function(context) { return prefix !== null ? context[prefix] : null }; return { disable: disable, enable: enable, getPrefix: getPrefix, isEnabled: isEnabled } }; module.exports = Smoothing() }, function(module, exports) { var Linear = function(p0, p1, t) { return (p1 - p0) * t + p0 }; module.exports = Linear }, function(module, exports) { var AddToDOM = function(element, parent, overflowHidden) { if (overflowHidden === undefined) { overflowHidden = true } var target; if (parent) { if (typeof parent === "string") { target = document.getElementById(parent) } else if (typeof parent === "object" && parent.nodeType === 1) { target = parent } } else if (element.parentElement) { return element } if (!target) { target = document.body } if (overflowHidden && target.style) { target.style.overflow = "hidden" } target.appendChild(element); return element }; module.exports = AddToDOM }, function(module, exports, __webpack_require__) { var OS = __webpack_require__(92); var Browser = { chrome: false, chromeVersion: 0, edge: false, firefox: false, firefoxVersion: 0, ie: false, ieVersion: 0, mobileSafari: false, opera: false, safari: false, safariVersion: 0, silk: false, trident: false, tridentVersion: 0 }; function init() { var ua = navigator.userAgent; if (/Edge\/\d+/.test(ua)) { Browser.edge = true } else if (/Chrome\/(\d+)/.test(ua) && !OS.windowsPhone) { Browser.chrome = true; Browser.chromeVersion = parseInt(RegExp.$1, 10) } else if (/Firefox\D+(\d+)/.test(ua)) { Browser.firefox = true; Browser.firefoxVersion = parseInt(RegExp.$1, 10) } else if (/AppleWebKit/.test(ua) && OS.iOS) { Browser.mobileSafari = true } else if (/MSIE (\d+\.\d+);/.test(ua)) { Browser.ie = true; Browser.ieVersion = parseInt(RegExp.$1, 10) } else if (/Opera/.test(ua)) { Browser.opera = true } else if (/Safari/.test(ua) && !OS.windowsPhone) { Browser.safari = true } else if (/Trident\/(\d+\.\d+)(.*)rv:(\d+\.\d+)/.test(ua)) { Browser.ie = true; Browser.trident = true; Browser.tridentVersion = parseInt(RegExp.$1, 10); Browser.ieVersion = parseInt(RegExp.$3, 10) } if (/Silk/.test(ua)) { Browser.silk = true } return Browser } module.exports = init() }, function(module, exports) { var IsSizePowerOfTwo = function(width, height) { return width > 0 && (width & width - 1) === 0 && height > 0 && (height & height - 1) === 0 }; module.exports = IsSizePowerOfTwo }, function(module, exports) { var CONST = { PENDING: 0, INIT: 1, START: 2, LOADING: 3, CREATING: 4, RUNNING: 5, PAUSED: 6, SLEEPING: 7, SHUTDOWN: 8, DESTROYED: 9 }; module.exports = CONST }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Clone = __webpack_require__(64); var EventEmitter = __webpack_require__(11); var NOOP = __webpack_require__(2); var BaseSoundManager = new Class({ Extends: EventEmitter, initialize: function BaseSoundManager(game) { EventEmitter.call(this); this.game = game; this.jsonCache = game.cache.json; this.sounds = []; this.mute = false; this.volume = 1; this.pauseOnBlur = true; this._rate = 1; this._detune = 0; this.locked = this.locked || false; this.unlocked = false; game.events.on("blur", function() { if (this.pauseOnBlur) { this.onBlur() } }, this); game.events.on("focus", function() { if (this.pauseOnBlur) { this.onFocus() } }, this); game.events.on("prestep", this.update, this); game.events.once("destroy", this.destroy, this) }, add: NOOP, addAudioSprite: function(key, config) { if (config === undefined) { config = {} } var sound = this.add(key, config); sound.spritemap = this.jsonCache.get(key).spritemap; for (var markerName in sound.spritemap) { if (!sound.spritemap.hasOwnProperty(markerName)) { continue } var markerConfig = Clone(config); var marker = sound.spritemap[markerName]; markerConfig.loop = marker.hasOwnProperty("loop") ? marker.loop : false; sound.addMarker({ name: markerName, start: marker.start, duration: marker.end - marker.start, config: markerConfig }) } return sound }, play: function(key, extra) { var sound = this.add(key); sound.once("ended", sound.destroy, sound); if (extra) { if (extra.name) { sound.addMarker(extra); return sound.play(extra.name) } else { return sound.play(extra) } } else { return sound.play() } }, playAudioSprite: function(key, spriteName, config) { var sound = this.addAudioSprite(key); sound.once("ended", sound.destroy, sound); return sound.play(spriteName, config) }, remove: function(sound) { var index = this.sounds.indexOf(sound); if (index !== -1) { sound.destroy(); this.sounds.splice(index, 1); return true } return false }, removeByKey: function(key) { var removed = 0; for (var i = this.sounds.length - 1; i >= 0; i--) { var sound = this.sounds[i]; if (sound.key === key) { sound.destroy(); this.sounds.splice(i, 1); removed++ } } return removed }, pauseAll: function() { this.forEachActiveSound(function(sound) { sound.pause() }); this.emit("pauseall", this) }, resumeAll: function() { this.forEachActiveSound(function(sound) { sound.resume() }); this.emit("resumeall", this) }, stopAll: function() { this.forEachActiveSound(function(sound) { sound.stop() }); this.emit("stopall", this) }, unlock: NOOP, onBlur: NOOP, onFocus: NOOP, update: function(time, delta) { if (this.unlocked) { this.unlocked = false; this.locked = false; this.emit("unlocked", this) } for (var i = this.sounds.length - 1; i >= 0; i--) { if (this.sounds[i].pendingRemove) { this.sounds.splice(i, 1) } } this.sounds.forEach(function(sound) { sound.update(time, delta) }) }, destroy: function() { this.removeAllListeners(); this.forEachActiveSound(function(sound) { sound.destroy() }); this.sounds.length = 0; this.sounds = null; this.game = null }, forEachActiveSound: function(callback, scope) { var _this = this; this.sounds.forEach(function(sound, index) { if (!sound.pendingRemove) { callback.call(scope || _this, sound, index, _this.sounds) } }) }, setRate: function(value) { this.rate = value; return this }, rate: { get: function() { return this._rate }, set: function(value) { this._rate = value; this.forEachActiveSound(function(sound) { sound.calculateRate() }); this.emit("rate", this, value) } }, setDetune: function(value) { this.detune = value; return this }, detune: { get: function() { return this._detune }, set: function(value) { this._detune = value; this.forEachActiveSound(function(sound) { sound.calculateRate() }); this.emit("detune", this, value) } } }); module.exports = BaseSoundManager }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var EventEmitter = __webpack_require__(11); var Extend = __webpack_require__(19); var NOOP = __webpack_require__(2); var BaseSound = new Class({ Extends: EventEmitter, initialize: function BaseSound(manager, key, config) { EventEmitter.call(this); this.manager = manager; this.key = key; this.isPlaying = false; this.isPaused = false; this.totalRate = 1; this.duration = this.duration || 0; this.totalDuration = this.totalDuration || 0; this.config = { mute: false, volume: 1, rate: 1, detune: 0, seek: 0, loop: false, delay: 0 }; this.currentConfig = this.config; this.config = Extend(this.config, config); this.markers = {}; this.currentMarker = null; this.pendingRemove = false }, addMarker: function(marker) { if (!marker || !marker.name || typeof marker.name !== "string") { return false } if (this.markers[marker.name]) { console.error("addMarker " + marker.name + " already exists in Sound"); return false } marker = Extend(true, { name: "", start: 0, duration: this.totalDuration - (marker.start || 0), config: { mute: false, volume: 1, rate: 1, detune: 0, seek: 0, loop: false, delay: 0 } }, marker); this.markers[marker.name] = marker; return true }, updateMarker: function(marker) { if (!marker || !marker.name || typeof marker.name !== "string") { return false } if (!this.markers[marker.name]) { console.warn("Audio Marker: " + marker.name + " missing in Sound: " + this.key); return false } this.markers[marker.name] = Extend(true, this.markers[marker.name], marker); return true }, removeMarker: function(markerName) { var marker = this.markers[markerName]; if (!marker) { return null } this.markers[markerName] = null; return marker }, play: function(markerName, config) { if (markerName === undefined) { markerName = "" } if (typeof markerName === "object") { config = markerName; markerName = "" } if (typeof markerName !== "string") { return false } if (!markerName) { this.currentMarker = null; this.currentConfig = this.config; this.duration = this.totalDuration } else { if (!this.markers[markerName]) { console.warn("Marker: " + markerName + " missing in Sound: " + this.key); return false } this.currentMarker = this.markers[markerName]; this.currentConfig = this.currentMarker.config; this.duration = this.currentMarker.duration } this.resetConfig(); this.currentConfig = Extend(this.currentConfig, config); this.isPlaying = true; this.isPaused = false; return true }, pause: function() { if (this.isPaused || !this.isPlaying) { return false } this.isPlaying = false; this.isPaused = true; return true }, resume: function() { if (!this.isPaused || this.isPlaying) { return false } this.isPlaying = true; this.isPaused = false; return true }, stop: function() { if (!this.isPaused && !this.isPlaying) { return false } this.isPlaying = false; this.isPaused = false; this.resetConfig(); return true }, applyConfig: function() { this.mute = this.currentConfig.mute; this.volume = this.currentConfig.volume; this.rate = this.currentConfig.rate; this.detune = this.currentConfig.detune; this.loop = this.currentConfig.loop }, resetConfig: function() { this.currentConfig.seek = 0; this.currentConfig.delay = 0 }, update: NOOP, calculateRate: function() { var cent = 1.0005777895065548; var totalDetune = this.currentConfig.detune + this.manager.detune; var detuneRate = Math.pow(cent, totalDetune); this.totalRate = this.currentConfig.rate * this.manager.rate * detuneRate }, destroy: function() { if (this.pendingRemove) { return } this.emit("destroy", this); this.pendingRemove = true; this.manager = null; this.key = ""; this.removeAllListeners(); this.isPlaying = false; this.isPaused = false; this.config = null; this.currentConfig = null; this.markers = null; this.currentMarker = null } }); module.exports = BaseSound }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Clamp = __webpack_require__(23); var Extend = __webpack_require__(19); var Frame = new Class({ initialize: function Frame(texture, name, sourceIndex, x, y, width, height) { this.texture = texture; this.name = name; this.source = texture.source[sourceIndex]; this.sourceIndex = sourceIndex; this.glTexture = this.source.glTexture; this.cutX; this.cutY; this.cutWidth; this.cutHeight; this.x = 0; this.y = 0; this.width; this.height; this.halfWidth; this.halfHeight; this.centerX; this.centerY; this.pivotX = 0; this.pivotY = 0; this.customPivot = false; this.rotated = false; this.autoRound = -1; this.customData = {}; this.u0 = 0; this.v0 = 0; this.u1 = 0; this.v1 = 0; this.data = { cut: { x: 0, y: 0, w: 0, h: 0, r: 0, b: 0 }, trim: false, sourceSize: { w: 0, h: 0 }, spriteSourceSize: { x: 0, y: 0, w: 0, h: 0, r: 0, b: 0 }, radius: 0, drawImage: { x: 0, y: 0, width: 0, height: 0 } }; this.setSize(width, height, x, y) }, setSize: function(width, height, x, y) { if (x === undefined) { x = 0 } if (y === undefined) { y = 0 } this.cutX = x; this.cutY = y; this.cutWidth = width; this.cutHeight = height; this.width = width; this.height = height; this.halfWidth = Math.floor(width * .5); this.halfHeight = Math.floor(height * .5); this.centerX = Math.floor(width / 2); this.centerY = Math.floor(height / 2); var data = this.data; var cut = data.cut; cut.x = x; cut.y = y; cut.w = width; cut.h = height; cut.r = x + width; cut.b = y + height; data.sourceSize.w = width; data.sourceSize.h = height; data.spriteSourceSize.w = width; data.spriteSourceSize.h = height; data.radius = .5 * Math.sqrt(width * width + height * height); var drawImage = data.drawImage; drawImage.x = x; drawImage.y = y; drawImage.width = width; drawImage.height = height; return this.updateUVs() }, setTrim: function(actualWidth, actualHeight, destX, destY, destWidth, destHeight) { var data = this.data; var ss = data.spriteSourceSize; data.trim = true; data.sourceSize.w = actualWidth; data.sourceSize.h = actualHeight; ss.x = destX; ss.y = destY; ss.w = destWidth; ss.h = destHeight; ss.r = destX + destWidth; ss.b = destY + destHeight; this.x = destX; this.y = destY; this.width = destWidth; this.height = destHeight; this.halfWidth = destWidth * .5; this.halfHeight = destHeight * .5; this.centerX = Math.floor(destWidth / 2); this.centerY = Math.floor(destHeight / 2); return this.updateUVs() }, setCropUVs: function(crop, x, y, width, height, flipX, flipY) { var cx = this.cutX; var cy = this.cutY; var cw = this.cutWidth; var ch = this.cutHeight; var rw = this.realWidth; var rh = this.realHeight; x = Clamp(x, 0, rw); y = Clamp(y, 0, rh); width = Clamp(width, 0, rw - x); height = Clamp(height, 0, rh - y); var ox = cx + x; var oy = cy + y; var ow = width; var oh = height; var data = this.data; if (data.trim) { var ss = data.spriteSourceSize; width = Clamp(width, 0, cw - x); height = Clamp(height, 0, ch - y); var cropRight = x + width; var cropBottom = y + height; var intersects = !(ss.r < x || ss.b < y || ss.x > cropRight || ss.y > cropBottom); if (intersects) { var ix = Math.max(ss.x, x); var iy = Math.max(ss.y, y); var iw = Math.min(ss.r, cropRight) - ix; var ih = Math.min(ss.b, cropBottom) - iy; ow = iw; oh = ih; if (flipX) { ox = cx + (cw - (ix - ss.x) - iw) } else { ox = cx + (ix - ss.x) } if (flipY) { oy = cy + (ch - (iy - ss.y) - ih) } else { oy = cy + (iy - ss.y) } x = ix; y = iy; width = iw; height = ih } else { ox = 0; oy = 0; ow = 0; oh = 0 } } else { if (flipX) { ox = cx + (cw - x - width) } if (flipY) { oy = cy + (ch - y - height) } } var tw = this.source.width; var th = this.source.height; crop.u0 = Math.max(0, ox / tw); crop.v0 = Math.max(0, oy / th); crop.u1 = Math.min(1, (ox + ow) / tw); crop.v1 = Math.min(1, (oy + oh) / th); crop.x = x; crop.y = y; crop.cx = ox; crop.cy = oy; crop.cw = ow; crop.ch = oh; crop.width = width; crop.height = height; crop.flipX = flipX; crop.flipY = flipY; return crop }, updateCropUVs: function(crop, flipX, flipY) { return this.setCropUVs(crop, crop.x, crop.y, crop.width, crop.height, flipX, flipY) }, updateUVs: function() { var cx = this.cutX; var cy = this.cutY; var cw = this.cutWidth; var ch = this.cutHeight; var cd = this.data.drawImage; cd.width = cw; cd.height = ch; var tw = this.source.width; var th = this.source.height; this.u0 = cx / tw; this.v0 = cy / th; this.u1 = (cx + cw) / tw; this.v1 = (cy + ch) / th; return this }, updateUVsInverted: function() { var tw = this.source.width; var th = this.source.height; this.u0 = (this.cutX + this.cutHeight) / tw; this.v0 = this.cutY / th; this.u1 = this.cutX / tw; this.v1 = (this.cutY + this.cutWidth) / th; return this }, clone: function() { var clone = new Frame(this.texture, this.name, this.sourceIndex); clone.cutX = this.cutX; clone.cutY = this.cutY; clone.cutWidth = this.cutWidth; clone.cutHeight = this.cutHeight; clone.x = this.x; clone.y = this.y; clone.width = this.width; clone.height = this.height; clone.halfWidth = this.halfWidth; clone.halfHeight = this.halfHeight; clone.centerX = this.centerX; clone.centerY = this.centerY; clone.rotated = this.rotated; clone.data = Extend(true, clone.data, this.data); clone.updateUVs(); return clone }, destroy: function() { this.texture = null; this.source = null }, realWidth: { get: function() { return this.data.sourceSize.w } }, realHeight: { get: function() { return this.data.sourceSize.h } }, radius: { get: function() { return this.data.radius } }, trimmed: { get: function() { return this.data.trim } }, canvasData: { get: function() { return this.data.drawImage } } }); module.exports = Frame }, function(module, exports, __webpack_require__) { var ArrayUtils = __webpack_require__(175); var Class = __webpack_require__(0); var NOOP = __webpack_require__(2); var StableSort = __webpack_require__(123); var List = new Class({ initialize: function List(parent) { this.parent = parent; this.list = []; this.position = 0; this.addCallback = NOOP; this.removeCallback = NOOP; this._sortKey = "" }, add: function(child, skipCallback) { if (skipCallback) { return ArrayUtils.Add(this.list, child) } else { return ArrayUtils.Add(this.list, child, 0, this.addCallback, this) } }, addAt: function(child, index, skipCallback) { if (skipCallback) { return ArrayUtils.AddAt(this.list, child, index) } else { return ArrayUtils.AddAt(this.list, child, index, 0, this.addCallback, this) } }, getAt: function(index) { return this.list[index] }, getIndex: function(child) { return this.list.indexOf(child) }, sort: function(property) { if (property) { this._sortKey = property; StableSort.inplace(this.list, this.sortHandler) } return this }, sortHandler: function(childA, childB) { return childA[this._sortKey] - childB[this._sortKey] }, getByName: function(name) { return ArrayUtils.GetFirst(this.list, "name", name) }, getRandom: function(startIndex, length) { return ArrayUtils.GetRandom(this.list, startIndex, length) }, getFirst: function(property, value, startIndex, endIndex) { return ArrayUtils.GetFirstElement(this.list, property, value, startIndex, endIndex) }, getAll: function(property, value, startIndex, endIndex) { return ArrayUtils.GetAll(this.list, property, value, startIndex, endIndex) }, count: function(property, value) { return ArrayUtils.CountAllMatching(this.list, property, value) }, swap: function(child1, child2) { ArrayUtils.Swap(this.list, child1, child2) }, moveTo: function(child, index) { return ArrayUtils.MoveTo(this.list, child, index) }, remove: function(child, skipCallback) { if (skipCallback) { return ArrayUtils.Remove(this.list, child) } else { return ArrayUtils.Remove(this.list, child, this.removeCallback, this) } }, removeAt: function(index, skipCallback) { if (skipCallback) { return ArrayUtils.RemoveAt(this.list, index) } else { return ArrayUtils.RemoveAt(this.list, index, this.removeCallback, this) } }, removeBetween: function(startIndex, endIndex, skipCallback) { if (skipCallback) { return ArrayUtils.RemoveBetween(this.list, startIndex, endIndex) } else { return ArrayUtils.RemoveBetween(this.list, startIndex, endIndex, this.removeCallback, this) } }, removeAll: function(skipCallback) { var i = this.list.length; while (i--) { this.remove(this.list[i], skipCallback) } return this }, bringToTop: function(child) { return ArrayUtils.BringToTop(this.list, child) }, sendToBack: function(child) { return ArrayUtils.SendToBack(this.list, child) }, moveUp: function(child) { ArrayUtils.MoveUp(this.list, child); return child }, moveDown: function(child) { ArrayUtils.MoveDown(this.list, child); return child }, reverse: function() { this.list.reverse(); return this }, shuffle: function() { ArrayUtils.Shuffle(this.list); return this }, replace: function(oldChild, newChild) { return ArrayUtils.Replace(this.list, oldChild, newChild) }, exists: function(child) { return this.list.indexOf(child) > -1 }, setAll: function(property, value, startIndex, endIndex) { ArrayUtils.SetAll(this.list, property, value, startIndex, endIndex); return this }, each: function(callback, context) { var args = [null]; for (var i = 2; i < arguments.length; i++) { args.push(arguments[i]) } for (i = 0; i < this.list.length; i++) { args[0] = this.list[i]; callback.apply(context, args) } }, shutdown: function() { this.removeAll(); this.list = [] }, destroy: function() { this.removeAll(); this.parent = null; this.addCallback = null; this.removeCallback = null }, length: { get: function() { return this.list.length } }, first: { get: function() { this.position = 0; if (this.list.length > 0) { return this.list[0] } else { return null } } }, last: { get: function() { if (this.list.length > 0) { this.position = this.list.length - 1; return this.list[this.position] } else { return null } } }, next: { get: function() { if (this.position < this.list.length) { this.position++; return this.list[this.position] } else { return null } } }, previous: { get: function() { if (this.position > 0) { this.position--; return this.list[this.position] } else { return null } } } }); module.exports = List }, function(module, exports, __webpack_require__) { var CheckMatrix = __webpack_require__(176); var TransposeMatrix = __webpack_require__(335); var RotateMatrix = function(matrix, direction) { if (direction === undefined) { direction = 90 } if (!CheckMatrix(matrix)) { return null } if (typeof direction !== "string") { direction = (direction % 360 + 360) % 360 } if (direction === 90 || direction === -270 || direction === "rotateLeft") { matrix = TransposeMatrix(matrix); matrix.reverse() } else if (direction === -90 || direction === 270 || direction === "rotateRight") { matrix.reverse(); matrix = TransposeMatrix(matrix) } else if (Math.abs(direction) === 180 || direction === "rotate180") { for (var i = 0; i < matrix.length; i++) { matrix[i].reverse() } matrix.reverse() } return matrix }; module.exports = RotateMatrix }, function(module, exports, __webpack_require__) { (function() { var stable = function(arr, comp) { return exec(arr.slice(), comp) }; stable.inplace = function(arr, comp) { var result = exec(arr, comp); if (result !== arr) { pass(result, null, arr.length, arr) } return arr }; function exec(arr, comp) { if (typeof comp !== "function") { comp = function(a, b) { return String(a).localeCompare(b) } } var len = arr.length; if (len <= 1) { return arr } var buffer = new Array(len); for (var chk = 1; chk < len; chk *= 2) { pass(arr, comp, chk, buffer); var tmp = arr; arr = buffer; buffer = tmp } return arr } var pass = function(arr, comp, chk, result) { var len = arr.length; var i = 0; var dbl = chk * 2; var l, r, e; var li, ri; for (l = 0; l < len; l += dbl) { r = l + chk; e = r + chk; if (r > len) r = len; if (e > len) e = len; li = l; ri = r; while (true) { if (li < r && ri < e) { if (comp(arr[li], arr[ri]) <= 0) { result[i++] = arr[li++] } else { result[i++] = arr[ri++] } } else if (li < r) { result[i++] = arr[li++] } else if (ri < e) { result[i++] = arr[ri++] } else { break } } } }; if (true) { module.exports = stable } else { window.stable = stable } })() }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Components = __webpack_require__(14); var GameObject = __webpack_require__(12); var GetBitmapTextSize = __webpack_require__(694); var ParseFromAtlas = __webpack_require__(695); var Render = __webpack_require__(696); var BitmapText = new Class({ Extends: GameObject, Mixins: [Components.Alpha, Components.BlendMode, Components.Depth, Components.Mask, Components.Origin, Components.Pipeline, Components.ScaleMode, Components.ScrollFactor, Components.Texture, Components.Tint, Components.Transform, Components.Visible, Render], initialize: function BitmapText(scene, x, y, font, text, size, align) { if (text === undefined) { text = "" } if (align === undefined) { align = 0 } GameObject.call(this, scene, "BitmapText"); this.font = font; var entry = this.scene.sys.cache.bitmapFont.get(font); this.fontData = entry.data; this._text = ""; this._fontSize = size || this.fontData.size; this._letterSpacing = 0; this._align = align; this._bounds = GetBitmapTextSize(this, false, this._bounds); this._dirty = false; this.setTexture(entry.texture, entry.frame); this.setPosition(x, y); this.setOrigin(0, 0); this.initPipeline(); this.setText(text) }, setLeftAlign: function() { this._align = BitmapText.ALIGN_LEFT; this._dirty = true; return this }, setCenterAlign: function() { this._align = BitmapText.ALIGN_CENTER; this._dirty = true; return this }, setRightAlign: function() { this._align = BitmapText.ALIGN_RIGHT; this._dirty = true; return this }, setFontSize: function(size) { this._fontSize = size; this._dirty = true; return this }, setLetterSpacing: function(spacing) { if (spacing === undefined) { spacing = 0 } this._letterSpacing = spacing; this._dirty = true; return this }, setText: function(value) { if (!value && value !== 0) { value = "" } if (Array.isArray(value)) { value = value.join("\n") } if (value !== this.text) { this._text = value.toString(); this._dirty = true; this.updateDisplayOrigin() } return this }, getTextBounds: function(round) { if (this._dirty) { GetBitmapTextSize(this, round, this._bounds) } return this._bounds }, setFont: function(key, size, align) { if (size === undefined) { size = this._fontSize } if (align === undefined) { align = this._align } if (key !== this.font) { var entry = this.scene.sys.cache.bitmapFont.get(key); if (entry) { this.font = key; this.fontData = entry.data; this._fontSize = size; this._align = align; this.setTexture(entry.texture, entry.frame); GetBitmapTextSize(this, false, this._bounds) } } return this }, align: { set: function(value) { this._align = value; this._dirty = true }, get: function() { return this._align } }, text: { set: function(value) { this.setText(value) }, get: function() { return this._text } }, fontSize: { set: function(value) { this._fontSize = value; this._dirty = true }, get: function() { return this._fontSize } }, letterSpacing: { set: function(value) { this._letterSpacing = value; this._dirty = true }, get: function() { return this._letterSpacing } }, width: { get: function() { this.getTextBounds(false); return this._bounds.global.width } }, height: { get: function() { this.getTextBounds(false); return this._bounds.global.height } }, toJSON: function() { var out = Components.ToJSON(this); var data = { font: this.font, text: this.text, fontSize: this.fontSize, letterSpacing: this.letterSpacing, align: this.align }; out.data = data; return out } }); BitmapText.ALIGN_LEFT = 0; BitmapText.ALIGN_CENTER = 1; BitmapText.ALIGN_RIGHT = 2; BitmapText.ParseFromAtlas = ParseFromAtlas; module.exports = BitmapText }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Vector4 = new Class({ initialize: function Vector4(x, y, z, w) { this.x = 0; this.y = 0; this.z = 0; this.w = 0; if (typeof x === "object") { this.x = x.x || 0; this.y = x.y || 0; this.z = x.z || 0; this.w = x.w || 0 } else { this.x = x || 0; this.y = y || 0; this.z = z || 0; this.w = w || 0 } }, clone: function() { return new Vector4(this.x, this.y, this.z, this.w) }, copy: function(src) { this.x = src.x; this.y = src.y; this.z = src.z || 0; this.w = src.w || 0; return this }, equals: function(v) { return this.x === v.x && this.y === v.y && this.z === v.z && this.w === v.w }, set: function(x, y, z, w) { if (typeof x === "object") { this.x = x.x || 0; this.y = x.y || 0; this.z = x.z || 0; this.w = x.w || 0 } else { this.x = x || 0; this.y = y || 0; this.z = z || 0; this.w = w || 0 } return this }, add: function(v) { this.x += v.x; this.y += v.y; this.z += v.z || 0; this.w += v.w || 0; return this }, subtract: function(v) { this.x -= v.x; this.y -= v.y; this.z -= v.z || 0; this.w -= v.w || 0; return this }, scale: function(scale) { this.x *= scale; this.y *= scale; this.z *= scale; this.w *= scale; return this }, length: function() { var x = this.x; var y = this.y; var z = this.z; var w = this.w; return Math.sqrt(x * x + y * y + z * z + w * w) }, lengthSq: function() { var x = this.x; var y = this.y; var z = this.z; var w = this.w; return x * x + y * y + z * z + w * w }, normalize: function() { var x = this.x; var y = this.y; var z = this.z; var w = this.w; var len = x * x + y * y + z * z + w * w; if (len > 0) { len = 1 / Math.sqrt(len); this.x = x * len; this.y = y * len; this.z = z * len; this.w = w * len } return this }, dot: function(v) { return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w }, lerp: function(v, t) { if (t === undefined) { t = 0 } var ax = this.x; var ay = this.y; var az = this.z; var aw = this.w; this.x = ax + t * (v.x - ax); this.y = ay + t * (v.y - ay); this.z = az + t * (v.z - az); this.w = aw + t * (v.w - aw); return this }, multiply: function(v) { this.x *= v.x; this.y *= v.y; this.z *= v.z || 1; this.w *= v.w || 1; return this }, divide: function(v) { this.x /= v.x; this.y /= v.y; this.z /= v.z || 1; this.w /= v.w || 1; return this }, distance: function(v) { var dx = v.x - this.x; var dy = v.y - this.y; var dz = v.z - this.z || 0; var dw = v.w - this.w || 0; return Math.sqrt(dx * dx + dy * dy + dz * dz + dw * dw) }, distanceSq: function(v) { var dx = v.x - this.x; var dy = v.y - this.y; var dz = v.z - this.z || 0; var dw = v.w - this.w || 0; return dx * dx + dy * dy + dz * dz + dw * dw }, negate: function() { this.x = -this.x; this.y = -this.y; this.z = -this.z; this.w = -this.w; return this }, transformMat4: function(mat) { var x = this.x; var y = this.y; var z = this.z; var w = this.w; var m = mat.val; this.x = m[0] * x + m[4] * y + m[8] * z + m[12] * w; this.y = m[1] * x + m[5] * y + m[9] * z + m[13] * w; this.z = m[2] * x + m[6] * y + m[10] * z + m[14] * w; this.w = m[3] * x + m[7] * y + m[11] * z + m[15] * w; return this }, transformQuat: function(q) { var x = this.x; var y = this.y; var z = this.z; var qx = q.x; var qy = q.y; var qz = q.z; var 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; this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy; this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz; this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx; return this }, reset: function() { this.x = 0; this.y = 0; this.z = 0; this.w = 0; return this } }); Vector4.prototype.sub = Vector4.prototype.subtract; Vector4.prototype.mul = Vector4.prototype.multiply; Vector4.prototype.div = Vector4.prototype.divide; Vector4.prototype.dist = Vector4.prototype.distance; Vector4.prototype.distSq = Vector4.prototype.distanceSq; Vector4.prototype.len = Vector4.prototype.length; Vector4.prototype.lenSq = Vector4.prototype.lengthSq; module.exports = Vector4 }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Components = __webpack_require__(14); var GameObject = __webpack_require__(12); var MeshRender = __webpack_require__(812); var Mesh = new Class({ Extends: GameObject, Mixins: [Components.Alpha, Components.BlendMode, Components.Depth, Components.Flip, Components.GetBounds, Components.Mask, Components.Origin, Components.Pipeline, Components.ScaleMode, Components.Size, Components.Texture, Components.Transform, Components.Visible, Components.ScrollFactor, MeshRender], initialize: function Mesh(scene, x, y, vertices, uv, colors, alphas, texture, frame) { GameObject.call(this, scene, "Mesh"); if (vertices.length !== uv.length) { throw new Error("Mesh Vertex count must match UV count") } var verticesUB = vertices.length / 2 | 0; if (colors.length > 0 && colors.length < verticesUB) { throw new Error("Mesh Color count must match Vertex count") } if (alphas.length > 0 && alphas.length < verticesUB) { throw new Error("Mesh Alpha count must match Vertex count") } var i; if (colors.length === 0) { for (i = 0; i < verticesUB; ++i) { colors[i] = 16777215 } } if (alphas.length === 0) { for (i = 0; i < verticesUB; ++i) { alphas[i] = 1 } } this.vertices = new Float32Array(vertices); this.uv = new Float32Array(uv); this.colors = new Uint32Array(colors); this.alphas = new Float32Array(alphas); this.tintFill = false; this.setTexture(texture, frame); this.setPosition(x, y); this.setSizeToFrame(); this.setOrigin(); this.initPipeline() } }); module.exports = Mesh }, function(module, exports, __webpack_require__) { var Point = __webpack_require__(6); var LineToLine = function(line1, line2, out) { if (out === undefined) { out = new Point } var x1 = line1.x1; var y1 = line1.y1; var x2 = line1.x2; var y2 = line1.y2; var x3 = line2.x1; var y3 = line2.y1; var x4 = line2.x2; var y4 = line2.y2; var numA = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3); var numB = (x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3); var deNom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1); if (deNom === 0) { return false } var uA = numA / deNom; var uB = numB / deNom; if (uA >= 0 && uA <= 1 && uB >= 0 && uB <= 1) { out.x = x1 + uA * (x2 - x1); out.y = y1 + uA * (y2 - y1); return true } return false }; module.exports = LineToLine }, function(module, exports, __webpack_require__) { var GetValue = __webpack_require__(4); var inputPlugins = {}; var InputPluginCache = {}; InputPluginCache.register = function(key, plugin, mapping, settingsKey, configKey) { inputPlugins[key] = { plugin: plugin, mapping: mapping, settingsKey: settingsKey, configKey: configKey } }; InputPluginCache.getPlugin = function(key) { return inputPlugins[key] }; InputPluginCache.install = function(target) { var sys = target.scene.sys; var settings = sys.settings.input; var config = sys.game.config; for (var key in inputPlugins) { var source = inputPlugins[key].plugin; var mapping = inputPlugins[key].mapping; var settingsKey = inputPlugins[key].settingsKey; var configKey = inputPlugins[key].configKey; if (GetValue(settings, settingsKey, config[configKey])) { target[mapping] = new source(target) } } }; InputPluginCache.remove = function(key) { if (inputPlugins.hasOwnProperty(key)) { delete inputPlugins[key] } }; module.exports = InputPluginCache }, function(module, exports) { var XHRSettings = function(responseType, async, user, password, timeout) { if (responseType === undefined) { responseType = "" } if (async === undefined) { async = true } if (user === undefined) { user = "" } if (password === undefined) { password = "" } if (timeout === undefined) { timeout = 0 } return { responseType: responseType, async: async, user: user, password: password, timeout: timeout, header: undefined, headerValue: undefined, requestedWith: false, overrideMimeType: undefined } }; module.exports = XHRSettings }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Components = __webpack_require__(417); var Sprite = __webpack_require__(50); var ArcadeSprite = new Class({ Extends: Sprite, Mixins: [Components.Acceleration, Components.Angular, Components.Bounce, Components.Debug, Components.Drag, Components.Enable, Components.Friction, Components.Gravity, Components.Immovable, Components.Mass, Components.Size, Components.Velocity], initialize: function ArcadeSprite(scene, x, y, texture, frame) { Sprite.call(this, scene, x, y, texture, frame); this.body = null } }); module.exports = ArcadeSprite }, function(module, exports, __webpack_require__) { module.exports = { Bounce: __webpack_require__(1056), Collision: __webpack_require__(1057), Force: __webpack_require__(1058), Friction: __webpack_require__(1059), Gravity: __webpack_require__(1060), Mass: __webpack_require__(1061), Static: __webpack_require__(1062), Sensor: __webpack_require__(1063), SetBody: __webpack_require__(1064), Sleep: __webpack_require__(1066), Transform: __webpack_require__(1067), Velocity: __webpack_require__(1068) } }, function(module, exports) { var Pair = {}; module.exports = Pair; (function() { Pair.create = function(collision, timestamp) { var bodyA = collision.bodyA, bodyB = collision.bodyB; var pair = { id: Pair.id(bodyA, bodyB), bodyA: bodyA, bodyB: bodyB, activeContacts: [], separation: 0, isActive: true, confirmedActive: true, isSensor: bodyA.isSensor || bodyB.isSensor, timeCreated: timestamp, timeUpdated: timestamp, collision: null, inverseMass: 0, friction: 0, frictionStatic: 0, restitution: 0, slop: 0 }; Pair.update(pair, collision, timestamp); return pair }; Pair.update = function(pair, collision, timestamp) { pair.collision = collision; if (collision.collided) { var supports = collision.supports, activeContacts = pair.activeContacts, parentA = collision.parentA, parentB = collision.parentB; pair.inverseMass = parentA.inverseMass + parentB.inverseMass; pair.friction = Math.min(parentA.friction, parentB.friction); pair.frictionStatic = Math.max(parentA.frictionStatic, parentB.frictionStatic); pair.restitution = Math.max(parentA.restitution, parentB.restitution); pair.slop = Math.max(parentA.slop, parentB.slop); for (var i = 0; i < supports.length; i++) { activeContacts[i] = supports[i].contact } var supportCount = supports.length; if (supportCount < activeContacts.length) { activeContacts.length = supportCount } pair.separation = collision.depth; Pair.setActive(pair, true, timestamp) } else { if (pair.isActive === true) Pair.setActive(pair, false, timestamp) } }; Pair.setActive = function(pair, isActive, timestamp) { if (isActive) { pair.isActive = true; pair.timeUpdated = timestamp } else { pair.isActive = false; pair.activeContacts.length = 0 } }; Pair.id = function(bodyA, bodyB) { if (bodyA.id < bodyB.id) { return "A" + bodyA.id + "B" + bodyB.id } else { return "A" + bodyB.id + "B" + bodyA.id } } })() }, function(module, exports, __webpack_require__) { module.exports = { CalculateFacesAt: __webpack_require__(211), CalculateFacesWithin: __webpack_require__(53), Copy: __webpack_require__(1090), CreateFromTiles: __webpack_require__(1091), CullTiles: __webpack_require__(1092), Fill: __webpack_require__(1093), FilterTiles: __webpack_require__(1094), FindByIndex: __webpack_require__(1095), FindTile: __webpack_require__(1096), ForEachTile: __webpack_require__(1097), GetTileAt: __webpack_require__(134), GetTileAtWorldXY: __webpack_require__(1098), GetTilesWithin: __webpack_require__(21), GetTilesWithinShape: __webpack_require__(1099), GetTilesWithinWorldXY: __webpack_require__(1100), HasTileAt: __webpack_require__(449), HasTileAtWorldXY: __webpack_require__(1101), IsInLayerBounds: __webpack_require__(104), PutTileAt: __webpack_require__(212), PutTileAtWorldXY: __webpack_require__(1102), PutTilesAt: __webpack_require__(1103), Randomize: __webpack_require__(1104), RemoveTileAt: __webpack_require__(450), RemoveTileAtWorldXY: __webpack_require__(1105), RenderDebug: __webpack_require__(1106), ReplaceByIndex: __webpack_require__(448), SetCollision: __webpack_require__(1107), SetCollisionBetween: __webpack_require__(1108), SetCollisionByExclusion: __webpack_require__(1109), SetCollisionByProperty: __webpack_require__(1110), SetCollisionFromCollisionGroup: __webpack_require__(1111), SetTileIndexCallback: __webpack_require__(1112), SetTileLocationCallback: __webpack_require__(1113), Shuffle: __webpack_require__(1114), SwapByIndex: __webpack_require__(1115), TileToWorldX: __webpack_require__(135), TileToWorldXY: __webpack_require__(1116), TileToWorldY: __webpack_require__(136), WeightedRandomize: __webpack_require__(1117), WorldToTileX: __webpack_require__(59), WorldToTileXY: __webpack_require__(1118), WorldToTileY: __webpack_require__(60) } }, function(module, exports, __webpack_require__) { var IsInLayerBounds = __webpack_require__(104); var GetTileAt = function(tileX, tileY, nonNull, layer) { if (nonNull === undefined) { nonNull = false } if (IsInLayerBounds(tileX, tileY, layer)) { var tile = layer.data[tileY][tileX]; if (tile === null) { return null } else if (tile.index === -1) { return nonNull ? tile : null } else { return tile } } else { return null } }; module.exports = GetTileAt }, function(module, exports) { var TileToWorldX = function(tileX, camera, layer) { var tileWidth = layer.baseTileWidth; var tilemapLayer = layer.tilemapLayer; var layerWorldX = 0; if (tilemapLayer) { if (camera === undefined) { camera = tilemapLayer.scene.cameras.main } layerWorldX = tilemapLayer.x + camera.scrollX * (1 - tilemapLayer.scrollFactorX); tileWidth *= tilemapLayer.scaleX } return layerWorldX + tileX * tileWidth }; module.exports = TileToWorldX }, function(module, exports) { var TileToWorldY = function(tileY, camera, layer) { var tileHeight = layer.baseTileHeight; var tilemapLayer = layer.tilemapLayer; var layerWorldY = 0; if (tilemapLayer) { if (camera === undefined) { camera = tilemapLayer.scene.cameras.main } layerWorldY = tilemapLayer.y + camera.scrollY * (1 - tilemapLayer.scrollFactorY); tileHeight *= tilemapLayer.scaleY } return layerWorldY + tileY * tileHeight }; module.exports = TileToWorldY }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Tileset = new Class({ initialize: function Tileset(name, firstgid, tileWidth, tileHeight, tileMargin, tileSpacing, tileProperties, tileData) { if (tileWidth === undefined || tileWidth <= 0) { tileWidth = 32 } if (tileHeight === undefined || tileHeight <= 0) { tileHeight = 32 } if (tileMargin === undefined) { tileMargin = 0 } if (tileSpacing === undefined) { tileSpacing = 0 } if (tileProperties === undefined) { tileProperties = {} } if (tileData === undefined) { tileData = {} } this.name = name; this.firstgid = firstgid; this.tileWidth = tileWidth; this.tileHeight = tileHeight; this.tileMargin = tileMargin; this.tileSpacing = tileSpacing; this.tileProperties = tileProperties; this.tileData = tileData; this.image = null; this.glTexture = null; this.rows = 0; this.columns = 0; this.total = 0; this.texCoordinates = [] }, getTileProperties: function(tileIndex) { if (!this.containsTileIndex(tileIndex)) { return null } return this.tileProperties[tileIndex - this.firstgid] }, getTileData: function(tileIndex) { if (!this.containsTileIndex(tileIndex)) { return null } return this.tileData[tileIndex - this.firstgid] }, getTileCollisionGroup: function(tileIndex) { var data = this.getTileData(tileIndex); return data && data.objectgroup ? data.objectgroup : null }, containsTileIndex: function(tileIndex) { return tileIndex >= this.firstgid && tileIndex < this.firstgid + this.total }, getTileTextureCoordinates: function(tileIndex) { if (!this.containsTileIndex(tileIndex)) { return null } return this.texCoordinates[tileIndex - this.firstgid] }, setImage: function(texture) { this.image = texture; this.glTexture = texture.get().source.glTexture; this.updateTileData(this.image.source[0].width, this.image.source[0].height); return this }, setTileSize: function(tileWidth, tileHeight) { if (tileWidth !== undefined) { this.tileWidth = tileWidth } if (tileHeight !== undefined) { this.tileHeight = tileHeight } if (this.image) { this.updateTileData(this.image.source[0].width, this.image.source[0].height) } return this }, setSpacing: function(margin, spacing) { if (margin !== undefined) { this.tileMargin = margin } if (spacing !== undefined) { this.tileSpacing = spacing } if (this.image) { this.updateTileData(this.image.source[0].width, this.image.source[0].height) } return this }, updateTileData: function(imageWidth, imageHeight) { var rowCount = (imageHeight - this.tileMargin * 2 + this.tileSpacing) / (this.tileHeight + this.tileSpacing); var colCount = (imageWidth - this.tileMargin * 2 + this.tileSpacing) / (this.tileWidth + this.tileSpacing); if (rowCount % 1 !== 0 || colCount % 1 !== 0) { console.warn("Image tile area not tile size multiple in: " + this.name) } rowCount = Math.floor(rowCount); colCount = Math.floor(colCount); this.rows = rowCount; this.columns = colCount; this.total = rowCount * colCount; this.texCoordinates.length = 0; var tx = this.tileMargin; var ty = this.tileMargin; for (var y = 0; y < this.rows; y++) { for (var x = 0; x < this.columns; x++) { this.texCoordinates.push({ x: tx, y: ty }); tx += this.tileWidth + this.tileSpacing } tx = this.tileMargin; ty += this.tileHeight + this.tileSpacing } return this } }); module.exports = Tileset }, function(module, exports) { var GetNewValue = function(source, key, defaultValue) { var valueCallback; if (source.hasOwnProperty(key)) { var t = typeof source[key]; if (t === "function") { valueCallback = function(index, totalTargets, target) { return source[key](index, totalTargets, target) } } else { valueCallback = function() { return source[key] } } } else if (typeof defaultValue === "function") { valueCallback = defaultValue } else { valueCallback = function() { return defaultValue } } return valueCallback }; module.exports = GetNewValue }, function(module, exports, __webpack_require__) { var Defaults = __webpack_require__(218); var GetAdvancedValue = __webpack_require__(13); var GetBoolean = __webpack_require__(98); var GetEaseFunction = __webpack_require__(97); var GetNewValue = __webpack_require__(138); var GetProps = __webpack_require__(463); var GetTargets = __webpack_require__(216); var GetValue = __webpack_require__(4); var GetValueOp = __webpack_require__(217); var Tween = __webpack_require__(219); var TweenData = __webpack_require__(220); var TweenBuilder = function(parent, config, defaults) { if (defaults === undefined) { defaults = Defaults } var targets = defaults.targets ? defaults.targets : GetTargets(config); var props = GetProps(config); var delay = GetNewValue(config, "delay", defaults.delay); var duration = GetNewValue(config, "duration", defaults.duration); var easeParams = GetValue(config, "easeParams", defaults.easeParams); var ease = GetEaseFunction(GetValue(config, "ease", defaults.ease), easeParams); var hold = GetNewValue(config, "hold", defaults.hold); var repeat = GetNewValue(config, "repeat", defaults.repeat); var repeatDelay = GetNewValue(config, "repeatDelay", defaults.repeatDelay); var yoyo = GetBoolean(config, "yoyo", defaults.yoyo); var flipX = GetBoolean(config, "flipX", defaults.flipX); var flipY = GetBoolean(config, "flipY", defaults.flipY); var data = []; for (var p = 0; p < props.length; p++) { var key = props[p].key; var value = props[p].value; for (var t = 0; t < targets.length; t++) { var ops = GetValueOp(key, value); var tweenData = TweenData(targets[t], key, ops.getEnd, ops.getStart, GetEaseFunction(GetValue(value, "ease", ease), easeParams), GetNewValue(value, "delay", delay), GetNewValue(value, "duration", duration), GetBoolean(value, "yoyo", yoyo), GetNewValue(value, "hold", hold), GetNewValue(value, "repeat", repeat), GetNewValue(value, "repeatDelay", repeatDelay), GetBoolean(value, "flipX", flipX), GetBoolean(value, "flipY", flipY)); data.push(tweenData) } } var tween = new Tween(parent, data, targets); tween.offset = GetAdvancedValue(config, "offset", null); tween.completeDelay = GetAdvancedValue(config, "completeDelay", 0); tween.loop = Math.round(GetAdvancedValue(config, "loop", 0)); tween.loopDelay = Math.round(GetAdvancedValue(config, "loopDelay", 0)); tween.paused = GetBoolean(config, "paused", false); tween.useFrames = GetBoolean(config, "useFrames", false); var scope = GetValue(config, "callbackScope", tween); var tweenArray = [tween, null]; var callbacks = Tween.TYPES; for (var i = 0; i < callbacks.length; i++) { var type = callbacks[i]; var callback = GetValue(config, type, false); if (callback) { var callbackScope = GetValue(config, type + "Scope", scope); var callbackParams = GetValue(config, type + "Params", []); tween.setCallback(type, callback, tweenArray.concat(callbackParams), callbackScope) } } return tween }; module.exports = TweenBuilder }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var GameObject = __webpack_require__(12); var Sprite = __webpack_require__(50); var Vector2 = __webpack_require__(3); var Vector4 = __webpack_require__(125); var Sprite3D = new Class({ Extends: GameObject, initialize: function Sprite3D(scene, x, y, z, texture, frame) { GameObject.call(this, scene, "Sprite3D"); this.gameObject = new Sprite(scene, 0, 0, texture, frame); this.position = new Vector4(x, y, z); this.size = new Vector2(this.gameObject.width, this.gameObject.height); this.scale = new Vector2(1, 1); this.adjustScaleX = true; this.adjustScaleY = true; this._visible = true }, project: function(camera) { var pos = this.position; var gameObject = this.gameObject; camera.project(pos, gameObject); camera.getPointSize(pos, this.size, this.scale); if (this.scale.x <= 0 || this.scale.y <= 0) { gameObject.setVisible(false) } else { if (!gameObject.visible) { gameObject.setVisible(true) } if (this.adjustScaleX) { gameObject.scaleX = this.scale.x } if (this.adjustScaleY) { gameObject.scaleY = this.scale.y } gameObject.setDepth(gameObject.z * -1) } }, setVisible: function(value) { this.visible = value; return this }, visible: { get: function() { return this._visible }, set: function(value) { this._visible = value; this.gameObject.visible = value } }, x: { get: function() { return this.position.x }, set: function(value) { this.position.x = value } }, y: { get: function() { return this.position.y }, set: function(value) { this.position.y = value } }, z: { get: function() { return this.position.z }, set: function(value) { this.position.z = value } } }); module.exports = Sprite3D }, , function(module, exports) { var g; g = function() { return this }(); try { g = g || Function("return this")() || (1, eval)("this") } catch (e) { if (typeof window === "object") g = window } module.exports = g }, function(module, exports) { var ALIGN_CONST = { TOP_LEFT: 0, TOP_CENTER: 1, TOP_RIGHT: 2, LEFT_TOP: 3, LEFT_CENTER: 4, LEFT_BOTTOM: 5, CENTER: 6, RIGHT_TOP: 7, RIGHT_CENTER: 8, RIGHT_BOTTOM: 9, BOTTOM_LEFT: 10, BOTTOM_CENTER: 11, BOTTOM_RIGHT: 12 }; module.exports = ALIGN_CONST }, function(module, exports, __webpack_require__) { var Point = __webpack_require__(6); var CircumferencePoint = function(circle, angle, out) { if (out === undefined) { out = new Point } out.x = circle.x + circle.radius * Math.cos(angle); out.y = circle.y + circle.radius * Math.sin(angle); return out }; module.exports = CircumferencePoint }, function(module, exports, __webpack_require__) { var Point = __webpack_require__(6); var Random = function(circle, out) { if (out === undefined) { out = new Point } var t = 2 * Math.PI * Math.random(); var u = Math.random() + Math.random(); var r = u > 1 ? 2 - u : u; var x = r * Math.cos(t); var y = r * Math.sin(t); out.x = circle.x + x * circle.radius; out.y = circle.y + y * circle.radius; return out }; module.exports = Random }, function(module, exports, __webpack_require__) { var Perimeter = __webpack_require__(108); var Point = __webpack_require__(6); var GetPoint = function(rectangle, position, out) { if (out === undefined) { out = new Point } if (position <= 0 || position >= 1) { out.x = rectangle.x; out.y = rectangle.y; return out } var p = Perimeter(rectangle) * position; if (position > .5) { p -= rectangle.width + rectangle.height; if (p <= rectangle.width) { out.x = rectangle.right - p; out.y = rectangle.bottom } else { out.x = rectangle.x; out.y = rectangle.bottom - (p - rectangle.width) } } else if (p <= rectangle.width) { out.x = rectangle.x + p; out.y = rectangle.y } else { out.x = rectangle.right; out.y = rectangle.y + (p - rectangle.width) } return out }; module.exports = GetPoint }, function(module, exports, __webpack_require__) { var Length = __webpack_require__(62); var Point = __webpack_require__(6); var GetPoints = function(line, quantity, stepRate, out) { if (out === undefined) { out = [] } if (!quantity) { quantity = Length(line) / stepRate } var x1 = line.x1; var y1 = line.y1; var x2 = line.x2; var y2 = line.y2; for (var i = 0; i < quantity; i++) { var position = i / quantity; var x = x1 + (x2 - x1) * position; var y = y1 + (y2 - y1) * position; out.push(new Point(x, y)) } return out }; module.exports = GetPoints }, function(module, exports, __webpack_require__) { var Point = __webpack_require__(6); var Random = function(line, out) { if (out === undefined) { out = new Point } var t = Math.random(); out.x = line.x1 + t * (line.x2 - line.x1); out.y = line.y1 + t * (line.y2 - line.y1); return out }; module.exports = Random }, function(module, exports, __webpack_require__) { var Point = __webpack_require__(6); var Random = function(rect, out) { if (out === undefined) { out = new Point } out.x = rect.x + Math.random() * rect.width; out.y = rect.y + Math.random() * rect.height; return out }; module.exports = Random }, function(module, exports, __webpack_require__) { var MathWrap = __webpack_require__(55); var Wrap = function(angle) { return MathWrap(angle, -Math.PI, Math.PI) }; module.exports = Wrap }, function(module, exports, __webpack_require__) { var Wrap = __webpack_require__(55); var WrapDegrees = function(angle) { return Wrap(angle, -180, 180) }; module.exports = WrapDegrees }, function(module, exports, __webpack_require__) { var Point = __webpack_require__(6); var Random = function(ellipse, out) { if (out === undefined) { out = new Point } var p = Math.random() * Math.PI * 2; var s = Math.sqrt(Math.random()); out.x = ellipse.x + s * Math.cos(p) * ellipse.width / 2; out.y = ellipse.y + s * Math.sin(p) * ellipse.height / 2; return out }; module.exports = Random }, function(module, exports, __webpack_require__) { var Point = __webpack_require__(6); var Random = function(triangle, out) { if (out === undefined) { out = new Point } var ux = triangle.x2 - triangle.x1; var uy = triangle.y2 - triangle.y1; var vx = triangle.x3 - triangle.x1; var vy = triangle.y3 - triangle.y1; var r = Math.random(); var s = Math.random(); if (r + s >= 1) { r = 1 - r; s = 1 - s } out.x = triangle.x1 + (ux * r + vx * s); out.y = triangle.y1 + (uy * r + vy * s); return out }; module.exports = Random }, function(module, exports) { var RotateAroundDistance = function(point, x, y, angle, distance) { var t = angle + Math.atan2(point.y - y, point.x - x); point.x = x + distance * Math.cos(t); point.y = y + distance * Math.sin(t); return point }; module.exports = RotateAroundDistance }, function(module, exports) { var SmootherStep = function(x, min, max) { x = Math.max(0, Math.min(1, (x - min) / (max - min))); return x * x * x * (x * (x * 6 - 15) + 10) }; module.exports = SmootherStep }, function(module, exports) { var SmoothStep = function(x, min, max) { if (x <= min) { return 0 } if (x >= max) { return 1 } x = (x - min) / (max - min); return x * x * (3 - 2 * x) }; module.exports = SmoothStep }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Map = new Class({ initialize: function Map(elements) { this.entries = {}; this.size = 0; if (Array.isArray(elements)) { for (var i = 0; i < elements.length; i++) { this.set(elements[i][0], elements[i][1]) } } }, set: function(key, value) { if (!this.has(key)) { this.entries[key] = value; this.size++ } return this }, get: function(key) { if (this.has(key)) { return this.entries[key] } }, getArray: function() { var output = []; var entries = this.entries; for (var key in entries) { output.push(entries[key]) } return output }, has: function(key) { return this.entries.hasOwnProperty(key) }, delete: function(key) { if (this.has(key)) { delete this.entries[key]; this.size-- } return this }, clear: function() { Object.keys(this.entries).forEach(function(prop) { delete this.entries[prop] }, this); this.size = 0; return this }, keys: function() { return Object.keys(this.entries) }, values: function() { var output = []; var entries = this.entries; for (var key in entries) { output.push(entries[key]) } return output }, dump: function() { var entries = this.entries; console.group("Map"); for (var key in entries) { console.log(key, entries[key]) } console.groupEnd() }, each: function(callback) { var entries = this.entries; for (var key in entries) { if (callback(key, entries[key]) === false) { break } } return this }, contains: function(value) { var entries = this.entries; for (var key in entries) { if (entries[key] === value) { return true } } return false }, merge: function(map, override) { if (override === undefined) { override = false } var local = this.entries; var source = map.entries; for (var key in source) { if (local.hasOwnProperty(key) && override) { local[key] = source[key] } else { this.set(key, source[key]) } } return this } }); module.exports = Map }, function(module, exports) { var Pad = function(str, len, pad, dir) { if (len === undefined) { len = 0 } if (pad === undefined) { pad = " " } if (dir === undefined) { dir = 3 } str = str.toString(); var padlen = 0; if (len + 1 >= str.length) { switch (dir) { case 1: str = new Array(len + 1 - str.length).join(pad) + str; break; case 3: var right = Math.ceil((padlen = len - str.length) / 2); var left = padlen - right; str = new Array(left + 1).join(pad) + str + new Array(right + 1).join(pad); break; default: str = str + new Array(len + 1 - str.length).join(pad); break } } return str }; module.exports = Pad }, function(module, exports, __webpack_require__) { var HexStringToColor = __webpack_require__(266); var IntegerToColor = __webpack_require__(269); var ObjectToColor = __webpack_require__(271); var RGBStringToColor = __webpack_require__(272); var ValueToColor = function(input) { var t = typeof input; switch (t) { case "string": if (input.substr(0, 3).toLowerCase() === "rgb") { return RGBStringToColor(input) } else { return HexStringToColor(input) } case "number": return IntegerToColor(input); case "object": return ObjectToColor(input) } }; module.exports = ValueToColor }, function(module, exports) { var GetColor = function(red, green, blue) { return red << 16 | green << 8 | blue }; module.exports = GetColor }, function(module, exports, __webpack_require__) { var GetColor = __webpack_require__(160); var HSVToRGB = function(h, s, v, out) { if (s === undefined) { s = 1 } if (v === undefined) { v = 1 } var i = Math.floor(h * 6); var f = h * 6 - i; var p = Math.floor(v * (1 - s) * 255); var q = Math.floor(v * (1 - f * s) * 255); var t = Math.floor(v * (1 - (1 - f) * s) * 255); v = Math.floor(v *= 255); var r = v; var g = v; var b = v; var c = i % 6; if (c === 0) { g = t; b = p } else if (c === 1) { r = q; b = p } else if (c === 2) { r = p; b = t } else if (c === 3) { r = p; g = q } else if (c === 4) { r = t; g = p } else if (c === 5) { g = p; b = q } if (!out) { return { r: r, g: g, b: b, color: GetColor(r, g, b) } } else if (out.setTo) { return out.setTo(r, g, b, out.alpha, false) } else { out.r = r; out.g = g; out.b = b; out.color = GetColor(r, g, b); return out } }; module.exports = HSVToRGB }, function(module, exports) { var CenterOn = function(rect, x, y) { rect.x = x - rect.width / 2; rect.y = y - rect.height / 2; return rect }; module.exports = CenterOn }, function(module, exports, __webpack_require__) { var Back = __webpack_require__(274); var Bounce = __webpack_require__(275); var Circular = __webpack_require__(276); var Cubic = __webpack_require__(277); var Elastic = __webpack_require__(278); var Expo = __webpack_require__(279); var Linear = __webpack_require__(280); var Quadratic = __webpack_require__(281); var Quartic = __webpack_require__(282); var Quintic = __webpack_require__(283); var Sine = __webpack_require__(284); var Stepped = __webpack_require__(285); module.exports = { Power0: Linear, Power1: Quadratic.Out, Power2: Cubic.Out, Power3: Quartic.Out, Power4: Quintic.Out, Linear: Linear, Quad: Quadratic.Out, Cubic: Cubic.Out, Quart: Quartic.Out, Quint: Quintic.Out, Sine: Sine.Out, Expo: Expo.Out, Circ: Circular.Out, Elastic: Elastic.Out, Back: Back.Out, Bounce: Bounce.Out, Stepped: Stepped, "Quad.easeIn": Quadratic.In, "Cubic.easeIn": Cubic.In, "Quart.easeIn": Quartic.In, "Quint.easeIn": Quintic.In, "Sine.easeIn": Sine.In, "Expo.easeIn": Expo.In, "Circ.easeIn": Circular.In, "Elastic.easeIn": Elastic.In, "Back.easeIn": Back.In, "Bounce.easeIn": Bounce.In, "Quad.easeOut": Quadratic.Out, "Cubic.easeOut": Cubic.Out, "Quart.easeOut": Quartic.Out, "Quint.easeOut": Quintic.Out, "Sine.easeOut": Sine.Out, "Expo.easeOut": Expo.Out, "Circ.easeOut": Circular.Out, "Elastic.easeOut": Elastic.Out, "Back.easeOut": Back.Out, "Bounce.easeOut": Bounce.Out, "Quad.easeInOut": Quadratic.InOut, "Cubic.easeInOut": Cubic.InOut, "Quart.easeInOut": Quartic.InOut, "Quint.easeInOut": Quintic.InOut, "Sine.easeInOut": Sine.InOut, "Expo.easeInOut": Expo.InOut, "Circ.easeInOut": Circular.InOut, "Elastic.easeInOut": Elastic.InOut, "Back.easeInOut": Back.InOut, "Bounce.easeInOut": Bounce.InOut } }, function(module, exports, __webpack_require__) { var Rectangle = __webpack_require__(9); var FromPoints = function(points, out) { if (out === undefined) { out = new Rectangle } if (points.length === 0) { return out } var minX = Number.MAX_VALUE; var minY = Number.MAX_VALUE; var maxX = Number.MIN_SAFE_INTEGER; var maxY = Number.MIN_SAFE_INTEGER; var p; var px; var py; for (var i = 0; i < points.length; i++) { p = points[i]; if (Array.isArray(p)) { px = p[0]; py = p[1] } else { px = p.x; py = p.y } minX = Math.min(minX, px); minY = Math.min(minY, py); maxX = Math.max(maxX, px); maxY = Math.max(maxY, py) } out.x = minX; out.y = minY; out.width = maxX - minX; out.height = maxY - minY; return out }; module.exports = FromPoints }, function(module, exports, __webpack_require__) { var CONST = __webpack_require__(18); var RadToDeg = function(radians) { return radians * CONST.RAD_TO_DEG }; module.exports = RadToDeg }, function(module, exports) { var CatmullRom = function(t, p0, p1, p2, p3) { var v0 = (p2 - p0) * .5; var v1 = (p3 - p1) * .5; var t2 = t * t; var t3 = t * t2; return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1 }; module.exports = CatmullRom }, function(module, exports) { var Between = function(min, max) { return Math.floor(Math.random() * (max - min + 1) + min) }; module.exports = Between }, function(module, exports) { var RemoveFromDOM = function(element) { if (element.parentNode) { element.parentNode.removeChild(element) } }; module.exports = RemoveFromDOM }, function(module, exports, __webpack_require__) { var OS = __webpack_require__(92); var Browser = __webpack_require__(115); var CanvasPool = __webpack_require__(28); var Features = { canvas: false, canvasBitBltShift: null, file: false, fileSystem: false, getUserMedia: true, littleEndian: false, localStorage: false, pointerLock: false, support32bit: false, vibration: false, webGL: false, worker: false }; function checkIsLittleEndian() { var a = new ArrayBuffer(4); var b = new Uint8Array(a); var c = new Uint32Array(a); b[0] = 161; b[1] = 178; b[2] = 195; b[3] = 212; if (c[0] === 3569595041) { return true } if (c[0] === 2712847316) { return false } else { return null } } function init() { Features.canvas = !!window["CanvasRenderingContext2D"] || OS.cocoonJS; try { Features.localStorage = !!localStorage.getItem } catch (error) { Features.localStorage = false } Features.file = !!window["File"] && !!window["FileReader"] && !!window["FileList"] && !!window["Blob"]; Features.fileSystem = !!window["requestFileSystem"]; var isUint8 = false; var testWebGL = function() { if (window["WebGLRenderingContext"]) { try { var canvas = CanvasPool.createWebGL(this); if (OS.cocoonJS) { canvas.screencanvas = false } var ctx = canvas.getContext("webgl") || canvas.getContext("experimental-webgl"); var canvas2D = CanvasPool.create2D(this); var ctx2D = canvas2D.getContext("2d"); var image = ctx2D.createImageData(1, 1); isUint8 = image.data instanceof Uint8ClampedArray; CanvasPool.remove(canvas); CanvasPool.remove(canvas2D); return !!ctx } catch (e) { return false } } return false }; Features.webGL = testWebGL(); Features.worker = !!window["Worker"]; Features.pointerLock = "pointerLockElement" in document || "mozPointerLockElement" in document || "webkitPointerLockElement" in document; navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.oGetUserMedia; window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL; Features.getUserMedia = Features.getUserMedia && !!navigator.getUserMedia && !!window.URL; if (Browser.firefox && Browser.firefoxVersion < 21) { Features.getUserMedia = false } if (!OS.iOS && (Browser.ie || Browser.firefox || Browser.chrome)) { Features.canvasBitBltShift = true } if (Browser.safari || Browser.mobileSafari) { Features.canvasBitBltShift = false } navigator.vibrate = navigator.vibrate || navigator.webkitVibrate || navigator.mozVibrate || navigator.msVibrate; if (navigator.vibrate) { Features.vibration = true } if (typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined" && typeof Uint32Array !== "undefined") { Features.littleEndian = checkIsLittleEndian() } Features.support32bit = typeof ArrayBuffer !== "undefined" && typeof Uint8ClampedArray !== "undefined" && typeof Int32Array !== "undefined" && Features.littleEndian !== null && isUint8; return Features } module.exports = init() }, function(module, exports) { var DefaultPlugins = { Global: ["game", "anims", "cache", "plugins", "registry", "scale", "sound", "textures"], CoreScene: ["EventEmitter", "CameraManager", "GameObjectCreator", "GameObjectFactory", "ScenePlugin", "DisplayList", "UpdateList"], DefaultScene: ["Clock", "DataManagerPlugin", "InputPlugin", "Loader", "TweenManager", "LightsPlugin"] }; if (typeof PLUGIN_CAMERA3D) { DefaultPlugins.DefaultScene.push("CameraManager3D") } if (typeof PLUGIN_FBINSTANT) { DefaultPlugins.Global.push("facebook") } module.exports = DefaultPlugins }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Utils = __webpack_require__(10); var WebGLPipeline = new Class({ initialize: function WebGLPipeline(config) { this.name = "WebGLPipeline"; this.game = config.game; this.view = config.game.canvas; this.resolution = config.game.config.resolution; this.width = config.game.config.width * this.resolution; this.height = config.game.config.height * this.resolution; this.gl = config.gl; this.vertexCount = 0; this.vertexCapacity = config.vertexCapacity; this.renderer = config.renderer; this.vertexData = config.vertices ? config.vertices : new ArrayBuffer(config.vertexCapacity * config.vertexSize); this.vertexBuffer = this.renderer.createVertexBuffer(config.vertices ? config.vertices : this.vertexData.byteLength, this.gl.STREAM_DRAW); this.program = this.renderer.createProgram(config.vertShader, config.fragShader); this.attributes = config.attributes; this.vertexSize = config.vertexSize; this.topology = config.topology; this.bytes = new Uint8Array(this.vertexData); this.vertexComponentCount = Utils.getComponentCount(config.attributes, this.gl); this.flushLocked = false; this.active = false }, boot: function() {}, addAttribute: function(name, size, type, normalized, offset) { this.attributes.push({ name: name, size: size, type: this.renderer.glFormats[type], normalized: normalized, offset: offset }); return this }, shouldFlush: function() { return this.vertexCount >= this.vertexCapacity }, resize: function(width, height, resolution) { this.width = width * resolution; this.height = height * resolution; return this }, bind: function() { var gl = this.gl; var vertexBuffer = this.vertexBuffer; var attributes = this.attributes; var program = this.program; var renderer = this.renderer; var vertexSize = this.vertexSize; renderer.setProgram(program); renderer.setVertexBuffer(vertexBuffer); for (var index = 0; index < attributes.length; ++index) { var element = attributes[index]; var location = gl.getAttribLocation(program, element.name); if (location >= 0) { gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, element.size, element.type, element.normalized, vertexSize, element.offset) } else { gl.disableVertexAttribArray(location) } } return this }, onBind: function() { return this }, onPreRender: function() { return this }, onRender: function() { return this }, onPostRender: function() { return this }, flush: function() { if (this.flushLocked) { return this } this.flushLocked = true; var gl = this.gl; var vertexCount = this.vertexCount; var topology = this.topology; var vertexSize = this.vertexSize; if (vertexCount === 0) { this.flushLocked = false; return } gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.bytes.subarray(0, vertexCount * vertexSize)); gl.drawArrays(topology, 0, vertexCount); this.vertexCount = 0; this.flushLocked = false; return this }, destroy: function() { var gl = this.gl; gl.deleteProgram(this.program); gl.deleteBuffer(this.vertexBuffer); delete this.program; delete this.vertexBuffer; delete this.gl; return this }, setFloat1: function(name, x) { this.renderer.setFloat1(this.program, name, x); return this }, setFloat2: function(name, x, y) { this.renderer.setFloat2(this.program, name, x, y); return this }, setFloat3: function(name, x, y, z) { this.renderer.setFloat3(this.program, name, x, y, z); return this }, setFloat4: function(name, x, y, z, w) { this.renderer.setFloat4(this.program, name, x, y, z, w); return this }, setFloat1v: function(name, arr) { this.renderer.setFloat1v(this.program, name, arr); return this }, setFloat2v: function(name, arr) { this.renderer.setFloat2v(this.program, name, arr); return this }, setFloat3v: function(name, arr) { this.renderer.setFloat3v(this.program, name, arr); return this }, setFloat4v: function(name, arr) { this.renderer.setFloat4v(this.program, name, arr); return this }, setInt1: function(name, x) { this.renderer.setInt1(this.program, name, x); return this }, setInt2: function(name, x, y) { this.renderer.setInt2(this.program, name, x, y); return this }, setInt3: function(name, x, y, z) { this.renderer.setInt3(this.program, name, x, y, z); return this }, setInt4: function(name, x, y, z, w) { this.renderer.setInt4(this.program, name, x, y, z, w); return this }, setMatrix2: function(name, transpose, matrix) { this.renderer.setMatrix2(this.program, name, transpose, matrix); return this }, setMatrix3: function(name, transpose, matrix) { this.renderer.setMatrix3(this.program, name, transpose, matrix); return this }, setMatrix4: function(name, transpose, matrix) { this.renderer.setMatrix4(this.program, name, transpose, matrix); return this } }); module.exports = WebGLPipeline }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Earcut = __webpack_require__(63); var GetFastValue = __webpack_require__(1); var ModelViewProjection = __webpack_require__(640); var ShaderSourceFS = __webpack_require__(641); var ShaderSourceVS = __webpack_require__(642); var TransformMatrix = __webpack_require__(48); var Utils = __webpack_require__(10); var WebGLPipeline = __webpack_require__(171); var TextureTintPipeline = new Class({ Extends: WebGLPipeline, Mixins: [ModelViewProjection], initialize: function TextureTintPipeline(config) { var rendererConfig = config.renderer.config; WebGLPipeline.call(this, { game: config.game, renderer: config.renderer, gl: config.renderer.gl, topology: GetFastValue(config, "topology", config.renderer.gl.TRIANGLES), vertShader: GetFastValue(config, "vertShader", ShaderSourceVS), fragShader: GetFastValue(config, "fragShader", ShaderSourceFS), vertexCapacity: GetFastValue(config, "vertexCapacity", 6 * rendererConfig.batchSize), vertexSize: GetFastValue(config, "vertexSize", Float32Array.BYTES_PER_ELEMENT * 5 + Uint8Array.BYTES_PER_ELEMENT * 4), attributes: [{ name: "inPosition", size: 2, type: config.renderer.gl.FLOAT, normalized: false, offset: 0 }, { name: "inTexCoord", size: 2, type: config.renderer.gl.FLOAT, normalized: false, offset: Float32Array.BYTES_PER_ELEMENT * 2 }, { name: "inTintEffect", size: 1, type: config.renderer.gl.FLOAT, normalized: false, offset: Float32Array.BYTES_PER_ELEMENT * 4 }, { name: "inTint", size: 4, type: config.renderer.gl.UNSIGNED_BYTE, normalized: true, offset: Float32Array.BYTES_PER_ELEMENT * 5 }] }); this.vertexViewF32 = new Float32Array(this.vertexData); this.vertexViewU32 = new Uint32Array(this.vertexData); this.maxQuads = rendererConfig.batchSize; this.batches = []; this._tempMatrix1 = new TransformMatrix; this._tempMatrix2 = new TransformMatrix; this._tempMatrix3 = new TransformMatrix; this._tempMatrix4 = new TransformMatrix; this.tempTriangle = [{ x: 0, y: 0, width: 0 }, { x: 0, y: 0, width: 0 }, { x: 0, y: 0, width: 0 }, { x: 0, y: 0, width: 0 }]; this.tintEffect = 2; this.strokeTint = { TL: 0, TR: 0, BL: 0, BR: 0 }; this.fillTint = { TL: 0, TR: 0, BL: 0, BR: 0 }; this.currentFrame = { u0: 0, v0: 0, u1: 1, v1: 1 }; this.firstQuad = [0, 0, 0, 0, 0]; this.prevQuad = [0, 0, 0, 0, 0]; this.polygonCache = []; this.mvpInit() }, onBind: function() { WebGLPipeline.prototype.onBind.call(this); this.mvpUpdate(); if (this.batches.length === 0) { this.pushBatch() } return this }, resize: function(width, height, resolution) { WebGLPipeline.prototype.resize.call(this, width, height, resolution); this.projOrtho(0, this.width, this.height, 0, -1e3, 1e3); return this }, setTexture2D: function(texture, unit) { if (!texture) { texture = this.renderer.blankTexture.glTexture; unit = 0 } var batches = this.batches; if (batches.length === 0) { this.pushBatch() } var batch = batches[batches.length - 1]; if (unit > 0) { if (batch.textures[unit - 1] && batch.textures[unit - 1] !== texture) { this.pushBatch() } batches[batches.length - 1].textures[unit - 1] = texture } else { if (batch.texture !== null && batch.texture !== texture) { this.pushBatch() } batches[batches.length - 1].texture = texture } return this }, pushBatch: function() { var batch = { first: this.vertexCount, texture: null, textures: [] }; this.batches.push(batch) }, flush: function() { if (this.flushLocked) { return this } this.flushLocked = true; var gl = this.gl; var vertexCount = this.vertexCount; var topology = this.topology; var vertexSize = this.vertexSize; var renderer = this.renderer; var batches = this.batches; var batchCount = batches.length; var batchVertexCount = 0; var batch = null; var batchNext; var textureIndex; var nTexture; if (batchCount === 0 || vertexCount === 0) { this.flushLocked = false; return this } gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.bytes.subarray(0, vertexCount * vertexSize)); for (var index = 0; index < batches.length - 1; index++) { batch = batches[index]; batchNext = batches[index + 1]; if (batch.textures.length > 0) { for (textureIndex = 0; textureIndex < batch.textures.length; ++textureIndex) { nTexture = batch.textures[textureIndex]; if (nTexture) { renderer.setTexture2D(nTexture, 1 + textureIndex) } } gl.activeTexture(gl.TEXTURE0) } batchVertexCount = batchNext.first - batch.first; if (batch.texture === null || batchVertexCount <= 0) { continue } renderer.setTexture2D(batch.texture, 0); gl.drawArrays(topology, batch.first, batchVertexCount) } batch = batches[batches.length - 1]; if (batch.textures.length > 0) { for (textureIndex = 0; textureIndex < batch.textures.length; ++textureIndex) { nTexture = batch.textures[textureIndex]; if (nTexture) { renderer.setTexture2D(nTexture, 1 + textureIndex) } } gl.activeTexture(gl.TEXTURE0) } batchVertexCount = vertexCount - batch.first; if (batch.texture && batchVertexCount > 0) { renderer.setTexture2D(batch.texture, 0); gl.drawArrays(topology, batch.first, batchVertexCount) } this.vertexCount = 0; batches.length = 0; this.pushBatch(); this.flushLocked = false; return this }, batchSprite: function(sprite, camera, parentTransformMatrix) { this.renderer.setPipeline(this); var camMatrix = this._tempMatrix1; var spriteMatrix = this._tempMatrix2; var calcMatrix = this._tempMatrix3; var frame = sprite.frame; var texture = frame.glTexture; var u0 = frame.u0; var v0 = frame.v0; var u1 = frame.u1; var v1 = frame.v1; var frameX = frame.x; var frameY = frame.y; var frameWidth = frame.cutWidth; var frameHeight = frame.cutHeight; var x = -sprite.displayOriginX + frameX; var y = -sprite.displayOriginY + frameY; if (sprite.isCropped) { var crop = sprite._crop; if (crop.flipX !== sprite.flipX || crop.flipY !== sprite.flipY) { frame.updateCropUVs(crop, sprite.flipX, sprite.flipY) } u0 = crop.u0; v0 = crop.v0; u1 = crop.u1; v1 = crop.v1; frameWidth = crop.width; frameHeight = crop.height; frameX = crop.x; frameY = crop.y; x = -sprite.displayOriginX + frameX; y = -sprite.displayOriginY + frameY } if (sprite.flipX) { x += frameWidth; frameWidth *= -1 } if (sprite.flipY) { y += frameHeight; frameHeight *= -1 } var xw = x + frameWidth; var yh = y + frameHeight; spriteMatrix.applyITRS(sprite.x, sprite.y, sprite.rotation, sprite.scaleX, sprite.scaleY); camMatrix.copyFrom(camera.matrix); if (parentTransformMatrix) { camMatrix.multiplyWithOffset(parentTransformMatrix, -camera.scrollX * sprite.scrollFactorX, -camera.scrollY * sprite.scrollFactorY); spriteMatrix.e = sprite.x; spriteMatrix.f = sprite.y; camMatrix.multiply(spriteMatrix, calcMatrix) } else { spriteMatrix.e -= camera.scrollX * sprite.scrollFactorX; spriteMatrix.f -= camera.scrollY * sprite.scrollFactorY; camMatrix.multiply(spriteMatrix, calcMatrix) } var tx0 = calcMatrix.getX(x, y); var ty0 = calcMatrix.getY(x, y); var tx1 = calcMatrix.getX(x, yh); var ty1 = calcMatrix.getY(x, yh); var tx2 = calcMatrix.getX(xw, yh); var ty2 = calcMatrix.getY(xw, yh); var tx3 = calcMatrix.getX(xw, y); var ty3 = calcMatrix.getY(xw, y); var tintTL = Utils.getTintAppendFloatAlpha(sprite._tintTL, camera.alpha * sprite._alphaTL); var tintTR = Utils.getTintAppendFloatAlpha(sprite._tintTR, camera.alpha * sprite._alphaTR); var tintBL = Utils.getTintAppendFloatAlpha(sprite._tintBL, camera.alpha * sprite._alphaBL); var tintBR = Utils.getTintAppendFloatAlpha(sprite._tintBR, camera.alpha * sprite._alphaBR); if (camera.roundPixels) { tx0 |= 0; ty0 |= 0; tx1 |= 0; ty1 |= 0; tx2 |= 0; ty2 |= 0; tx3 |= 0; ty3 |= 0 } this.setTexture2D(texture, 0); var tintEffect = sprite._isTinted && sprite.tintFill; this.batchQuad(tx0, ty0, tx1, ty1, tx2, ty2, tx3, ty3, u0, v0, u1, v1, tintTL, tintTR, tintBL, tintBR, tintEffect) }, batchQuad: function(x0, y0, x1, y1, x2, y2, x3, y3, u0, v0, u1, v1, tintTL, tintTR, tintBL, tintBR, tintEffect) { var hasFlushed = false; if (this.vertexCount + 6 > this.vertexCapacity) { this.flush(); hasFlushed = true } var vertexViewF32 = this.vertexViewF32; var vertexViewU32 = this.vertexViewU32; var vertexOffset = this.vertexCount * this.vertexComponentCount - 1; vertexViewF32[++vertexOffset] = x0; vertexViewF32[++vertexOffset] = y0; vertexViewF32[++vertexOffset] = u0; vertexViewF32[++vertexOffset] = v0; vertexViewF32[++vertexOffset] = tintEffect; vertexViewU32[++vertexOffset] = tintTL; vertexViewF32[++vertexOffset] = x1; vertexViewF32[++vertexOffset] = y1; vertexViewF32[++vertexOffset] = u0; vertexViewF32[++vertexOffset] = v1; vertexViewF32[++vertexOffset] = tintEffect; vertexViewU32[++vertexOffset] = tintBL; vertexViewF32[++vertexOffset] = x2; vertexViewF32[++vertexOffset] = y2; vertexViewF32[++vertexOffset] = u1; vertexViewF32[++vertexOffset] = v1; vertexViewF32[++vertexOffset] = tintEffect; vertexViewU32[++vertexOffset] = tintBR; vertexViewF32[++vertexOffset] = x0; vertexViewF32[++vertexOffset] = y0; vertexViewF32[++vertexOffset] = u0; vertexViewF32[++vertexOffset] = v0; vertexViewF32[++vertexOffset] = tintEffect; vertexViewU32[++vertexOffset] = tintTL; vertexViewF32[++vertexOffset] = x2; vertexViewF32[++vertexOffset] = y2; vertexViewF32[++vertexOffset] = u1; vertexViewF32[++vertexOffset] = v1; vertexViewF32[++vertexOffset] = tintEffect; vertexViewU32[++vertexOffset] = tintBR; vertexViewF32[++vertexOffset] = x3; vertexViewF32[++vertexOffset] = y3; vertexViewF32[++vertexOffset] = u1; vertexViewF32[++vertexOffset] = v0; vertexViewF32[++vertexOffset] = tintEffect; vertexViewU32[++vertexOffset] = tintTR; this.vertexCount += 6; return hasFlushed }, batchTri: function(x1, y1, x2, y2, x3, y3, u0, v0, u1, v1, tintTL, tintTR, tintBL, tintEffect) { var hasFlushed = false; if (this.vertexCount + 3 > this.vertexCapacity) { this.flush(); hasFlushed = true } var vertexViewF32 = this.vertexViewF32; var vertexViewU32 = this.vertexViewU32; var vertexOffset = this.vertexCount * this.vertexComponentCount - 1; vertexViewF32[++vertexOffset] = x1; vertexViewF32[++vertexOffset] = y1; vertexViewF32[++vertexOffset] = u0; vertexViewF32[++vertexOffset] = v0; vertexViewF32[++vertexOffset] = tintEffect; vertexViewU32[++vertexOffset] = tintTL; vertexViewF32[++vertexOffset] = x2; vertexViewF32[++vertexOffset] = y2; vertexViewF32[++vertexOffset] = u0; vertexViewF32[++vertexOffset] = v1; vertexViewF32[++vertexOffset] = tintEffect; vertexViewU32[++vertexOffset] = tintTR; vertexViewF32[++vertexOffset] = x3; vertexViewF32[++vertexOffset] = y3; vertexViewF32[++vertexOffset] = u1; vertexViewF32[++vertexOffset] = v1; vertexViewF32[++vertexOffset] = tintEffect; vertexViewU32[++vertexOffset] = tintBL; this.vertexCount += 3; return hasFlushed }, batchTexture: function(gameObject, texture, textureWidth, textureHeight, srcX, srcY, srcWidth, srcHeight, scaleX, scaleY, rotation, flipX, flipY, scrollFactorX, scrollFactorY, displayOriginX, displayOriginY, frameX, frameY, frameWidth, frameHeight, tintTL, tintTR, tintBL, tintBR, tintEffect, uOffset, vOffset, camera, parentTransformMatrix, skipFlip) { this.renderer.setPipeline(this, gameObject); var camMatrix = this._tempMatrix1; var spriteMatrix = this._tempMatrix2; var calcMatrix = this._tempMatrix3; var u0 = frameX / textureWidth + uOffset; var v0 = frameY / textureHeight + vOffset; var u1 = (frameX + frameWidth) / textureWidth + uOffset; var v1 = (frameY + frameHeight) / textureHeight + vOffset; var width = srcWidth; var height = srcHeight; var x = -displayOriginX; var y = -displayOriginY; if (gameObject.isCropped) { var crop = gameObject._crop; width = crop.width; height = crop.height; srcWidth = crop.width; srcHeight = crop.height; frameX = crop.x; frameY = crop.y; var ox = frameX; var oy = frameY; if (flipX) { ox = frameWidth - crop.x - crop.width } if (flipY && !texture.isRenderTexture) { oy = frameHeight - crop.y - crop.height } u0 = ox / textureWidth + uOffset; v0 = oy / textureHeight + vOffset; u1 = (ox + crop.width) / textureWidth + uOffset; v1 = (oy + crop.height) / textureHeight + vOffset; x = -displayOriginX + frameX; y = -displayOriginY + frameY } flipY = flipY ^ (!skipFlip && texture.isRenderTexture ? 1 : 0); if (flipX) { width *= -1; x += srcWidth } if (flipY) { height *= -1; y += srcHeight } var xw = x + width; var yh = y + height; spriteMatrix.applyITRS(srcX, srcY, rotation, scaleX, scaleY); camMatrix.copyFrom(camera.matrix); if (parentTransformMatrix) { camMatrix.multiplyWithOffset(parentTransformMatrix, -camera.scrollX * scrollFactorX, -camera.scrollY * scrollFactorY); spriteMatrix.e = srcX; spriteMatrix.f = srcY; camMatrix.multiply(spriteMatrix, calcMatrix) } else { spriteMatrix.e -= camera.scrollX * scrollFactorX; spriteMatrix.f -= camera.scrollY * scrollFactorY; camMatrix.multiply(spriteMatrix, calcMatrix) } var tx0 = calcMatrix.getX(x, y); var ty0 = calcMatrix.getY(x, y); var tx1 = calcMatrix.getX(x, yh); var ty1 = calcMatrix.getY(x, yh); var tx2 = calcMatrix.getX(xw, yh); var ty2 = calcMatrix.getY(xw, yh); var tx3 = calcMatrix.getX(xw, y); var ty3 = calcMatrix.getY(xw, y); if (camera.roundPixels) { tx0 |= 0; ty0 |= 0; tx1 |= 0; ty1 |= 0; tx2 |= 0; ty2 |= 0; tx3 |= 0; ty3 |= 0 } this.setTexture2D(texture, 0); this.batchQuad(tx0, ty0, tx1, ty1, tx2, ty2, tx3, ty3, u0, v0, u1, v1, tintTL, tintTR, tintBL, tintBR, tintEffect) }, batchTextureFrame: function(frame, x, y, tint, alpha, transformMatrix, parentTransformMatrix) { this.renderer.setPipeline(this); var spriteMatrix = this._tempMatrix1.copyFrom(transformMatrix); var calcMatrix = this._tempMatrix2; var xw = x + frame.width; var yh = y + frame.height; if (parentTransformMatrix) { spriteMatrix.multiply(parentTransformMatrix, calcMatrix) } else { calcMatrix = spriteMatrix } var tx0 = calcMatrix.getX(x, y); var ty0 = calcMatrix.getY(x, y); var tx1 = calcMatrix.getX(x, yh); var ty1 = calcMatrix.getY(x, yh); var tx2 = calcMatrix.getX(xw, yh); var ty2 = calcMatrix.getY(xw, yh); var tx3 = calcMatrix.getX(xw, y); var ty3 = calcMatrix.getY(xw, y); this.setTexture2D(frame.glTexture, 0); tint = Utils.getTintAppendFloatAlpha(tint, alpha); this.batchQuad(tx0, ty0, tx1, ty1, tx2, ty2, tx3, ty3, frame.u0, frame.v0, frame.u1, frame.v1, tint, tint, tint, tint, 0) }, drawFillRect: function(x, y, width, height, color, alpha) { var xw = x + width; var yh = y + height; var tint = Utils.getTintAppendFloatAlphaAndSwap(color, alpha); this.batchQuad(x, y, x, yh, xw, yh, xw, y, 0, 0, 1, 1, tint, tint, tint, tint, 2) }, batchFillRect: function(x, y, width, height, currentMatrix, parentMatrix) { this.renderer.setPipeline(this); var calcMatrix = this._tempMatrix3; if (parentMatrix) { parentMatrix.multiply(currentMatrix, calcMatrix) } var xw = x + width; var yh = y + height; var x0 = calcMatrix.getX(x, y); var y0 = calcMatrix.getY(x, y); var x1 = calcMatrix.getX(x, yh); var y1 = calcMatrix.getY(x, yh); var x2 = calcMatrix.getX(xw, yh); var y2 = calcMatrix.getY(xw, yh); var x3 = calcMatrix.getX(xw, y); var y3 = calcMatrix.getY(xw, y); var frame = this.currentFrame; var u0 = frame.u0; var v0 = frame.v0; var u1 = frame.u1; var v1 = frame.v1; this.batchQuad(x0, y0, x1, y1, x2, y2, x3, y3, u0, v0, u1, v1, this.fillTint.TL, this.fillTint.TR, this.fillTint.BL, this.fillTint.BR, this.tintEffect) }, batchFillTriangle: function(x0, y0, x1, y1, x2, y2, currentMatrix, parentMatrix) { this.renderer.setPipeline(this); var calcMatrix = this._tempMatrix3; if (parentMatrix) { parentMatrix.multiply(currentMatrix, calcMatrix) } var tx0 = calcMatrix.getX(x0, y0); var ty0 = calcMatrix.getY(x0, y0); var tx1 = calcMatrix.getX(x1, y1); var ty1 = calcMatrix.getY(x1, y1); var tx2 = calcMatrix.getX(x2, y2); var ty2 = calcMatrix.getY(x2, y2); var frame = this.currentFrame; var u0 = frame.u0; var v0 = frame.v0; var u1 = frame.u1; var v1 = frame.v1; this.batchTri(tx0, ty0, tx1, ty1, tx2, ty2, u0, v0, u1, v1, this.fillTint.TL, this.fillTint.TR, this.fillTint.BL, this.tintEffect) }, batchStrokeTriangle: function(x0, y0, x1, y1, x2, y2, lineWidth, currentMatrix, parentMatrix) { var tempTriangle = this.tempTriangle; tempTriangle[0].x = x0; tempTriangle[0].y = y0; tempTriangle[0].width = lineWidth; tempTriangle[1].x = x1; tempTriangle[1].y = y1; tempTriangle[1].width = lineWidth; tempTriangle[2].x = x2; tempTriangle[2].y = y2; tempTriangle[2].width = lineWidth; tempTriangle[3].x = x0; tempTriangle[3].y = y0; tempTriangle[3].width = lineWidth; this.batchStrokePath(tempTriangle, lineWidth, false, currentMatrix, parentMatrix) }, batchFillPath: function(path, currentMatrix, parentMatrix) { this.renderer.setPipeline(this); var calcMatrix = this._tempMatrix3; if (parentMatrix) { parentMatrix.multiply(currentMatrix, calcMatrix) } var length = path.length; var polygonCache = this.polygonCache; var polygonIndexArray; var point; var tintTL = this.fillTint.TL; var tintTR = this.fillTint.TR; var tintBL = this.fillTint.BL; var tintEffect = this.tintEffect; for (var pathIndex = 0; pathIndex < length; ++pathIndex) { point = path[pathIndex]; polygonCache.push(point.x, point.y) } polygonIndexArray = Earcut(polygonCache); length = polygonIndexArray.length; var frame = this.currentFrame; for (var index = 0; index < length; index += 3) { var p0 = polygonIndexArray[index + 0] * 2; var p1 = polygonIndexArray[index + 1] * 2; var p2 = polygonIndexArray[index + 2] * 2; var x0 = polygonCache[p0 + 0]; var y0 = polygonCache[p0 + 1]; var x1 = polygonCache[p1 + 0]; var y1 = polygonCache[p1 + 1]; var x2 = polygonCache[p2 + 0]; var y2 = polygonCache[p2 + 1]; var tx0 = calcMatrix.getX(x0, y0); var ty0 = calcMatrix.getY(x0, y0); var tx1 = calcMatrix.getX(x1, y1); var ty1 = calcMatrix.getY(x1, y1); var tx2 = calcMatrix.getX(x2, y2); var ty2 = calcMatrix.getY(x2, y2); var u0 = frame.u0; var v0 = frame.v0; var u1 = frame.u1; var v1 = frame.v1; this.batchTri(tx0, ty0, tx1, ty1, tx2, ty2, u0, v0, u1, v1, tintTL, tintTR, tintBL, tintEffect) } polygonCache.length = 0 }, batchStrokePath: function(path, lineWidth, pathOpen, currentMatrix, parentMatrix) { this.renderer.setPipeline(this); this.prevQuad[4] = 0; this.firstQuad[4] = 0; var pathLength = path.length - 1; for (var pathIndex = 0; pathIndex < pathLength; pathIndex++) { var point0 = path[pathIndex]; var point1 = path[pathIndex + 1]; this.batchLine(point0.x, point0.y, point1.x, point1.y, point0.width / 2, point1.width / 2, lineWidth, pathIndex, !pathOpen && pathIndex === pathLength - 1, currentMatrix, parentMatrix) } }, batchLine: function(ax, ay, bx, by, aLineWidth, bLineWidth, lineWidth, index, closePath, currentMatrix, parentMatrix) { this.renderer.setPipeline(this); var calcMatrix = this._tempMatrix3; if (parentMatrix) { parentMatrix.multiply(currentMatrix, calcMatrix) } var dx = bx - ax; var dy = by - ay; var len = Math.sqrt(dx * dx + dy * dy); var al0 = aLineWidth * (by - ay) / len; var al1 = aLineWidth * (ax - bx) / len; var bl0 = bLineWidth * (by - ay) / len; var bl1 = bLineWidth * (ax - bx) / len; var lx0 = bx - bl0; var ly0 = by - bl1; var lx1 = ax - al0; var ly1 = ay - al1; var lx2 = bx + bl0; var ly2 = by + bl1; var lx3 = ax + al0; var ly3 = ay + al1; var brX = calcMatrix.getX(lx0, ly0); var brY = calcMatrix.getY(lx0, ly0); var blX = calcMatrix.getX(lx1, ly1); var blY = calcMatrix.getY(lx1, ly1); var trX = calcMatrix.getX(lx2, ly2); var trY = calcMatrix.getY(lx2, ly2); var tlX = calcMatrix.getX(lx3, ly3); var tlY = calcMatrix.getY(lx3, ly3); var tint = this.strokeTint; var tintEffect = this.tintEffect; var tintTL = tint.TL; var tintTR = tint.TR; var tintBL = tint.BL; var tintBR = tint.BR; var frame = this.currentFrame; var u0 = frame.u0; var v0 = frame.v0; var u1 = frame.u1; var v1 = frame.v1; this.batchQuad(tlX, tlY, blX, blY, brX, brY, trX, trY, u0, v0, u1, v1, tintTL, tintTR, tintBL, tintBR, tintEffect); if (lineWidth <= 2) { return } var prev = this.prevQuad; var first = this.firstQuad; if (index > 0 && prev[4]) { this.batchQuad(tlX, tlY, blX, blY, prev[0], prev[1], prev[2], prev[3], u0, v0, u1, v1, tintTL, tintTR, tintBL, tintBR, tintEffect) } else { first[0] = tlX; first[1] = tlY; first[2] = blX; first[3] = blY; first[4] = 1 } if (closePath && first[4]) { this.batchQuad(brX, brY, trX, trY, first[0], first[1], first[2], first[3], u0, v0, u1, v1, tintTL, tintTR, tintBL, tintBR, tintEffect) } else { prev[0] = brX; prev[1] = brY; prev[2] = trX; prev[3] = trY; prev[4] = 1 } } }); module.exports = TextureTintPipeline }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var CONST = __webpack_require__(117); var DefaultPlugins = __webpack_require__(170); var GetPhysicsPlugins = __webpack_require__(644); var GetScenePlugins = __webpack_require__(645); var NOOP = __webpack_require__(2); var Settings = __webpack_require__(323); var Systems = new Class({ initialize: function Systems(scene, config) { this.scene = scene; this.game; if (typeof PLUGIN_FBINSTANT) { this.facebook } this.config = config; this.settings = Settings.create(config); this.canvas; this.context; this.anims; this.cache; this.plugins; this.registry; this.sound; this.textures; this.add; this.cameras; this.displayList; this.events; this.make; this.scenePlugin; this.updateList; this.sceneUpdate = NOOP }, init: function(game) { this.settings.status = CONST.INIT; this.sceneUpdate = NOOP; this.game = game; this.canvas = game.canvas; this.context = game.context; var pluginManager = game.plugins; this.plugins = pluginManager; pluginManager.addToScene(this, DefaultPlugins.Global, [DefaultPlugins.CoreScene, GetScenePlugins(this), GetPhysicsPlugins(this)]); this.events.emit("boot", this); this.settings.isBooted = true }, install: function(plugin) { if (!Array.isArray(plugin)) { plugin = [plugin] } this.plugins.installLocal(this, plugin) }, step: function(time, delta) { this.events.emit("preupdate", time, delta); this.events.emit("update", time, delta); this.sceneUpdate.call(this.scene, time, delta); this.events.emit("postupdate", time, delta) }, render: function(renderer) { var displayList = this.displayList; displayList.depthSort(); this.cameras.render(renderer, displayList); this.events.emit("render", renderer) }, queueDepthSort: function() { this.displayList.queueDepthSort() }, depthSort: function() { this.displayList.depthSort() }, pause: function(data) { if (this.settings.active) { this.settings.status = CONST.PAUSED; this.settings.active = false; this.events.emit("pause", this, data) } return this }, resume: function(data) { if (!this.settings.active) { this.settings.status = CONST.RUNNING; this.settings.active = true; this.events.emit("resume", this, data) } return this }, sleep: function(data) { this.settings.status = CONST.SLEEPING; this.settings.active = false; this.settings.visible = false; this.events.emit("sleep", this, data); return this }, wake: function(data) { var settings = this.settings; settings.status = CONST.RUNNING; settings.active = true; settings.visible = true; this.events.emit("wake", this, data); if (settings.isTransition) { this.events.emit("transitionwake", settings.transitionFrom, settings.transitionDuration) } return this }, isSleeping: function() { return this.settings.status === CONST.SLEEPING }, isActive: function() { return this.settings.status === CONST.RUNNING }, isPaused: function() { return this.settings.status === CONST.PAUSED }, isTransitioning: function() { return this.settings.isTransition || this.scenePlugin._target !== null }, isTransitionOut: function() { return this.scenePlugin._target !== null && this.scenePlugin._duration > 0 }, isTransitionIn: function() { return this.settings.isTransition }, isVisible: function() { return this.settings.visible }, setVisible: function(value) { this.settings.visible = value; return this }, setActive: function(value, data) { if (value) { return this.resume(data) } else { return this.pause(data) } }, start: function(data) { if (data) { this.settings.data = data } this.settings.status = CONST.START; this.settings.active = true; this.settings.visible = true; this.events.emit("start", this); this.events.emit("ready", this, data) }, resize: function(width, height) { this.events.emit("resize", width, height) }, shutdown: function(data) { this.events.off("transitioninit"); this.events.off("transitionstart"); this.events.off("transitioncomplete"); this.events.off("transitionout"); this.settings.status = CONST.SHUTDOWN; this.settings.active = false; this.settings.visible = false; this.events.emit("shutdown", this, data) }, destroy: function() { this.settings.status = CONST.DESTROYED; this.settings.active = false; this.settings.visible = false; this.events.emit("destroy", this); this.events.removeAllListeners(); var props = ["scene", "game", "anims", "cache", "plugins", "registry", "sound", "textures", "add", "camera", "displayList", "events", "make", "scenePlugin", "updateList"]; for (var i = 0; i < props.length; i++) { this[props[i]] = null } } }); module.exports = Systems }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Frame = __webpack_require__(120); var TextureSource = __webpack_require__(332); var TEXTURE_MISSING_ERROR = "Texture.frame missing: "; var Texture = new Class({ initialize: function Texture(manager, key, source, width, height) { if (!Array.isArray(source)) { source = [source] } this.manager = manager; this.key = key; this.source = []; this.dataSource = []; this.frames = {}; this.customData = {}; this.firstFrame = "__BASE"; this.frameTotal = 0; for (var i = 0; i < source.length; i++) { this.source.push(new TextureSource(this, source[i], width, height)) } }, add: function(name, sourceIndex, x, y, width, height) { var frame = new Frame(this, name, sourceIndex, x, y, width, height); this.frames[name] = frame; if (this.frameTotal === 1) { this.firstFrame = name } this.frameTotal++; return frame }, has: function(name) { return this.frames[name] }, get: function(name) { if (!name) { name = this.firstFrame } var frame = this.frames[name]; if (!frame) { console.warn(TEXTURE_MISSING_ERROR + name); frame = this.frames[this.firstFrame] } return frame }, getTextureSourceIndex: function(source) { for (var i = 0; i < this.source.length; i++) { if (this.source[i] === source) { return i } } return -1 }, getFramesFromTextureSource: function(sourceIndex, includeBase) { if (includeBase === undefined) { includeBase = false } var out = []; for (var frameName in this.frames) { if (frameName === "__BASE" && !includeBase) { continue } var frame = this.frames[frameName]; if (frame.sourceIndex === sourceIndex) { out.push(frame) } } return out }, getFrameNames: function(includeBase) { if (includeBase === undefined) { includeBase = false } var out = Object.keys(this.frames); if (!includeBase) { var idx = out.indexOf("__BASE"); if (idx !== -1) { out.splice(idx, 1) } } return out }, getSourceImage: function(name) { if (name === undefined || name === null || this.frameTotal === 1) { name = "__BASE" } var frame = this.frames[name]; if (frame) { return frame.source.image } else { console.warn(TEXTURE_MISSING_ERROR + name); return this.frames["__BASE"].source.image } }, getDataSourceImage: function(name) { if (name === undefined || name === null || this.frameTotal === 1) { name = "__BASE" } var frame = this.frames[name]; var idx; if (!frame) { console.warn(TEXTURE_MISSING_ERROR + name); idx = this.frames["__BASE"].sourceIndex } else { idx = frame.sourceIndex } return this.dataSource[idx].image }, setDataSource: function(data) { if (!Array.isArray(data)) { data = [data] } for (var i = 0; i < data.length; i++) { var source = this.source[i]; this.dataSource.push(new TextureSource(this, data[i], source.width, source.height)) } }, setFilter: function(filterMode) { var i; for (i = 0; i < this.source.length; i++) { this.source[i].setFilter(filterMode) } for (i = 0; i < this.dataSource.length; i++) { this.dataSource[i].setFilter(filterMode) } }, destroy: function() { var i; for (i = 0; i < this.source.length; i++) { this.source[i].destroy() } for (i = 0; i < this.dataSource.length; i++) { this.dataSource[i].destroy() } for (var frameName in this.frames) { var frame = this.frames[frameName]; frame.destroy() } this.source = []; this.dataSource = []; this.frames = {}; this.manager = null } }); module.exports = Texture }, function(module, exports, __webpack_require__) { module.exports = { Matrix: __webpack_require__(666), Add: __webpack_require__(673), AddAt: __webpack_require__(674), BringToTop: __webpack_require__(675), CountAllMatching: __webpack_require__(676), Each: __webpack_require__(677), EachInRange: __webpack_require__(678), FindClosestInSorted: __webpack_require__(260), GetAll: __webpack_require__(679), GetFirst: __webpack_require__(680), GetRandom: __webpack_require__(177), MoveDown: __webpack_require__(681), MoveTo: __webpack_require__(682), MoveUp: __webpack_require__(683), NumberArray: __webpack_require__(684), NumberArrayStep: __webpack_require__(685), QuickSelect: __webpack_require__(337), Range: __webpack_require__(338), Remove: __webpack_require__(319), RemoveAt: __webpack_require__(686), RemoveBetween: __webpack_require__(687), RemoveRandomElement: __webpack_require__(688), Replace: __webpack_require__(689), RotateLeft: __webpack_require__(256), RotateRight: __webpack_require__(257), SafeRange: __webpack_require__(65), SendToBack: __webpack_require__(690), SetAll: __webpack_require__(691), Shuffle: __webpack_require__(110), SpliceOne: __webpack_require__(93), StableSort: __webpack_require__(123), Swap: __webpack_require__(692) } }, function(module, exports) { var CheckMatrix = function(matrix) { if (!Array.isArray(matrix) || matrix.length < 2 || !Array.isArray(matrix[0])) { return false } var size = matrix[0].length; for (var i = 1; i < matrix.length; i++) { if (matrix[i].length !== size) { return false } } return true }; module.exports = CheckMatrix }, function(module, exports) { var GetRandom = function(array, startIndex, length) { if (startIndex === undefined) { startIndex = 0 } if (length === undefined) { length = array.length } var randomIndex = startIndex + Math.floor(Math.random() * length); return array[randomIndex] === undefined ? null : array[randomIndex] }; module.exports = GetRandom }, function(module, exports, __webpack_require__) { var GetAdvancedValue = __webpack_require__(13); var BuildGameObjectAnimation = function(sprite, config) { var animConfig = GetAdvancedValue(config, "anims", null); if (animConfig === null) { return sprite } if (typeof animConfig === "string") { sprite.anims.play(animConfig) } else if (typeof animConfig === "object") { var anims = sprite.anims; var key = GetAdvancedValue(animConfig, "key", undefined); var startFrame = GetAdvancedValue(animConfig, "startFrame", undefined); var delay = GetAdvancedValue(animConfig, "delay", 0); var repeat = GetAdvancedValue(animConfig, "repeat", 0); var repeatDelay = GetAdvancedValue(animConfig, "repeatDelay", 0); var yoyo = GetAdvancedValue(animConfig, "yoyo", false); var play = GetAdvancedValue(animConfig, "play", false); var delayedPlay = GetAdvancedValue(animConfig, "delayedPlay", 0); anims.setDelay(delay); anims.setRepeat(repeat); anims.setRepeatDelay(repeatDelay); anims.setYoyo(yoyo); if (play) { anims.play(key, startFrame) } else if (delayedPlay > 0) { anims.delayedPlay(delayedPlay, key, startFrame) } else { anims.load(key) } } return sprite }; module.exports = BuildGameObjectAnimation }, function(module, exports, __webpack_require__) { var BlitterRender = __webpack_require__(699); var Bob = __webpack_require__(702); var Class = __webpack_require__(0); var Components = __webpack_require__(14); var Frame = __webpack_require__(120); var GameObject = __webpack_require__(12); var List = __webpack_require__(121); var Blitter = new Class({ Extends: GameObject, Mixins: [Components.Alpha, Components.BlendMode, Components.Depth, Components.Mask, Components.Pipeline, Components.ScaleMode, Components.ScrollFactor, Components.Size, Components.Texture, Components.Transform, Components.Visible, BlitterRender], initialize: function Blitter(scene, x, y, texture, frame) { GameObject.call(this, scene, "Blitter"); this.setTexture(texture, frame); this.setPosition(x, y); this.initPipeline(); this.children = new List; this.renderList = []; this.dirty = false }, create: function(x, y, frame, visible, index) { if (visible === undefined) { visible = true } if (index === undefined) { index = this.children.length } if (frame === undefined) { frame = this.frame } else if (!(frame instanceof Frame)) { frame = this.texture.get(frame) } var bob = new Bob(this, x, y, frame, visible); this.children.addAt(bob, index, false); this.dirty = true; return bob }, createFromCallback: function(callback, quantity, frame, visible) { var bobs = this.createMultiple(quantity, frame, visible); for (var i = 0; i < bobs.length; i++) { var bob = bobs[i]; callback.call(this, bob, i) } return bobs }, createMultiple: function(quantity, frame, visible) { if (frame === undefined) { frame = this.frame.name } if (visible === undefined) { visible = true } if (!Array.isArray(frame)) { frame = [frame] } var bobs = []; var _this = this; frame.forEach(function(singleFrame) { for (var i = 0; i < quantity; i++) { bobs.push(_this.create(0, 0, singleFrame, visible)) } }); return bobs }, childCanRender: function(child) { return child.visible && child.alpha > 0 }, getRenderList: function() { if (this.dirty) { this.renderList = this.children.list.filter(this.childCanRender, this); this.dirty = false } return this.renderList }, clear: function() { this.children.removeAll(); this.dirty = true }, preDestroy: function() { this.children.destroy(); this.renderList = [] } }); module.exports = Blitter }, function(module, exports, __webpack_require__) { var ArrayUtils = __webpack_require__(175); var BlendModes = __webpack_require__(61); var Class = __webpack_require__(0); var Components = __webpack_require__(14); var GameObject = __webpack_require__(12); var Rectangle = __webpack_require__(9); var Render = __webpack_require__(703); var Union = __webpack_require__(340); var Vector2 = __webpack_require__(3); var Container = new Class({ Extends: GameObject, Mixins: [Components.Alpha, Components.BlendMode, Components.ComputedSize, Components.Depth, Components.Mask, Components.ScrollFactor, Components.Transform, Components.Visible, Render], initialize: function Container(scene, x, y, children) { GameObject.call(this, scene, "Container"); this.list = []; this.exclusive = true; this.maxSize = -1; this.position = 0; this.localTransform = new Components.TransformMatrix; this.tempTransformMatrix = new Components.TransformMatrix; this._displayList = scene.sys.displayList; this._sortKey = ""; this._sysEvents = scene.sys.events; this.setPosition(x, y); this.clearAlpha(); this.setBlendMode(BlendModes.SKIP_CHECK); if (children) { this.add(children) } }, originX: { get: function() { return .5 } }, originY: { get: function() { return .5 } }, displayOriginX: { get: function() { return this.width * .5 } }, displayOriginY: { get: function() { return this.height * .5 } }, setExclusive: function(value) { if (value === undefined) { value = true } this.exclusive = value; return this }, getBounds: function(output) { if (output === undefined) { output = new Rectangle } output.setTo(this.x, this.y, 0, 0); if (this.list.length > 0) { var children = this.list; var tempRect = new Rectangle; for (var i = 0; i < children.length; i++) { var entry = children[i]; if (entry.getBounds) { entry.getBounds(tempRect); Union(tempRect, output, output) } } } return output }, addHandler: function(gameObject) { gameObject.once("destroy", this.remove, this); if (this.exclusive) { this._displayList.remove(gameObject); if (gameObject.parentContainer) { gameObject.parentContainer.remove(gameObject) } gameObject.parentContainer = this } }, removeHandler: function(gameObject) { gameObject.off("destroy", this.remove); if (this.exclusive) { gameObject.parentContainer = null } }, pointToContainer: function(source, output) { if (output === undefined) { output = new Vector2 } if (this.parentContainer) { return this.parentContainer.pointToContainer(source, output) } var tempMatrix = this.tempTransformMatrix; tempMatrix.applyITRS(this.x, this.y, this.rotation, this.scaleX, this.scaleY); tempMatrix.invert(); tempMatrix.transformPoint(source.x, source.y, output); return output }, getBoundsTransformMatrix: function() { return this.getWorldTransformMatrix(this.tempTransformMatrix, this.localTransform) }, add: function(child) { ArrayUtils.Add(this.list, child, this.maxSize, this.addHandler, this); return this }, addAt: function(child, index) { ArrayUtils.AddAt(this.list, child, index, this.maxSize, this.addHandler, this); return this }, getAt: function(index) { return this.list[index] }, getIndex: function(child) { return this.list.indexOf(child) }, sort: function(property) { if (property) { this._sortKey = property; ArrayUtils.StableSort.inplace(this.list, this.sortHandler) } return this }, sortHandler: function(childA, childB) { return childA[this._sortKey] - childB[this._sortKey] }, getByName: function(name) { return ArrayUtils.GetFirst(this.list, "name", name) }, getRandom: function(startIndex, length) { return ArrayUtils.GetRandom(this.list, startIndex, length) }, getFirst: function(property, value, startIndex, endIndex) { return ArrayUtils.GetFirstElement(this.list, property, value, startIndex, endIndex) }, getAll: function(property, value, startIndex, endIndex) { return ArrayUtils.GetAll(this.list, property, value, startIndex, endIndex) }, count: function(property, value, startIndex, endIndex) { return ArrayUtils.CountAllMatching(this.list, property, value, startIndex, endIndex) }, swap: function(child1, child2) { ArrayUtils.Swap(this.list, child1, child2); return this }, moveTo: function(child, index) { ArrayUtils.MoveTo(this.list, child, index); return this }, remove: function(child, destroyChild) { var removed = ArrayUtils.Remove(this.list, child, this.removeHandler, this); if (destroyChild && removed) { if (!Array.isArray(removed)) { removed = [removed] } for (var i = 0; i < removed.length; i++) { removed[i].destroy() } } return this }, removeAt: function(index, destroyChild) { var removed = ArrayUtils.RemoveAt(this.list, index, this.removeHandler, this); if (destroyChild && removed) { removed.destroy() } return this }, removeBetween: function(startIndex, endIndex, destroyChild) { var removed = ArrayUtils.RemoveBetween(this.list, startIndex, endIndex, this.removeHandler, this); if (destroyChild) { for (var i = 0; i < removed.length; i++) { removed[i].destroy() } } return this }, removeAll: function(destroyChild) { var removed = ArrayUtils.RemoveBetween(this.list, 0, this.list.length, this.removeHandler, this); if (destroyChild) { for (var i = 0; i < removed.length; i++) { removed[i].destroy() } } return this }, bringToTop: function(child) { ArrayUtils.BringToTop(this.list, child); return this }, sendToBack: function(child) { ArrayUtils.SendToBack(this.list, child); return this }, moveUp: function(child) { ArrayUtils.MoveUp(this.list, child); return this }, moveDown: function(child) { ArrayUtils.MoveDown(this.list, child); return this }, reverse: function() { this.list.reverse(); return this }, shuffle: function() { ArrayUtils.Shuffle(this.list); return this }, replace: function(oldChild, newChild, destroyChild) { var moved = ArrayUtils.Replace(this.list, oldChild, newChild); if (moved) { this.addHandler(newChild); this.removeHandler(oldChild); if (destroyChild) { oldChild.destroy() } } return this }, exists: function(child) { return this.list.indexOf(child) > -1 }, setAll: function(property, value, startIndex, endIndex) { ArrayUtils.SetAll(this.list, property, value, startIndex, endIndex); return this }, each: function(callback, context) { var args = [null]; var i; var temp = this.list.slice(); var len = temp.length; for (i = 2; i < arguments.length; i++) { args.push(arguments[i]) } for (i = 0; i < len; i++) { args[0] = temp[i]; callback.apply(context, args) } return this }, iterate: function(callback, context) { var args = [null]; var i; for (i = 2; i < arguments.length; i++) { args.push(arguments[i]) } for (i = 0; i < this.list.length; i++) { args[0] = this.list[i]; callback.apply(context, args) } return this }, length: { get: function() { return this.list.length } }, first: { get: function() { this.position = 0; if (this.list.length > 0) { return this.list[0] } else { return null } } }, last: { get: function() { if (this.list.length > 0) { this.position = this.list.length - 1; return this.list[this.position] } else { return null } } }, next: { get: function() { if (this.position < this.list.length) { this.position++; return this.list[this.position] } else { return null } } }, previous: { get: function() { if (this.position > 0) { this.position--; return this.list[this.position] } else { return null } } }, preDestroy: function() { this.removeAll(!!this.exclusive); this.localTransform.destroy(); this.tempTransformMatrix.destroy(); this.list = []; this._displayList = null } }); module.exports = Container }, function(module, exports, __webpack_require__) { var BitmapText = __webpack_require__(124); var Class = __webpack_require__(0); var Render = __webpack_require__(706); var DynamicBitmapText = new Class({ Extends: BitmapText, Mixins: [Render], initialize: function DynamicBitmapText(scene, x, y, font, text, size, align) { BitmapText.call(this, scene, x, y, font, text, size, align); this.type = "DynamicBitmapText"; this.scrollX = 0; this.scrollY = 0; this.cropWidth = 0; this.cropHeight = 0; this.displayCallback; this.callbackData = { color: 0, tint: { topLeft: 0, topRight: 0, bottomLeft: 0, bottomRight: 0 }, index: 0, charCode: 0, x: 0, y: 0, scale: 0, rotation: 0, data: 0 } }, setSize: function(width, height) { this.cropWidth = width; this.cropHeight = height; return this }, setDisplayCallback: function(callback) { this.displayCallback = callback; return this }, setScrollX: function(value) { this.scrollX = value; return this }, setScrollY: function(value) { this.scrollY = value; return this } }); module.exports = DynamicBitmapText }, function(module, exports, __webpack_require__) { var BaseCamera = __webpack_require__(111); var Class = __webpack_require__(0); var Commands = __webpack_require__(183); var ComponentsAlpha = __webpack_require__(241); var ComponentsBlendMode = __webpack_require__(243); var ComponentsDepth = __webpack_require__(244); var ComponentsMask = __webpack_require__(248); var ComponentsPipeline = __webpack_require__(109); var ComponentsTransform = __webpack_require__(253); var ComponentsVisible = __webpack_require__(254); var ComponentsScrollFactor = __webpack_require__(251); var Ellipse = __webpack_require__(94); var GameObject = __webpack_require__(12); var GetFastValue = __webpack_require__(1); var GetValue = __webpack_require__(4); var MATH_CONST = __webpack_require__(18); var Render = __webpack_require__(709); var Graphics = new Class({ Extends: GameObject, Mixins: [ComponentsAlpha, ComponentsBlendMode, ComponentsDepth, ComponentsMask, ComponentsPipeline, ComponentsTransform, ComponentsVisible, ComponentsScrollFactor, Render], initialize: function Graphics(scene, options) { var x = GetValue(options, "x", 0); var y = GetValue(options, "y", 0); GameObject.call(this, scene, "Graphics"); this.setPosition(x, y); this.initPipeline(); this.displayOriginX = 0; this.displayOriginY = 0; this.commandBuffer = []; this.defaultFillColor = -1; this.defaultFillAlpha = 1; this.defaultStrokeWidth = 1; this.defaultStrokeColor = -1; this.defaultStrokeAlpha = 1; this._lineWidth = 1; this.setDefaultStyles(options) }, setDefaultStyles: function(options) { if (GetValue(options, "lineStyle", null)) { this.defaultStrokeWidth = GetValue(options, "lineStyle.width", 1); this.defaultStrokeColor = GetValue(options, "lineStyle.color", 16777215); this.defaultStrokeAlpha = GetValue(options, "lineStyle.alpha", 1); this.lineStyle(this.defaultStrokeWidth, this.defaultStrokeColor, this.defaultStrokeAlpha) } if (GetValue(options, "fillStyle", null)) { this.defaultFillColor = GetValue(options, "fillStyle.color", 16777215); this.defaultFillAlpha = GetValue(options, "fillStyle.alpha", 1); this.fillStyle(this.defaultFillColor, this.defaultFillAlpha) } return this }, lineStyle: function(lineWidth, color, alpha) { if (alpha === undefined) { alpha = 1 } this.commandBuffer.push(Commands.LINE_STYLE, lineWidth, color, alpha); this._lineWidth = lineWidth; return this }, fillStyle: function(color, alpha) { if (alpha === undefined) { alpha = 1 } this.commandBuffer.push(Commands.FILL_STYLE, color, alpha); return this }, fillGradientStyle: function(topLeft, topRight, bottomLeft, bottomRight, alpha) { if (alpha === undefined) { alpha = 1 } this.commandBuffer.push(Commands.GRADIENT_FILL_STYLE, alpha, topLeft, topRight, bottomLeft, bottomRight); return this }, lineGradientStyle: function(lineWidth, topLeft, topRight, bottomLeft, bottomRight, alpha) { if (alpha === undefined) { alpha = 1 } this.commandBuffer.push(Commands.GRADIENT_LINE_STYLE, lineWidth, alpha, topLeft, topRight, bottomLeft, bottomRight); return this }, setTexture: function(key, frame, mode) { if (mode === undefined) { mode = 0 } if (key === undefined) { this.commandBuffer.push(Commands.CLEAR_TEXTURE) } else { var textureFrame = this.scene.sys.textures.getFrame(key, frame); if (textureFrame) { if (mode === 2) { mode = 3 } this.commandBuffer.push(Commands.SET_TEXTURE, textureFrame, mode) } } return this }, beginPath: function() { this.commandBuffer.push(Commands.BEGIN_PATH); return this }, closePath: function() { this.commandBuffer.push(Commands.CLOSE_PATH); return this }, fillPath: function() { this.commandBuffer.push(Commands.FILL_PATH); return this }, strokePath: function() { this.commandBuffer.push(Commands.STROKE_PATH); return this }, fillCircleShape: function(circle) { return this.fillCircle(circle.x, circle.y, circle.radius) }, strokeCircleShape: function(circle) { return this.strokeCircle(circle.x, circle.y, circle.radius) }, fillCircle: function(x, y, radius) { this.beginPath(); this.arc(x, y, radius, 0, MATH_CONST.PI2); this.fillPath(); return this }, strokeCircle: function(x, y, radius) { this.beginPath(); this.arc(x, y, radius, 0, MATH_CONST.PI2); this.strokePath(); return this }, fillRectShape: function(rect) { return this.fillRect(rect.x, rect.y, rect.width, rect.height) }, strokeRectShape: function(rect) { return this.strokeRect(rect.x, rect.y, rect.width, rect.height) }, fillRect: function(x, y, width, height) { this.commandBuffer.push(Commands.FILL_RECT, x, y, width, height); return this }, strokeRect: function(x, y, width, height) { var lineWidthHalf = this._lineWidth / 2; var minx = x - lineWidthHalf; var maxx = x + lineWidthHalf; this.beginPath(); this.moveTo(x, y); this.lineTo(x, y + height); this.strokePath(); this.beginPath(); this.moveTo(x + width, y); this.lineTo(x + width, y + height); this.strokePath(); this.beginPath(); this.moveTo(minx, y); this.lineTo(maxx + width, y); this.strokePath(); this.beginPath(); this.moveTo(minx, y + height); this.lineTo(maxx + width, y + height); this.strokePath(); return this }, fillRoundedRect: function(x, y, width, height, radius) { if (radius === undefined) { radius = 20 } var tl = radius; var tr = radius; var bl = radius; var br = radius; if (typeof radius !== "number") { tl = GetFastValue(radius, "tl", 20); tr = GetFastValue(radius, "tr", 20); bl = GetFastValue(radius, "bl", 20); br = GetFastValue(radius, "br", 20) } this.beginPath(); this.moveTo(x + tl, y); this.lineTo(x + width - tr, y); this.arc(x + width - tr, y + tr, tr, -MATH_CONST.TAU, 0); this.lineTo(x + width, y + height - br); this.arc(x + width - br, y + height - br, br, 0, MATH_CONST.TAU); this.lineTo(x + bl, y + height); this.arc(x + bl, y + height - bl, bl, MATH_CONST.TAU, Math.PI); this.lineTo(x, y + tl); this.arc(x + tl, y + tl, tl, -Math.PI, -MATH_CONST.TAU); this.fillPath(); return this }, strokeRoundedRect: function(x, y, width, height, radius) { if (radius === undefined) { radius = 20 } var tl = radius; var tr = radius; var bl = radius; var br = radius; if (typeof radius !== "number") { tl = GetFastValue(radius, "tl", 20); tr = GetFastValue(radius, "tr", 20); bl = GetFastValue(radius, "bl", 20); br = GetFastValue(radius, "br", 20) } this.beginPath(); this.moveTo(x + tl, y); this.lineTo(x + width - tr, y); this.arc(x + width - tr, y + tr, tr, -MATH_CONST.TAU, 0); this.lineTo(x + width, y + height - br); this.arc(x + width - br, y + height - br, br, 0, MATH_CONST.TAU); this.lineTo(x + bl, y + height); this.arc(x + bl, y + height - bl, bl, MATH_CONST.TAU, Math.PI); this.lineTo(x, y + tl); this.arc(x + tl, y + tl, tl, -Math.PI, -MATH_CONST.TAU); this.strokePath(); return this }, fillPointShape: function(point, size) { return this.fillPoint(point.x, point.y, size) }, fillPoint: function(x, y, size) { if (!size || size < 1) { size = 1 } else { x -= size / 2; y -= size / 2 } this.commandBuffer.push(Commands.FILL_RECT, x, y, size, size); return this }, fillTriangleShape: function(triangle) { return this.fillTriangle(triangle.x1, triangle.y1, triangle.x2, triangle.y2, triangle.x3, triangle.y3) }, strokeTriangleShape: function(triangle) { return this.strokeTriangle(triangle.x1, triangle.y1, triangle.x2, triangle.y2, triangle.x3, triangle.y3) }, fillTriangle: function(x0, y0, x1, y1, x2, y2) { this.commandBuffer.push(Commands.FILL_TRIANGLE, x0, y0, x1, y1, x2, y2); return this }, strokeTriangle: function(x0, y0, x1, y1, x2, y2) { this.commandBuffer.push(Commands.STROKE_TRIANGLE, x0, y0, x1, y1, x2, y2); return this }, strokeLineShape: function(line) { return this.lineBetween(line.x1, line.y1, line.x2, line.y2) }, lineBetween: function(x1, y1, x2, y2) { this.beginPath(); this.moveTo(x1, y1); this.lineTo(x2, y2); this.strokePath(); return this }, lineTo: function(x, y) { this.commandBuffer.push(Commands.LINE_TO, x, y); return this }, moveTo: function(x, y) { this.commandBuffer.push(Commands.MOVE_TO, x, y); return this }, lineFxTo: function(x, y, width, rgb) { this.commandBuffer.push(Commands.LINE_FX_TO, x, y, width, rgb, 1); return this }, moveFxTo: function(x, y, width, rgb) { this.commandBuffer.push(Commands.MOVE_FX_TO, x, y, width, rgb, 1); return this }, strokePoints: function(points, autoClose, endIndex) { if (autoClose === undefined) { autoClose = false } if (endIndex === undefined) { endIndex = points.length } this.beginPath(); this.moveTo(points[0].x, points[0].y); for (var i = 1; i < endIndex; i++) { this.lineTo(points[i].x, points[i].y) } if (autoClose) { this.lineTo(points[0].x, points[0].y) } this.strokePath(); return this }, fillPoints: function(points, autoClose, endIndex) { if (autoClose === undefined) { autoClose = false } if (endIndex === undefined) { endIndex = points.length } this.beginPath(); this.moveTo(points[0].x, points[0].y); for (var i = 1; i < endIndex; i++) { this.lineTo(points[i].x, points[i].y) } if (autoClose) { this.lineTo(points[0].x, points[0].y) } this.fillPath(); return this }, strokeEllipseShape: function(ellipse, smoothness) { if (smoothness === undefined) { smoothness = 32 } var points = ellipse.getPoints(smoothness); return this.strokePoints(points, true) }, strokeEllipse: function(x, y, width, height, smoothness) { if (smoothness === undefined) { smoothness = 32 } var ellipse = new Ellipse(x, y, width, height); var points = ellipse.getPoints(smoothness); return this.strokePoints(points, true) }, fillEllipseShape: function(ellipse, smoothness) { if (smoothness === undefined) { smoothness = 32 } var points = ellipse.getPoints(smoothness); return this.fillPoints(points, true) }, fillEllipse: function(x, y, width, height, smoothness) { if (smoothness === undefined) { smoothness = 32 } var ellipse = new Ellipse(x, y, width, height); var points = ellipse.getPoints(smoothness); return this.fillPoints(points, true) }, arc: function(x, y, radius, startAngle, endAngle, anticlockwise, overshoot) { if (anticlockwise === undefined) { anticlockwise = false } if (overshoot === undefined) { overshoot = 0 } this.commandBuffer.push(Commands.ARC, x, y, radius, startAngle, endAngle, anticlockwise, overshoot); return this }, slice: function(x, y, radius, startAngle, endAngle, anticlockwise, overshoot) { if (anticlockwise === undefined) { anticlockwise = false } if (overshoot === undefined) { overshoot = 0 } this.commandBuffer.push(Commands.BEGIN_PATH); this.commandBuffer.push(Commands.MOVE_TO, x, y); this.commandBuffer.push(Commands.ARC, x, y, radius, startAngle, endAngle, anticlockwise, overshoot); this.commandBuffer.push(Commands.CLOSE_PATH); return this }, save: function() { this.commandBuffer.push(Commands.SAVE); return this }, restore: function() { this.commandBuffer.push(Commands.RESTORE); return this }, translate: function(x, y) { this.commandBuffer.push(Commands.TRANSLATE, x, y); return this }, scale: function(x, y) { this.commandBuffer.push(Commands.SCALE, x, y); return this }, rotate: function(radians) { this.commandBuffer.push(Commands.ROTATE, radians); return this }, clear: function() { this.commandBuffer.length = 0; if (this.defaultFillColor > -1) { this.fillStyle(this.defaultFillColor, this.defaultFillAlpha) } if (this.defaultStrokeColor > -1) { this.lineStyle(this.defaultStrokeWidth, this.defaultStrokeColor, this.defaultStrokeAlpha) } return this }, generateTexture: function(key, width, height) { var sys = this.scene.sys; var renderer = sys.game.renderer; if (width === undefined) { width = sys.game.config.width } if (height === undefined) { height = sys.game.config.height } Graphics.TargetCamera.setScene(this.scene); Graphics.TargetCamera.setViewport(0, 0, width, height); Graphics.TargetCamera.scrollX = this.x; Graphics.TargetCamera.scrollY = this.y; var texture; var ctx; if (typeof key === "string") { if (sys.textures.exists(key)) { texture = sys.textures.get(key); var src = texture.getSourceImage(); if (src instanceof HTMLCanvasElement) { ctx = src.getContext("2d") } } else { texture = sys.textures.createCanvas(key, width, height); ctx = texture.getSourceImage().getContext("2d") } } else if (key instanceof HTMLCanvasElement) { ctx = key.getContext("2d") } if (ctx) { this.renderCanvas(renderer, this, 0, Graphics.TargetCamera, null, ctx, false); if (texture) { texture.refresh() } } return this }, preDestroy: function() { this.commandBuffer = [] } }); Graphics.TargetCamera = new BaseCamera; module.exports = Graphics }, function(module, exports) { module.exports = { ARC: 0, BEGIN_PATH: 1, CLOSE_PATH: 2, FILL_RECT: 3, LINE_TO: 4, MOVE_TO: 5, LINE_STYLE: 6, FILL_STYLE: 7, FILL_PATH: 8, STROKE_PATH: 9, FILL_TRIANGLE: 10, STROKE_TRIANGLE: 11, LINE_FX_TO: 12, MOVE_FX_TO: 13, SAVE: 14, RESTORE: 15, TRANSLATE: 16, SCALE: 17, ROTATE: 18, SET_TEXTURE: 19, CLEAR_TEXTURE: 20, GRADIENT_FILL_STYLE: 21, GRADIENT_LINE_STYLE: 22 } }, function(module, exports, __webpack_require__) { var Point = __webpack_require__(6); var CircumferencePoint = function(ellipse, angle, out) { if (out === undefined) { out = new Point } var halfWidth = ellipse.width / 2; var halfHeight = ellipse.height / 2; out.x = ellipse.x + halfWidth * Math.cos(angle); out.y = ellipse.y + halfHeight * Math.sin(angle); return out }; module.exports = CircumferencePoint }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Components = __webpack_require__(14); var GameObject = __webpack_require__(12); var GravityWell = __webpack_require__(345); var List = __webpack_require__(121); var ParticleEmitter = __webpack_require__(347); var Render = __webpack_require__(719); var ParticleEmitterManager = new Class({ Extends: GameObject, Mixins: [Components.Depth, Components.Pipeline, Components.Transform, Components.Visible, Render], initialize: function ParticleEmitterManager(scene, texture, frame, emitters) { GameObject.call(this, scene, "ParticleEmitterManager"); this.blendMode = -1; this.timeScale = 1; this.texture = null; this.frame = null; this.frameNames = []; if (frame !== null && (typeof frame === "object" || Array.isArray(frame))) { emitters = frame; frame = null } this.setTexture(texture, frame); this.initPipeline(); this.emitters = new List(this); this.wells = new List(this); if (emitters) { if (!Array.isArray(emitters)) { emitters = [emitters] } for (var i = 0; i < emitters.length; i++) { this.createEmitter(emitters[i]) } } }, setTexture: function(key, frame) { this.texture = this.scene.sys.textures.get(key); return this.setFrame(frame) }, setFrame: function(frame) { this.frame = this.texture.get(frame); var frames = this.texture.getFramesFromTextureSource(this.frame.sourceIndex); var names = []; frames.forEach(function(sourceFrame) { names.push(sourceFrame.name) }); this.frameNames = names; this.defaultFrame = this.frame; return this }, setEmitterFrames: function(frames, emitter) { if (!Array.isArray(frames)) { frames = [frames] } var out = emitter.frames; out.length = 0; for (var i = 0; i < frames.length; i++) { var frame = frames[i]; if (this.frameNames.indexOf(frame) !== -1) { out.push(this.texture.get(frame)) } } if (out.length > 0) { emitter.defaultFrame = out[0] } else { emitter.defaultFrame = this.defaultFrame } return this }, addEmitter: function(emitter) { return this.emitters.add(emitter) }, createEmitter: function(config) { return this.addEmitter(new ParticleEmitter(this, config)) }, addGravityWell: function(well) { return this.wells.add(well) }, createGravityWell: function(config) { return this.addGravityWell(new GravityWell(config)) }, emitParticle: function(count, x, y) { var emitters = this.emitters.list; for (var i = 0; i < emitters.length; i++) { var emitter = emitters[i]; if (emitter.active) { emitter.emitParticle(count, x, y) } } return this }, emitParticleAt: function(x, y, count) { return this.emitParticle(count, x, y) }, pause: function() { this.active = false; return this }, resume: function() { this.active = true; return this }, getProcessors: function() { return this.wells.getAll("active", true) }, preUpdate: function(time, delta) { delta *= this.timeScale; var emitters = this.emitters.list; for (var i = 0; i < emitters.length; i++) { var emitter = emitters[i]; if (emitter.active) { emitter.preUpdate(time, delta) } } }, setAlpha: function() {}, setScrollFactor: function() {}, setBlendMode: function() {} }); module.exports = ParticleEmitterManager }, function(module, exports, __webpack_require__) { var Camera = __webpack_require__(111); var CanvasPool = __webpack_require__(28); var Class = __webpack_require__(0); var Components = __webpack_require__(14); var CONST = __webpack_require__(26); var Frame = __webpack_require__(120); var GameObject = __webpack_require__(12); var Render = __webpack_require__(723); var UUID = __webpack_require__(354); var RenderTexture = new Class({ Extends: GameObject, Mixins: [Components.Alpha, Components.BlendMode, Components.ComputedSize, Components.Crop, Components.Depth, Components.Flip, Components.GetBounds, Components.Mask, Components.Origin, Components.Pipeline, Components.ScaleMode, Components.ScrollFactor, Components.Tint, Components.Transform, Components.Visible, Render], initialize: function RenderTexture(scene, x, y, width, height) { if (x === undefined) { x = 0 } if (y === undefined) { y = 0 } if (width === undefined) { width = 32 } if (height === undefined) { height = 32 } GameObject.call(this, scene, "RenderTexture"); this.renderer = scene.sys.game.renderer; this.textureManager = scene.sys.textures; this.globalTint = 16777215; this.globalAlpha = 1; this.canvas = CanvasPool.create2D(this, width, height); this.context = this.canvas.getContext("2d"); this.framebuffer = null; this._crop = this.resetCropObject(); this.texture = scene.sys.textures.addCanvas(UUID(), this.canvas); this.frame = this.texture.get(); this._saved = false; this.camera = new Camera(0, 0, width, height); this.dirty = false; this.gl = null; var renderer = this.renderer; if (renderer.type === CONST.WEBGL) { var gl = renderer.gl; this.gl = gl; this.drawGameObject = this.batchGameObjectWebGL; this.framebuffer = renderer.createFramebuffer(width, height, this.frame.source.glTexture, false) } else if (renderer.type === CONST.CANVAS) { this.drawGameObject = this.batchGameObjectCanvas } this.camera.setScene(scene); this.setPosition(x, y); this.setSize(width, height); this.setOrigin(0, 0); this.initPipeline() }, setSize: function(width, height) { return this.resize(width, height) }, resize: function(width, height) { if (height === undefined) { height = width } if (width !== this.width || height !== this.height) { this.canvas.width = width; this.canvas.height = height; if (this.gl) { var gl = this.gl; this.renderer.deleteTexture(this.frame.source.glTexture); this.renderer.deleteFramebuffer(this.framebuffer); this.frame.source.glTexture = this.renderer.createTexture2D(0, gl.NEAREST, gl.NEAREST, gl.CLAMP_TO_EDGE, gl.CLAMP_TO_EDGE, gl.RGBA, null, width, height, false); this.framebuffer = this.renderer.createFramebuffer(width, height, this.frame.source.glTexture, false); this.frame.glTexture = this.frame.source.glTexture } this.frame.source.width = width; this.frame.source.height = height; this.camera.setSize(width, height); this.frame.setSize(width, height); this.width = width; this.height = height } return this }, setGlobalTint: function(tint) { this.globalTint = tint; return this }, setGlobalAlpha: function(alpha) { this.globalAlpha = alpha; return this }, saveTexture: function(key) { this.textureManager.renameTexture(this.texture.key, key); this._saved = true; return this.texture }, fill: function(rgb, alpha) { if (alpha === undefined) { alpha = 1 } var ur = (rgb >> 16 | 0) & 255; var ug = (rgb >> 8 | 0) & 255; var ub = (rgb | 0) & 255; if (this.gl) { this.renderer.setFramebuffer(this.framebuffer); var gl = this.gl; gl.clearColor(ur / 255, ug / 255, ub / 255, alpha); gl.clear(gl.COLOR_BUFFER_BIT); this.renderer.setFramebuffer(null) } else { this.context.fillStyle = "rgb(" + ur + "," + ug + "," + ub + ")"; this.context.fillRect(0, 0, this.canvas.width, this.canvas.height) } return this }, clear: function() { if (this.dirty) { if (this.gl) { this.renderer.setFramebuffer(this.framebuffer); var gl = this.gl; gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT); this.renderer.setFramebuffer(null) } else { var ctx = this.context; ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); ctx.restore() } this.dirty = false } return this }, draw: function(entries, x, y, alpha, tint) { if (alpha === undefined) { alpha = this.globalAlpha } if (tint === undefined) { tint = (this.globalTint >> 16) + (this.globalTint & 65280) + ((this.globalTint & 255) << 16) } else { tint = (tint >> 16) + (tint & 65280) + ((tint & 255) << 16) } if (!Array.isArray(entries)) { entries = [entries] } var gl = this.gl; this.camera.preRender(1, 1, 1); if (gl) { this.renderer.setFramebuffer(this.framebuffer); var pipeline = this.pipeline; pipeline.projOrtho(0, this.width, 0, this.height, -1e3, 1e3); this.batchList(entries, x, y, alpha, tint); pipeline.flush(); this.renderer.setFramebuffer(null); pipeline.projOrtho(0, pipeline.width, pipeline.height, 0, -1e3, 1e3) } else { this.renderer.setContext(this.context); this.batchList(entries, x, y, alpha, tint); this.renderer.setContext() } this.dirty = true; return this }, drawFrame: function(key, frame, x, y, alpha, tint) { if (x === undefined) { x = 0 } if (y === undefined) { y = 0 } if (alpha === undefined) { alpha = this.globalAlpha } if (tint === undefined) { tint = (this.globalTint >> 16) + (this.globalTint & 65280) + ((this.globalTint & 255) << 16) } else { tint = (tint >> 16) + (tint & 65280) + ((tint & 255) << 16) } var gl = this.gl; var textureFrame = this.textureManager.getFrame(key, frame); if (textureFrame) { this.camera.preRender(1, 1, 1); if (gl) { this.renderer.setFramebuffer(this.framebuffer); var pipeline = this.pipeline; pipeline.projOrtho(0, this.width, 0, this.height, -1e3, 1e3); pipeline.batchTextureFrame(textureFrame, x, y, tint, alpha, this.camera.matrix, null); pipeline.flush(); this.renderer.setFramebuffer(null); pipeline.projOrtho(0, pipeline.width, pipeline.height, 0, -1e3, 1e3) } else { this.batchTextureFrame(textureFrame, x, y, alpha, tint) } this.dirty = true } return this }, batchList: function(children, x, y, alpha, tint) { for (var i = 0; i < children.length; i++) { var entry = children[i]; if (!entry || entry === this) { continue } if (entry.renderWebGL || entry.renderCanvas) { this.drawGameObject(entry, x, y) } else if (entry.isParent || entry.list) { this.batchGroup(entry.getChildren(), x, y) } else if (typeof entry === "string") { this.batchTextureFrameKey(entry, null, x, y, alpha, tint) } else if (entry instanceof Frame) { this.batchTextureFrame(entry, x, y, alpha, tint) } else if (Array.isArray(entry)) { this.batchList(entry, x, y, alpha, tint) } } }, batchGroup: function(children, x, y) { if (x === undefined) { x = 0 } if (y === undefined) { y = 0 } for (var i = 0; i < children.length; i++) { var entry = children[i]; if (entry.willRender()) { var tx = entry.x + x; var ty = entry.y + y; this.drawGameObject(entry, tx, ty) } } }, batchGameObjectWebGL: function(gameObject, x, y) { if (x === undefined) { x = gameObject.x } if (y === undefined) { y = gameObject.y } var prevX = gameObject.x; var prevY = gameObject.y; this.renderer.setBlendMode(gameObject.blendMode); gameObject.setPosition(x, y); gameObject.renderWebGL(this.renderer, gameObject, 0, this.camera, null); gameObject.setPosition(prevX, prevY) }, batchGameObjectCanvas: function(gameObject, x, y) { if (x === undefined) { x = gameObject.x } if (y === undefined) { y = gameObject.y } var prevX = gameObject.x; var prevY = gameObject.y; gameObject.setPosition(x, y); gameObject.renderCanvas(this.renderer, gameObject, 0, this.camera, null); gameObject.setPosition(prevX, prevY) }, batchTextureFrameKey: function(key, frame, x, y, alpha, tint) { var textureFrame = this.textureManager.getFrame(key, frame); if (textureFrame) { this.batchTextureFrame(textureFrame, x, y, alpha, tint) } }, batchTextureFrame: function(textureFrame, x, y, alpha, tint) { if (x === undefined) { x = 0 } if (y === undefined) { y = 0 } if (this.gl) { this.pipeline.batchTextureFrame(textureFrame, x, y, tint, alpha, this.camera.matrix, null) } else { var ctx = this.context; var cd = textureFrame.canvasData; var source = textureFrame.source.image; var matrix = this.camera.matrix; ctx.globalAlpha = this.globalAlpha; ctx.setTransform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]); ctx.drawImage(source, cd.x, cd.y, cd.width, cd.height, x, y, cd.width, cd.height) } }, preDestroy: function() { if (!this._saved) { CanvasPool.remove(this.canvas); if (this.gl) { this.renderer.deleteFramebuffer(this.framebuffer) } this.texture.destroy() } } }); module.exports = RenderTexture }, function(module, exports, __webpack_require__) { var AddToDOM = __webpack_require__(114); var CanvasPool = __webpack_require__(28); var Class = __webpack_require__(0); var Components = __webpack_require__(14); var CONST = __webpack_require__(26); var GameObject = __webpack_require__(12); var GetTextSize = __webpack_require__(729); var GetValue = __webpack_require__(4); var RemoveFromDOM = __webpack_require__(168); var TextRender = __webpack_require__(730); var TextStyle = __webpack_require__(733); var Text = new Class({ Extends: GameObject, Mixins: [Components.Alpha, Components.BlendMode, Components.ComputedSize, Components.Crop, Components.Depth, Components.Flip, Components.GetBounds, Components.Mask, Components.Origin, Components.Pipeline, Components.ScaleMode, Components.ScrollFactor, Components.Tint, Components.Transform, Components.Visible, TextRender], initialize: function Text(scene, x, y, text, style) { if (x === undefined) { x = 0 } if (y === undefined) { y = 0 } GameObject.call(this, scene, "Text"); this.renderer = scene.sys.game.renderer; this.setPosition(x, y); this.setOrigin(0, 0); this.initPipeline(); this.canvas = CanvasPool.create(this); this.context = this.canvas.getContext("2d"); this.style = new TextStyle(this, style); this.autoRound = true; this.splitRegExp = /(?:\r\n|\r|\n)/; this._text = ""; this.padding = { left: 0, right: 0, top: 0, bottom: 0 }; this.width = 1; this.height = 1; this.lineSpacing = 0; this.dirty = false; if (this.style.resolution === 0) { this.style.resolution = scene.sys.game.config.resolution } this._crop = this.resetCropObject(); this.texture = scene.sys.textures.addCanvas(null, this.canvas, true); this.frame = this.texture.get(); this.frame.source.resolution = this.style.resolution; if (this.renderer && this.renderer.gl) { this.renderer.deleteTexture(this.frame.source.glTexture); this.frame.source.glTexture = null } this.initRTL(); if (style && style.padding) { this.setPadding(style.padding) } if (style && style.lineSpacing) { this.lineSpacing = style.lineSpacing } this.setText(text); if (scene.sys.game.config.renderType === CONST.WEBGL) { scene.sys.game.renderer.onContextRestored(function() { this.dirty = true }, this) } }, initRTL: function() { if (!this.style.rtl) { return } this.canvas.dir = "rtl"; this.context.direction = "rtl"; this.canvas.style.display = "none"; AddToDOM(this.canvas, this.scene.sys.canvas); this.originX = 1 }, runWordWrap: function(text) { var style = this.style; if (style.wordWrapCallback) { var wrappedLines = style.wordWrapCallback.call(style.wordWrapCallbackScope, text, this); if (Array.isArray(wrappedLines)) { wrappedLines = wrappedLines.join("\n") } return wrappedLines } else if (style.wordWrapWidth) { if (style.wordWrapUseAdvanced) { return this.advancedWordWrap(text, this.context, this.style.wordWrapWidth) } else { return this.basicWordWrap(text, this.context, this.style.wordWrapWidth) } } else { return text } }, advancedWordWrap: function(text, context, wordWrapWidth) { var output = ""; var lines = text.replace(/ +/gi, " ").split(this.splitRegExp); var linesCount = lines.length; for (var i = 0; i < linesCount; i++) { var line = lines[i]; var out = ""; line = line.replace(/^ *|\s*$/gi, ""); var lineWidth = context.measureText(line).width; if (lineWidth < wordWrapWidth) { output += line + "\n"; continue } var currentLineWidth = wordWrapWidth; var words = line.split(" "); for (var j = 0; j < words.length; j++) { var word = words[j]; var wordWithSpace = word + " "; var wordWidth = context.measureText(wordWithSpace).width; if (wordWidth > currentLineWidth) { if (j === 0) { var newWord = wordWithSpace; while (newWord.length) { newWord = newWord.slice(0, -1); wordWidth = context.measureText(newWord).width; if (wordWidth <= currentLineWidth) { break } } if (!newWord.length) { throw new Error("This text's wordWrapWidth setting is less than a single character!") } var secondPart = word.substr(newWord.length); words[j] = secondPart; out += newWord } var offset = words[j].length ? j : j + 1; var remainder = words.slice(offset).join(" ").replace(/[ \n]*$/gi, ""); lines[i + 1] = remainder + " " + (lines[i + 1] || ""); linesCount = lines.length; break } else { out += wordWithSpace; currentLineWidth -= wordWidth } } output += out.replace(/[ \n]*$/gi, "") + "\n" } output = output.replace(/[\s|\n]*$/gi, ""); return output }, basicWordWrap: function(text, context, wordWrapWidth) { var result = ""; var lines = text.split(this.splitRegExp); for (var i = 0; i < lines.length; i++) { var spaceLeft = wordWrapWidth; var words = lines[i].split(" "); for (var j = 0; j < words.length; j++) { var wordWidth = context.measureText(words[j]).width; var wordWidthWithSpace = wordWidth + context.measureText(" ").width; if (wordWidthWithSpace > spaceLeft) { if (j > 0) { result += "\n" } result += words[j] + " "; spaceLeft = wordWrapWidth - wordWidth } else { spaceLeft -= wordWidthWithSpace; result += words[j]; if (j < words.length - 1) { result += " " } } } if (i < lines.length - 1) { result += "\n" } } return result }, getWrappedText: function(text) { if (text === undefined) { text = this._text } this.style.syncFont(this.canvas, this.context); var wrappedLines = this.runWordWrap(text); return wrappedLines.split(this.splitRegExp) }, setText: function(value) { if (!value && value !== 0) { value = "" } if (Array.isArray(value)) { value = value.join("\n") } if (value !== this._text) { this._text = value.toString(); this.updateText() } return this }, setStyle: function(style) { return this.style.setStyle(style) }, setFont: function(font) { return this.style.setFont(font) }, setFontFamily: function(family) { return this.style.setFontFamily(family) }, setFontSize: function(size) { return this.style.setFontSize(size) }, setFontStyle: function(style) { return this.style.setFontStyle(style) }, setFixedSize: function(width, height) { return this.style.setFixedSize(width, height) }, setBackgroundColor: function(color) { return this.style.setBackgroundColor(color) }, setFill: function(color) { return this.style.setFill(color) }, setColor: function(color) { return this.style.setColor(color) }, setStroke: function(color, thickness) { return this.style.setStroke(color, thickness) }, setShadow: function(x, y, color, blur, shadowStroke, shadowFill) { return this.style.setShadow(x, y, color, blur, shadowStroke, shadowFill) }, setShadowOffset: function(x, y) { return this.style.setShadowOffset(x, y) }, setShadowColor: function(color) { return this.style.setShadowColor(color) }, setShadowBlur: function(blur) { return this.style.setShadowBlur(blur) }, setShadowStroke: function(enabled) { return this.style.setShadowStroke(enabled) }, setShadowFill: function(enabled) { return this.style.setShadowFill(enabled) }, setWordWrapWidth: function(width, useAdvancedWrap) { return this.style.setWordWrapWidth(width, useAdvancedWrap) }, setWordWrapCallback: function(callback, scope) { return this.style.setWordWrapCallback(callback, scope) }, setAlign: function(align) { return this.style.setAlign(align) }, setResolution: function(value) { return this.style.setResolution(value) }, setLineSpacing: function(value) { this.lineSpacing = value; return this.updateText() }, setPadding: function(left, top, right, bottom) { if (typeof left === "object") { var config = left; var x = GetValue(config, "x", null); if (x !== null) { left = x; right = x } else { left = GetValue(config, "left", 0); right = GetValue(config, "right", left) } var y = GetValue(config, "y", null); if (y !== null) { top = y; bottom = y } else { top = GetValue(config, "top", 0); bottom = GetValue(config, "bottom", top) } } else { if (left === undefined) { left = 0 } if (top === undefined) { top = left } if (right === undefined) { right = left } if (bottom === undefined) { bottom = top } } this.padding.left = left; this.padding.top = top; this.padding.right = right; this.padding.bottom = bottom; return this.updateText() }, setMaxLines: function(max) { return this.style.setMaxLines(max) }, updateText: function() { var canvas = this.canvas; var context = this.context; var style = this.style; var resolution = style.resolution; var size = style.metrics; style.syncFont(canvas, context); var outputText = this._text; if (style.wordWrapWidth || style.wordWrapCallback) { outputText = this.runWordWrap(this._text) } var lines = outputText.split(this.splitRegExp); var textSize = GetTextSize(this, size, lines); var padding = this.padding; var w = textSize.width + padding.left + padding.right; var h = textSize.height + padding.top + padding.bottom; if (style.fixedWidth === 0) { this.width = w } if (style.fixedHeight === 0) { this.height = h } this.updateDisplayOrigin(); w *= resolution; h *= resolution; w = Math.max(w, 1); h = Math.max(h, 1); if (canvas.width !== w || canvas.height !== h) { canvas.width = w; canvas.height = h; this.frame.setSize(w, h); style.syncFont(canvas, context) } else { context.clearRect(0, 0, w, h) } context.save(); context.scale(resolution, resolution); if (style.backgroundColor) { context.fillStyle = style.backgroundColor; context.fillRect(0, 0, w, h) } style.syncStyle(canvas, context); context.textBaseline = "alphabetic"; context.translate(padding.left, padding.top); var linePositionX; var linePositionY; for (var i = 0; i < textSize.lines; i++) { linePositionX = style.strokeThickness / 2; linePositionY = style.strokeThickness / 2 + i * textSize.lineHeight + size.ascent; if (i > 0) { linePositionY += textSize.lineSpacing * i } if (style.rtl) { linePositionX = w - linePositionX } else if (style.align === "right") { linePositionX += textSize.width - textSize.lineWidths[i] } else if (style.align === "center") { linePositionX += (textSize.width - textSize.lineWidths[i]) / 2 } if (this.autoRound) { linePositionX = Math.round(linePositionX); linePositionY = Math.round(linePositionY) } if (style.strokeThickness) { this.style.syncShadow(context, style.shadowStroke); context.strokeText(lines[i], linePositionX, linePositionY) } if (style.color) { this.style.syncShadow(context, style.shadowFill); context.fillText(lines[i], linePositionX, linePositionY) } } context.restore(); if (this.renderer.gl) { this.frame.source.glTexture = this.renderer.canvasToTexture(canvas, this.frame.source.glTexture, true); this.frame.glTexture = this.frame.source.glTexture } this.dirty = true; return this }, getTextMetrics: function() { return this.style.getTextMetrics() }, text: { get: function() { return this._text }, set: function(value) { this.setText(value) } }, toJSON: function() { var out = Components.ToJSON(this); var data = { autoRound: this.autoRound, text: this._text, style: this.style.toJSON(), padding: { left: this.padding.left, right: this.padding.right, top: this.padding.top, bottom: this.padding.bottom } }; out.data = data; return out }, preDestroy: function() { if (this.style.rtl) { RemoveFromDOM(this.canvas) } CanvasPool.remove(this.canvas); this.texture.destroy() } }); module.exports = Text }, function(module, exports, __webpack_require__) { var CanvasPool = __webpack_require__(28); var Class = __webpack_require__(0); var Components = __webpack_require__(14); var CONST = __webpack_require__(26); var GameObject = __webpack_require__(12); var GetPowerOfTwo = __webpack_require__(355); var Smoothing = __webpack_require__(112); var TileSpriteRender = __webpack_require__(735); var Vector2 = __webpack_require__(3); var _FLAG = 8; var TileSprite = new Class({ Extends: GameObject, Mixins: [Components.Alpha, Components.BlendMode, Components.ComputedSize, Components.Crop, Components.Depth, Components.Flip, Components.GetBounds, Components.Mask, Components.Origin, Components.Pipeline, Components.ScaleMode, Components.ScrollFactor, Components.Tint, Components.Transform, Components.Visible, TileSpriteRender], initialize: function TileSprite(scene, x, y, width, height, textureKey, frameKey) { var renderer = scene.sys.game.renderer; GameObject.call(this, scene, "TileSprite"); var displayTexture = scene.sys.textures.get(textureKey); var displayFrame = displayTexture.get(frameKey); if (!width || !height) { width = displayFrame.width; height = displayFrame.height } else { width = Math.floor(width); height = Math.floor(height) } this._tilePosition = new Vector2; this._tileScale = new Vector2(1, 1); this.dirty = false; this.renderer = renderer; this.canvas = CanvasPool.create(this, width, height); this.context = this.canvas.getContext("2d"); this.displayTexture = displayTexture; this.displayFrame = displayFrame; this._crop = this.resetCropObject(); this.texture = scene.sys.textures.addCanvas(null, this.canvas, true); this.frame = this.texture.get(); this.potWidth = GetPowerOfTwo(displayFrame.width); this.potHeight = GetPowerOfTwo(displayFrame.height); this.fillCanvas = CanvasPool.create2D(this, this.potWidth, this.potHeight); this.fillContext = this.fillCanvas.getContext("2d"); this.fillPattern = null; this.setPosition(x, y); this.setSize(width, height); this.setFrame(frameKey); this.setOriginFromFrame(); this.initPipeline(); if (scene.sys.game.config.renderType === CONST.WEBGL) { scene.sys.game.renderer.onContextRestored(function(renderer) { var gl = renderer.gl; this.dirty = true; this.fillPattern = null; this.fillPattern = renderer.createTexture2D(0, gl.LINEAR, gl.LINEAR, gl.REPEAT, gl.REPEAT, gl.RGBA, this.fillCanvas, this.potWidth, this.potHeight) }, this) } }, setTexture: function(key, frame) { this.displayTexture = this.scene.sys.textures.get(key); return this.setFrame(frame) }, setFrame: function(frame) { this.displayFrame = this.displayTexture.get(frame); if (!this.displayFrame.cutWidth || !this.displayFrame.cutHeight) { this.renderFlags &= ~_FLAG } else { this.renderFlags |= _FLAG } this.dirty = true; this.updateTileTexture(); return this }, setTilePosition: function(x, y) { if (x !== undefined) { this.tilePositionX = x } if (y !== undefined) { this.tilePositionY = y } return this }, setTileScale: function(x, y) { if (x !== undefined) { this.tileScaleX = x } if (y !== undefined) { this.tileScaleY = y } return this }, updateTileTexture: function() { if (!this.dirty) { return } var frame = this.displayFrame; var ctx = this.fillContext; var canvas = this.fillCanvas; var fw = this.potWidth; var fh = this.potHeight; if (!this.renderer.gl) { fw = frame.cutWidth; fh = frame.cutHeight } ctx.clearRect(0, 0, fw, fh); canvas.width = fw; canvas.height = fh; ctx.drawImage(frame.source.image, frame.cutX, frame.cutY, frame.cutWidth, frame.cutHeight, 0, 0, fw, fh); if (this.renderer.gl) { this.fillPattern = this.renderer.canvasToTexture(canvas, this.fillPattern) } else { this.fillPattern = ctx.createPattern(canvas, "repeat") } this.updateCanvas(); this.dirty = false }, updateCanvas: function() { var canvas = this.canvas; if (canvas.width !== this.width || canvas.height !== this.height) { canvas.width = this.width; canvas.height = this.height; this.frame.setSize(this.width, this.height) } if (!this.dirty || this.renderer && this.renderer.gl) { this.dirty = false; return } var ctx = this.context; if (!this.scene.sys.game.config.antialias) { Smoothing.disable(ctx) } var scaleX = this._tileScale.x; var scaleY = this._tileScale.y; var positionX = this._tilePosition.x; var positionY = this._tilePosition.y; ctx.clearRect(0, 0, this.width, this.height); ctx.save(); ctx.scale(scaleX, scaleY); ctx.translate(-positionX, -positionY); ctx.fillStyle = this.fillPattern; ctx.fillRect(positionX, positionY, this.width / scaleX, this.height / scaleY); ctx.restore(); this.dirty = false }, preDestroy: function() { if (this.renderer && this.renderer.gl) { this.renderer.deleteTexture(this.fillPattern) } CanvasPool.remove(this.canvas); CanvasPool.remove(this.fillCanvas); this.fillPattern = null; this.fillContext = null; this.fillCanvas = null; this.displayTexture = null; this.displayFrame = null; this.texture.destroy(); this.renderer = null }, tilePositionX: { get: function() { return this._tilePosition.x }, set: function(value) { this._tilePosition.x = value; this.dirty = true } }, tilePositionY: { get: function() { return this._tilePosition.y }, set: function(value) { this._tilePosition.y = value; this.dirty = true } }, tileScaleX: { get: function() { return this._tileScale.x }, set: function(value) { this._tileScale.x = value; this.dirty = true } }, tileScaleY: { get: function() { return this._tileScale.y }, set: function(value) { this._tileScale.y = value; this.dirty = true } } }); module.exports = TileSprite }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Contains = __webpack_require__(190); var GetPoints = __webpack_require__(365); var Polygon = new Class({ initialize: function Polygon(points) { this.area = 0; this.points = []; if (points) { this.setTo(points) } }, contains: function(x, y) { return Contains(this, x, y) }, setTo: function(points) { this.area = 0; this.points = []; if (typeof points === "string") { points = points.split(" ") } if (!Array.isArray(points)) { return this } var p; var y0 = Number.MAX_VALUE; for (var i = 0; i < points.length; i++) { p = { x: 0, y: 0 }; if (typeof points[i] === "number" || typeof points[i] === "string") { p.x = parseFloat(points[i]); p.y = parseFloat(points[i + 1]); i++ } else if (Array.isArray(points[i])) { p.x = points[i][0]; p.y = points[i][1] } else { p.x = points[i].x; p.y = points[i].y } this.points.push(p); if (p.y < y0) { y0 = p.y } } this.calculateArea(y0); return this }, calculateArea: function() { if (this.points.length < 3) { this.area = 0; return this.area } var sum = 0; var p1; var p2; for (var i = 0; i < this.points.length - 1; i++) { p1 = this.points[i]; p2 = this.points[i + 1]; sum += (p2.x - p1.x) * (p1.y + p2.y) } p1 = this.points[0]; p2 = this.points[this.points.length - 1]; sum += (p1.x - p2.x) * (p2.y + p1.y); this.area = -sum * .5; return this.area }, getPoints: function(quantity, step, output) { return GetPoints(this, quantity, step, output) } }); module.exports = Polygon }, function(module, exports) { var Contains = function(polygon, x, y) { var inside = false; for (var i = -1, j = polygon.points.length - 1; ++i < polygon.points.length; j = i) { var ix = polygon.points[i].x; var iy = polygon.points[i].y; var jx = polygon.points[j].x; var jy = polygon.points[j].y; if ((iy <= y && y < jy || jy <= y && y < iy) && x < (jx - ix) * (y - iy) / (jy - iy) + ix) { inside = !inside } } return inside }; module.exports = Contains }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Mesh = __webpack_require__(126); var Quad = new Class({ Extends: Mesh, initialize: function Quad(scene, x, y, texture, frame) { var vertices = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; var uv = [0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0]; var colors = [16777215, 16777215, 16777215, 16777215, 16777215, 16777215]; var alphas = [1, 1, 1, 1, 1, 1]; Mesh.call(this, scene, x, y, vertices, uv, colors, alphas, texture, frame); this.resetPosition() }, setFrame: function(frame) { this.frame = this.texture.get(frame); if (!this.frame.cutWidth || !this.frame.cutHeight) { this.renderFlags &= ~8 } else { this.renderFlags |= 8 } frame = this.frame; this.uv[0] = frame.u0; this.uv[1] = frame.v0; this.uv[2] = frame.u0; this.uv[3] = frame.v1; this.uv[4] = frame.u1; this.uv[5] = frame.v1; this.uv[6] = frame.u0; this.uv[7] = frame.v0; this.uv[8] = frame.u1; this.uv[9] = frame.v1; this.uv[10] = frame.u1; this.uv[11] = frame.v0; return this }, topLeftX: { get: function() { return this.x + this.vertices[0] }, set: function(value) { this.vertices[0] = value - this.x; this.vertices[6] = value - this.x } }, topLeftY: { get: function() { return this.y + this.vertices[1] }, set: function(value) { this.vertices[1] = value - this.y; this.vertices[7] = value - this.y } }, topRightX: { get: function() { return this.x + this.vertices[10] }, set: function(value) { this.vertices[10] = value - this.x } }, topRightY: { get: function() { return this.y + this.vertices[11] }, set: function(value) { this.vertices[11] = value - this.y } }, bottomLeftX: { get: function() { return this.x + this.vertices[2] }, set: function(value) { this.vertices[2] = value - this.x } }, bottomLeftY: { get: function() { return this.y + this.vertices[3] }, set: function(value) { this.vertices[3] = value - this.y } }, bottomRightX: { get: function() { return this.x + this.vertices[4] }, set: function(value) { this.vertices[4] = value - this.x; this.vertices[8] = value - this.x } }, bottomRightY: { get: function() { return this.y + this.vertices[5] }, set: function(value) { this.vertices[5] = value - this.y; this.vertices[9] = value - this.y } }, topLeftAlpha: { get: function() { return this.alphas[0] }, set: function(value) { this.alphas[0] = value; this.alphas[3] = value } }, topRightAlpha: { get: function() { return this.alphas[5] }, set: function(value) { this.alphas[5] = value } }, bottomLeftAlpha: { get: function() { return this.alphas[1] }, set: function(value) { this.alphas[1] = value } }, bottomRightAlpha: { get: function() { return this.alphas[2] }, set: function(value) { this.alphas[2] = value; this.alphas[4] = value } }, topLeftColor: { get: function() { return this.colors[0] }, set: function(value) { this.colors[0] = value; this.colors[3] = value } }, topRightColor: { get: function() { return this.colors[5] }, set: function(value) { this.colors[5] = value } }, bottomLeftColor: { get: function() { return this.colors[1] }, set: function(value) { this.colors[1] = value } }, bottomRightColor: { get: function() { return this.colors[2] }, set: function(value) { this.colors[2] = value; this.colors[4] = value } }, setTopLeft: function(x, y) { this.topLeftX = x; this.topLeftY = y; return this }, setTopRight: function(x, y) { this.topRightX = x; this.topRightY = y; return this }, setBottomLeft: function(x, y) { this.bottomLeftX = x; this.bottomLeftY = y; return this }, setBottomRight: function(x, y) { this.bottomRightX = x; this.bottomRightY = y; return this }, resetPosition: function() { var x = this.x; var y = this.y; var halfWidth = Math.floor(this.width / 2); var halfHeight = Math.floor(this.height / 2); this.setTopLeft(x - halfWidth, y - halfHeight); this.setTopRight(x + halfWidth, y - halfHeight); this.setBottomLeft(x - halfWidth, y + halfHeight); this.setBottomRight(x + halfWidth, y + halfHeight); return this }, resetAlpha: function() { var alphas = this.alphas; alphas[0] = 1; alphas[1] = 1; alphas[2] = 1; alphas[3] = 1; alphas[4] = 1; alphas[5] = 1; return this }, resetColors: function() { var colors = this.colors; colors[0] = 16777215; colors[1] = 16777215; colors[2] = 16777215; colors[3] = 16777215; colors[4] = 16777215; colors[5] = 16777215; return this }, reset: function() { this.resetPosition(); this.resetAlpha(); return this.resetColors() } }); module.exports = Quad }, function(module, exports) { var RectangleToRectangle = function(rectA, rectB) { if (rectA.width <= 0 || rectA.height <= 0 || rectB.width <= 0 || rectB.height <= 0) { return false } return !(rectA.right < rectB.x || rectA.bottom < rectB.y || rectA.x > rectB.right || rectA.y > rectB.bottom) }; module.exports = RectangleToRectangle }, function(module, exports) { var ContainsArray = function(triangle, points, returnFirst, out) { if (returnFirst === undefined) { returnFirst = false } if (out === undefined) { out = [] } var v0x = triangle.x3 - triangle.x1; var v0y = triangle.y3 - triangle.y1; var v1x = triangle.x2 - triangle.x1; var v1y = triangle.y2 - triangle.y1; var dot00 = v0x * v0x + v0y * v0y; var dot01 = v0x * v1x + v0y * v1y; var dot11 = v1x * v1x + v1y * v1y; var b = dot00 * dot11 - dot01 * dot01; var inv = b === 0 ? 0 : 1 / b; var u; var v; var v2x; var v2y; var dot02; var dot12; var x1 = triangle.x1; var y1 = triangle.y1; for (var i = 0; i < points.length; i++) { v2x = points[i].x - x1; v2y = points[i].y - y1; dot02 = v0x * v2x + v0y * v2y; dot12 = v1x * v2x + v1y * v2y; u = (dot11 * dot02 - dot01 * dot12) * inv; v = (dot00 * dot12 - dot01 * dot02) * inv; if (u >= 0 && v >= 0 && u + v < 1) { out.push({ x: points[i].x, y: points[i].y }); if (returnFirst) { break } } } return out }; module.exports = ContainsArray }, function(module, exports) { var RotateAroundXY = function(line, x, y, angle) { var c = Math.cos(angle); var s = Math.sin(angle); var tx = line.x1 - x; var ty = line.y1 - y; line.x1 = tx * c - ty * s + x; line.y1 = tx * s + ty * c + y; tx = line.x2 - x; ty = line.y2 - y; line.x2 = tx * c - ty * s + x; line.y2 = tx * s + ty * c + y; return line }; module.exports = RotateAroundXY }, function(module, exports) { var GetAspectRatio = function(rect) { return rect.height === 0 ? NaN : rect.width / rect.height }; module.exports = GetAspectRatio }, function(module, exports) { var RotateAroundXY = function(triangle, x, y, angle) { var c = Math.cos(angle); var s = Math.sin(angle); var tx = triangle.x1 - x; var ty = triangle.y1 - y; triangle.x1 = tx * c - ty * s + x; triangle.y1 = tx * s + ty * c + y; tx = triangle.x2 - x; ty = triangle.y2 - y; triangle.x2 = tx * c - ty * s + x; triangle.y2 = tx * s + ty * c + y; tx = triangle.x3 - x; ty = triangle.y3 - y; triangle.x3 = tx * c - ty * s + x; triangle.y3 = tx * s + ty * c + y; return triangle }; module.exports = RotateAroundXY }, function(module, exports) { var KeyCodes = { BACKSPACE: 8, TAB: 9, ENTER: 13, SHIFT: 16, CTRL: 17, ALT: 18, PAUSE: 19, CAPS_LOCK: 20, ESC: 27, SPACE: 32, PAGE_UP: 33, PAGE_DOWN: 34, END: 35, HOME: 36, LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40, PRINT_SCREEN: 42, INSERT: 45, DELETE: 46, ZERO: 48, ONE: 49, TWO: 50, THREE: 51, FOUR: 52, FIVE: 53, SIX: 54, SEVEN: 55, EIGHT: 56, NINE: 57, NUMPAD_ZERO: 96, NUMPAD_ONE: 97, NUMPAD_TWO: 98, NUMPAD_THREE: 99, NUMPAD_FOUR: 100, NUMPAD_FIVE: 101, NUMPAD_SIX: 102, NUMPAD_SEVEN: 103, NUMPAD_EIGHT: 104, NUMPAD_NINE: 105, 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, F1: 112, F2: 113, F3: 114, F4: 115, F5: 116, F6: 117, F7: 118, F8: 119, F9: 120, F10: 121, F11: 122, F12: 123, SEMICOLON: 186, PLUS: 187, COMMA: 188, MINUS: 189, PERIOD: 190, FORWARD_SLASH: 191, BACK_SLASH: 220, QUOTES: 222, BACKTICK: 192, OPEN_BRACKET: 219, CLOSED_BRACKET: 221 }; module.exports = KeyCodes }, function(module, exports) { var SnapFloor = function(value, gap, start, divide) { if (start === undefined) { start = 0 } if (gap === 0) { return value } value -= start; value = gap * Math.floor(value / gap); return divide ? (start + value) / gap : start + value }; module.exports = SnapFloor }, function(module, exports) { var GetURL = function(file, baseURL) { if (!file.url) { return false } if (file.url.match(/^(?:blob:|data:|http:\/\/|https:\/\/|\/\/)/)) { return file.url } else { return baseURL + file.url } }; module.exports = GetURL }, function(module, exports, __webpack_require__) { var Extend = __webpack_require__(19); var XHRSettings = __webpack_require__(129); var MergeXHRSettings = function(global, local) { var output = global === undefined ? XHRSettings() : Extend({}, global); if (local) { for (var setting in local) { if (local[setting] !== undefined) { output[setting] = local[setting] } } } return output }; module.exports = MergeXHRSettings }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var CONST = __webpack_require__(20); var File = __webpack_require__(22); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(1); var IsPlainObject = __webpack_require__(7); var ParseXML = __webpack_require__(300); var XMLFile = new Class({ Extends: File, initialize: function XMLFile(loader, key, url, xhrSettings) { var extension = "xml"; if (IsPlainObject(key)) { var config = key; key = GetFastValue(config, "key"); url = GetFastValue(config, "url"); xhrSettings = GetFastValue(config, "xhrSettings"); extension = GetFastValue(config, "extension", extension) } var fileConfig = { type: "xml", cache: loader.cacheManager.xml, extension: extension, responseType: "text", key: key, url: url, xhrSettings: xhrSettings }; File.call(this, loader, fileConfig) }, onProcess: function() { this.state = CONST.FILE_PROCESSING; this.data = ParseXML(this.xhrLoader.responseText); if (this.data) { this.onProcessComplete() } else { console.warn("Invalid XMLFile: " + this.key); this.onProcessError() } } }); FileTypesManager.register("xml", function(key, url, xhrSettings) { if (Array.isArray(key)) { for (var i = 0; i < key.length; i++) { this.addFile(new XMLFile(this, key[i])) } } else { this.addFile(new XMLFile(this, key, url, xhrSettings)) } return this }); module.exports = XMLFile }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var EPSILON = 1e-6; var Matrix4 = new Class({ initialize: function Matrix4(m) { this.val = new Float32Array(16); if (m) { this.copy(m) } else { this.identity() } }, clone: function() { return new Matrix4(this) }, set: function(src) { return this.copy(src) }, copy: function(src) { var out = this.val; var a = src.val; out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; out[3] = a[3]; out[4] = a[4]; out[5] = a[5]; out[6] = a[6]; out[7] = a[7]; out[8] = a[8]; out[9] = a[9]; out[10] = a[10]; out[11] = a[11]; out[12] = a[12]; out[13] = a[13]; out[14] = a[14]; out[15] = a[15]; return this }, fromArray: function(a) { var out = this.val; out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; out[3] = a[3]; out[4] = a[4]; out[5] = a[5]; out[6] = a[6]; out[7] = a[7]; out[8] = a[8]; out[9] = a[9]; out[10] = a[10]; out[11] = a[11]; out[12] = a[12]; out[13] = a[13]; out[14] = a[14]; out[15] = a[15]; return this }, zero: function() { var out = this.val; out[0] = 0; out[1] = 0; out[2] = 0; out[3] = 0; out[4] = 0; out[5] = 0; out[6] = 0; out[7] = 0; out[8] = 0; out[9] = 0; out[10] = 0; out[11] = 0; out[12] = 0; out[13] = 0; out[14] = 0; out[15] = 0; return this }, xyz: function(x, y, z) { this.identity(); var out = this.val; out[12] = x; out[13] = y; out[14] = z; return this }, scaling: function(x, y, z) { this.zero(); var out = this.val; out[0] = x; out[5] = y; out[10] = z; out[15] = 1; return this }, identity: function() { var out = this.val; out[0] = 1; out[1] = 0; out[2] = 0; out[3] = 0; out[4] = 0; out[5] = 1; out[6] = 0; out[7] = 0; out[8] = 0; out[9] = 0; out[10] = 1; out[11] = 0; out[12] = 0; out[13] = 0; out[14] = 0; out[15] = 1; return this }, transpose: function() { var a = this.val; var a01 = a[1]; var a02 = a[2]; var a03 = a[3]; var a12 = a[6]; var a13 = a[7]; var a23 = a[11]; a[1] = a[4]; a[2] = a[8]; a[3] = a[12]; a[4] = a01; a[6] = a[9]; a[7] = a[13]; a[8] = a02; a[9] = a12; a[11] = a[14]; a[12] = a03; a[13] = a13; a[14] = a23; return this }, invert: function() { var a = this.val; var a00 = a[0]; var a01 = a[1]; var a02 = a[2]; var a03 = a[3]; var a10 = a[4]; var a11 = a[5]; var a12 = a[6]; var a13 = a[7]; var a20 = a[8]; var a21 = a[9]; var a22 = a[10]; var a23 = a[11]; var a30 = a[12]; var a31 = a[13]; var a32 = a[14]; var a33 = a[15]; var b00 = a00 * a11 - a01 * a10; var b01 = a00 * a12 - a02 * a10; var b02 = a00 * a13 - a03 * a10; var b03 = a01 * a12 - a02 * a11; var b04 = a01 * a13 - a03 * a11; var b05 = a02 * a13 - a03 * a12; var b06 = a20 * a31 - a21 * a30; var b07 = a20 * a32 - a22 * a30; var b08 = a20 * a33 - a23 * a30; var b09 = a21 * a32 - a22 * a31; var b10 = a21 * a33 - a23 * a31; var b11 = a22 * a33 - a23 * a32; var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; if (!det) { return null } det = 1 / det; a[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; a[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det; a[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det; a[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det; a[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det; a[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det; a[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det; a[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det; a[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det; a[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det; a[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det; a[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det; a[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det; a[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det; a[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det; a[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det; return this }, adjoint: function() { var a = this.val; var a00 = a[0]; var a01 = a[1]; var a02 = a[2]; var a03 = a[3]; var a10 = a[4]; var a11 = a[5]; var a12 = a[6]; var a13 = a[7]; var a20 = a[8]; var a21 = a[9]; var a22 = a[10]; var a23 = a[11]; var a30 = a[12]; var a31 = a[13]; var a32 = a[14]; var a33 = a[15]; a[0] = a11 * (a22 * a33 - a23 * a32) - a21 * (a12 * a33 - a13 * a32) + a31 * (a12 * a23 - a13 * a22); a[1] = -(a01 * (a22 * a33 - a23 * a32) - a21 * (a02 * a33 - a03 * a32) + a31 * (a02 * a23 - a03 * a22)); a[2] = a01 * (a12 * a33 - a13 * a32) - a11 * (a02 * a33 - a03 * a32) + a31 * (a02 * a13 - a03 * a12); a[3] = -(a01 * (a12 * a23 - a13 * a22) - a11 * (a02 * a23 - a03 * a22) + a21 * (a02 * a13 - a03 * a12)); a[4] = -(a10 * (a22 * a33 - a23 * a32) - a20 * (a12 * a33 - a13 * a32) + a30 * (a12 * a23 - a13 * a22)); a[5] = a00 * (a22 * a33 - a23 * a32) - a20 * (a02 * a33 - a03 * a32) + a30 * (a02 * a23 - a03 * a22); a[6] = -(a00 * (a12 * a33 - a13 * a32) - a10 * (a02 * a33 - a03 * a32) + a30 * (a02 * a13 - a03 * a12)); a[7] = a00 * (a12 * a23 - a13 * a22) - a10 * (a02 * a23 - a03 * a22) + a20 * (a02 * a13 - a03 * a12); a[8] = a10 * (a21 * a33 - a23 * a31) - a20 * (a11 * a33 - a13 * a31) + a30 * (a11 * a23 - a13 * a21); a[9] = -(a00 * (a21 * a33 - a23 * a31) - a20 * (a01 * a33 - a03 * a31) + a30 * (a01 * a23 - a03 * a21)); a[10] = a00 * (a11 * a33 - a13 * a31) - a10 * (a01 * a33 - a03 * a31) + a30 * (a01 * a13 - a03 * a11); a[11] = -(a00 * (a11 * a23 - a13 * a21) - a10 * (a01 * a23 - a03 * a21) + a20 * (a01 * a13 - a03 * a11)); a[12] = -(a10 * (a21 * a32 - a22 * a31) - a20 * (a11 * a32 - a12 * a31) + a30 * (a11 * a22 - a12 * a21)); a[13] = a00 * (a21 * a32 - a22 * a31) - a20 * (a01 * a32 - a02 * a31) + a30 * (a01 * a22 - a02 * a21); a[14] = -(a00 * (a11 * a32 - a12 * a31) - a10 * (a01 * a32 - a02 * a31) + a30 * (a01 * a12 - a02 * a11)); a[15] = a00 * (a11 * a22 - a12 * a21) - a10 * (a01 * a22 - a02 * a21) + a20 * (a01 * a12 - a02 * a11); return this }, determinant: function() { var a = this.val; var a00 = a[0]; var a01 = a[1]; var a02 = a[2]; var a03 = a[3]; var a10 = a[4]; var a11 = a[5]; var a12 = a[6]; var a13 = a[7]; var a20 = a[8]; var a21 = a[9]; var a22 = a[10]; var a23 = a[11]; var a30 = a[12]; var a31 = a[13]; var a32 = a[14]; var a33 = a[15]; var b00 = a00 * a11 - a01 * a10; var b01 = a00 * a12 - a02 * a10; var b02 = a00 * a13 - a03 * a10; var b03 = a01 * a12 - a02 * a11; var b04 = a01 * a13 - a03 * a11; var b05 = a02 * a13 - a03 * a12; var b06 = a20 * a31 - a21 * a30; var b07 = a20 * a32 - a22 * a30; var b08 = a20 * a33 - a23 * a30; var b09 = a21 * a32 - a22 * a31; var b10 = a21 * a33 - a23 * a31; var b11 = a22 * a33 - a23 * a32; return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06 }, multiply: function(src) { var a = this.val; var a00 = a[0]; var a01 = a[1]; var a02 = a[2]; var a03 = a[3]; var a10 = a[4]; var a11 = a[5]; var a12 = a[6]; var a13 = a[7]; var a20 = a[8]; var a21 = a[9]; var a22 = a[10]; var a23 = a[11]; var a30 = a[12]; var a31 = a[13]; var a32 = a[14]; var a33 = a[15]; var b = src.val; var b0 = b[0]; var b1 = b[1]; var b2 = b[2]; var b3 = b[3]; a[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; a[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; a[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; a[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; b0 = b[4]; b1 = b[5]; b2 = b[6]; b3 = b[7]; a[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; a[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; a[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; a[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; b0 = b[8]; b1 = b[9]; b2 = b[10]; b3 = b[11]; a[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; a[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; a[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; a[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; b0 = b[12]; b1 = b[13]; b2 = b[14]; b3 = b[15]; a[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; a[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; a[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; a[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; return this }, multiplyLocal: function(src) { var a = []; var m1 = this.val; var m2 = src.val; a[0] = m1[0] * m2[0] + m1[1] * m2[4] + m1[2] * m2[8] + m1[3] * m2[12]; a[1] = m1[0] * m2[1] + m1[1] * m2[5] + m1[2] * m2[9] + m1[3] * m2[13]; a[2] = m1[0] * m2[2] + m1[1] * m2[6] + m1[2] * m2[10] + m1[3] * m2[14]; a[3] = m1[0] * m2[3] + m1[1] * m2[7] + m1[2] * m2[11] + m1[3] * m2[15]; a[4] = m1[4] * m2[0] + m1[5] * m2[4] + m1[6] * m2[8] + m1[7] * m2[12]; a[5] = m1[4] * m2[1] + m1[5] * m2[5] + m1[6] * m2[9] + m1[7] * m2[13]; a[6] = m1[4] * m2[2] + m1[5] * m2[6] + m1[6] * m2[10] + m1[7] * m2[14]; a[7] = m1[4] * m2[3] + m1[5] * m2[7] + m1[6] * m2[11] + m1[7] * m2[15]; a[8] = m1[8] * m2[0] + m1[9] * m2[4] + m1[10] * m2[8] + m1[11] * m2[12]; a[9] = m1[8] * m2[1] + m1[9] * m2[5] + m1[10] * m2[9] + m1[11] * m2[13]; a[10] = m1[8] * m2[2] + m1[9] * m2[6] + m1[10] * m2[10] + m1[11] * m2[14]; a[11] = m1[8] * m2[3] + m1[9] * m2[7] + m1[10] * m2[11] + m1[11] * m2[15]; a[12] = m1[12] * m2[0] + m1[13] * m2[4] + m1[14] * m2[8] + m1[15] * m2[12]; a[13] = m1[12] * m2[1] + m1[13] * m2[5] + m1[14] * m2[9] + m1[15] * m2[13]; a[14] = m1[12] * m2[2] + m1[13] * m2[6] + m1[14] * m2[10] + m1[15] * m2[14]; a[15] = m1[12] * m2[3] + m1[13] * m2[7] + m1[14] * m2[11] + m1[15] * m2[15]; return this.fromArray(a) }, translate: function(v) { var x = v.x; var y = v.y; var z = v.z; var a = this.val; a[12] = a[0] * x + a[4] * y + a[8] * z + a[12]; a[13] = a[1] * x + a[5] * y + a[9] * z + a[13]; a[14] = a[2] * x + a[6] * y + a[10] * z + a[14]; a[15] = a[3] * x + a[7] * y + a[11] * z + a[15]; return this }, scale: function(v) { var x = v.x; var y = v.y; var z = v.z; var a = this.val; a[0] = a[0] * x; a[1] = a[1] * x; a[2] = a[2] * x; a[3] = a[3] * x; a[4] = a[4] * y; a[5] = a[5] * y; a[6] = a[6] * y; a[7] = a[7] * y; a[8] = a[8] * z; a[9] = a[9] * z; a[10] = a[10] * z; a[11] = a[11] * z; return this }, makeRotationAxis: function(axis, angle) { var c = Math.cos(angle); var s = Math.sin(angle); var t = 1 - c; var x = axis.x; var y = axis.y; var z = axis.z; var tx = t * x; var ty = t * y; this.fromArray([tx * x + c, tx * y - s * z, tx * z + s * y, 0, tx * y + s * z, ty * y + c, ty * z - s * x, 0, tx * z - s * y, ty * z + s * x, t * z * z + c, 0, 0, 0, 0, 1]); return this }, rotate: function(rad, axis) { var a = this.val; var x = axis.x; var y = axis.y; var z = axis.z; 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; var s = Math.sin(rad); var c = Math.cos(rad); var t = 1 - c; var a00 = a[0]; var a01 = a[1]; var a02 = a[2]; var a03 = a[3]; var a10 = a[4]; var a11 = a[5]; var a12 = a[6]; var a13 = a[7]; var a20 = a[8]; var a21 = a[9]; var a22 = a[10]; var a23 = a[11]; var b00 = x * x * t + c; var b01 = y * x * t + z * s; var b02 = z * x * t - y * s; var b10 = x * y * t - z * s; var b11 = y * y * t + c; var b12 = z * y * t + x * s; var b20 = x * z * t + y * s; var b21 = y * z * t - x * s; var b22 = z * z * t + c; a[0] = a00 * b00 + a10 * b01 + a20 * b02; a[1] = a01 * b00 + a11 * b01 + a21 * b02; a[2] = a02 * b00 + a12 * b01 + a22 * b02; a[3] = a03 * b00 + a13 * b01 + a23 * b02; a[4] = a00 * b10 + a10 * b11 + a20 * b12; a[5] = a01 * b10 + a11 * b11 + a21 * b12; a[6] = a02 * b10 + a12 * b11 + a22 * b12; a[7] = a03 * b10 + a13 * b11 + a23 * b12; a[8] = a00 * b20 + a10 * b21 + a20 * b22; a[9] = a01 * b20 + a11 * b21 + a21 * b22; a[10] = a02 * b20 + a12 * b21 + a22 * b22; a[11] = a03 * b20 + a13 * b21 + a23 * b22; return this }, rotateX: function(rad) { var a = this.val; var s = Math.sin(rad); var c = Math.cos(rad); var a10 = a[4]; var a11 = a[5]; var a12 = a[6]; var a13 = a[7]; var a20 = a[8]; var a21 = a[9]; var a22 = a[10]; var a23 = a[11]; a[4] = a10 * c + a20 * s; a[5] = a11 * c + a21 * s; a[6] = a12 * c + a22 * s; a[7] = a13 * c + a23 * s; a[8] = a20 * c - a10 * s; a[9] = a21 * c - a11 * s; a[10] = a22 * c - a12 * s; a[11] = a23 * c - a13 * s; return this }, rotateY: function(rad) { var a = this.val; var s = Math.sin(rad); var c = Math.cos(rad); var a00 = a[0]; var a01 = a[1]; var a02 = a[2]; var a03 = a[3]; var a20 = a[8]; var a21 = a[9]; var a22 = a[10]; var a23 = a[11]; a[0] = a00 * c - a20 * s; a[1] = a01 * c - a21 * s; a[2] = a02 * c - a22 * s; a[3] = a03 * c - a23 * s; a[8] = a00 * s + a20 * c; a[9] = a01 * s + a21 * c; a[10] = a02 * s + a22 * c; a[11] = a03 * s + a23 * c; return this }, rotateZ: function(rad) { var a = this.val; var s = Math.sin(rad); var c = Math.cos(rad); var a00 = a[0]; var a01 = a[1]; var a02 = a[2]; var a03 = a[3]; var a10 = a[4]; var a11 = a[5]; var a12 = a[6]; var a13 = a[7]; a[0] = a00 * c + a10 * s; a[1] = a01 * c + a11 * s; a[2] = a02 * c + a12 * s; a[3] = a03 * c + a13 * s; a[4] = a10 * c - a00 * s; a[5] = a11 * c - a01 * s; a[6] = a12 * c - a02 * s; a[7] = a13 * c - a03 * s; return this }, fromRotationTranslation: function(q, v) { var out = this.val; var x = q.x; var y = q.y; var z = q.z; var 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[0] = 1 - (yy + zz); out[1] = xy + wz; out[2] = xz - wy; out[3] = 0; out[4] = xy - wz; out[5] = 1 - (xx + zz); out[6] = yz + wx; out[7] = 0; out[8] = xz + wy; out[9] = yz - wx; out[10] = 1 - (xx + yy); out[11] = 0; out[12] = v.x; out[13] = v.y; out[14] = v.z; out[15] = 1; return this }, fromQuat: function(q) { var out = this.val; var x = q.x; var y = q.y; var z = q.z; var 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[0] = 1 - (yy + zz); out[1] = xy + wz; out[2] = xz - wy; out[3] = 0; out[4] = xy - wz; out[5] = 1 - (xx + zz); out[6] = yz + wx; out[7] = 0; out[8] = xz + wy; out[9] = yz - wx; out[10] = 1 - (xx + yy); out[11] = 0; out[12] = 0; out[13] = 0; out[14] = 0; out[15] = 1; return this }, frustum: function(left, right, bottom, top, near, far) { var out = this.val; var rl = 1 / (right - left); var tb = 1 / (top - bottom); var nf = 1 / (near - far); out[0] = near * 2 * rl; out[1] = 0; out[2] = 0; out[3] = 0; out[4] = 0; out[5] = near * 2 * tb; out[6] = 0; out[7] = 0; out[8] = (right + left) * rl; out[9] = (top + bottom) * tb; out[10] = (far + near) * nf; out[11] = -1; out[12] = 0; out[13] = 0; out[14] = far * near * 2 * nf; out[15] = 0; return this }, perspective: function(fovy, aspect, near, far) { var out = this.val; var f = 1 / Math.tan(fovy / 2); var nf = 1 / (near - far); out[0] = f / aspect; out[1] = 0; out[2] = 0; out[3] = 0; out[4] = 0; out[5] = f; out[6] = 0; out[7] = 0; out[8] = 0; out[9] = 0; out[10] = (far + near) * nf; out[11] = -1; out[12] = 0; out[13] = 0; out[14] = 2 * far * near * nf; out[15] = 0; return this }, perspectiveLH: function(width, height, near, far) { var out = this.val; out[0] = 2 * near / width; out[1] = 0; out[2] = 0; out[3] = 0; out[4] = 0; out[5] = 2 * near / height; out[6] = 0; out[7] = 0; out[8] = 0; out[9] = 0; out[10] = -far / (near - far); out[11] = 1; out[12] = 0; out[13] = 0; out[14] = near * far / (near - far); out[15] = 0; return this }, ortho: function(left, right, bottom, top, near, far) { var out = this.val; var lr = left - right; var bt = bottom - top; var nf = near - far; lr = lr === 0 ? lr : 1 / lr; bt = bt === 0 ? bt : 1 / bt; nf = nf === 0 ? nf : 1 / nf; out[0] = -2 * lr; out[1] = 0; out[2] = 0; out[3] = 0; out[4] = 0; out[5] = -2 * bt; out[6] = 0; out[7] = 0; out[8] = 0; out[9] = 0; out[10] = 2 * nf; out[11] = 0; out[12] = (left + right) * lr; out[13] = (top + bottom) * bt; out[14] = (far + near) * nf; out[15] = 1; return this }, lookAt: function(eye, center, up) { var out = this.val; 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 this.identity() } var z0 = eyex - centerx; var z1 = eyey - centery; var z2 = eyez - centerz; var len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2); z0 *= len; z1 *= len; z2 *= len; var x0 = upy * z2 - upz * z1; var x1 = upz * z0 - upx * z2; var x2 = upx * z1 - upy * z0; len = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2); if (!len) { x0 = 0; x1 = 0; x2 = 0 } else { len = 1 / len; x0 *= len; x1 *= len; x2 *= len } var y0 = z1 * x2 - z2 * x1; var y1 = z2 * x0 - z0 * x2; var y2 = z0 * x1 - z1 * x0; len = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2); if (!len) { y0 = 0; y1 = 0; y2 = 0 } else { len = 1 / len; y0 *= len; y1 *= len; y2 *= len } out[0] = x0; out[1] = y0; out[2] = z0; out[3] = 0; out[4] = x1; out[5] = y1; out[6] = z1; out[7] = 0; out[8] = x2; out[9] = y2; out[10] = z2; out[11] = 0; out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez); out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez); out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez); out[15] = 1; return this }, yawPitchRoll: function(yaw, pitch, roll) { this.zero(); _tempMat1.zero(); _tempMat2.zero(); var m0 = this.val; var m1 = _tempMat1.val; var m2 = _tempMat2.val; var s = Math.sin(roll); var c = Math.cos(roll); m0[10] = 1; m0[15] = 1; m0[0] = c; m0[1] = s; m0[4] = -s; m0[5] = c; s = Math.sin(pitch); c = Math.cos(pitch); m1[0] = 1; m1[15] = 1; m1[5] = c; m1[10] = c; m1[9] = -s; m1[6] = s; s = Math.sin(yaw); c = Math.cos(yaw); m2[5] = 1; m2[15] = 1; m2[0] = c; m2[2] = -s; m2[8] = s; m2[10] = c; this.multiplyLocal(_tempMat1); this.multiplyLocal(_tempMat2); return this }, setWorldMatrix: function(rotation, position, scale, viewMatrix, projectionMatrix) { this.yawPitchRoll(rotation.y, rotation.x, rotation.z); _tempMat1.scaling(scale.x, scale.y, scale.z); _tempMat2.xyz(position.x, position.y, position.z); this.multiplyLocal(_tempMat1); this.multiplyLocal(_tempMat2); if (viewMatrix !== undefined) { this.multiplyLocal(viewMatrix) } if (projectionMatrix !== undefined) { this.multiplyLocal(projectionMatrix) } return this } }); var _tempMat1 = new Matrix4; var _tempMat2 = new Matrix4; module.exports = Matrix4 }, function(module, exports, __webpack_require__) { module.exports = { Acceleration: __webpack_require__(1038), BodyScale: __webpack_require__(1039), BodyType: __webpack_require__(1040), Bounce: __webpack_require__(1041), CheckAgainst: __webpack_require__(1042), Collides: __webpack_require__(1043), Debug: __webpack_require__(1044), Friction: __webpack_require__(1045), Gravity: __webpack_require__(1046), Offset: __webpack_require__(1047), SetGameObject: __webpack_require__(1048), Velocity: __webpack_require__(1049) } }, function(module, exports, __webpack_require__) { var Axes = {}; module.exports = Axes; var Vector = __webpack_require__(33); var Common = __webpack_require__(17); (function() { Axes.fromVertices = function(vertices) { var axes = {}; for (var i = 0; i < vertices.length; i++) { var j = (i + 1) % vertices.length, normal = Vector.normalise({ x: vertices[j].y - vertices[i].y, y: vertices[i].x - vertices[j].x }), gradient = normal.y === 0 ? Infinity : normal.x / normal.y; gradient = gradient.toFixed(3).toString(); axes[gradient] = normal } return Common.values(axes) }; Axes.rotate = function(axes, angle) { if (angle === 0) return; var cos = Math.cos(angle), sin = Math.sin(angle); for (var i = 0; i < axes.length; i++) { var axis = axes[i], xx; xx = axis.x * cos - axis.y * sin; axis.y = axis.x * sin + axis.y * cos; axis.x = xx } } })() }, function(module, exports, __webpack_require__) { var Bodies = __webpack_require__(58); var Body = __webpack_require__(25); var Class = __webpack_require__(0); var Components = __webpack_require__(131); var GetFastValue = __webpack_require__(1); var HasValue = __webpack_require__(83); var Vertices = __webpack_require__(32); var MatterTileBody = new Class({ Mixins: [Components.Bounce, Components.Collision, Components.Friction, Components.Gravity, Components.Mass, Components.Sensor, Components.Sleep, Components.Static], initialize: function MatterTileBody(world, tile, options) { this.tile = tile; this.world = world; if (tile.physics.matterBody) { tile.physics.matterBody.destroy() } tile.physics.matterBody = this; var body = GetFastValue(options, "body", null); var addToWorld = GetFastValue(options, "addToWorld", true); if (!body) { var collisionGroup = tile.getCollisionGroup(); var collisionObjects = GetFastValue(collisionGroup, "objects", []); if (collisionObjects.length > 0) { this.setFromTileCollision(options) } else { this.setFromTileRectangle(options) } } else { this.setBody(body, addToWorld) } }, setFromTileRectangle: function(options) { if (options === undefined) { options = {} } if (!HasValue(options, "isStatic")) { options.isStatic = true } if (!HasValue(options, "addToWorld")) { options.addToWorld = true } var bounds = this.tile.getBounds(); var cx = bounds.x + bounds.width / 2; var cy = bounds.y + bounds.height / 2; var body = Bodies.rectangle(cx, cy, bounds.width, bounds.height, options); this.setBody(body, options.addToWorld); return this }, setFromTileCollision: function(options) { if (options === undefined) { options = {} } if (!HasValue(options, "isStatic")) { options.isStatic = true } if (!HasValue(options, "addToWorld")) { options.addToWorld = true } var sx = this.tile.tilemapLayer.scaleX; var sy = this.tile.tilemapLayer.scaleY; var tileX = this.tile.getLeft(); var tileY = this.tile.getTop(); var collisionGroup = this.tile.getCollisionGroup(); var collisionObjects = GetFastValue(collisionGroup, "objects", []); var parts = []; for (var i = 0; i < collisionObjects.length; i++) { var object = collisionObjects[i]; var ox = tileX + object.x * sx; var oy = tileY + object.y * sy; var ow = object.width * sx; var oh = object.height * sy; var body = null; if (object.rectangle) { body = Bodies.rectangle(ox + ow / 2, oy + oh / 2, ow, oh, options) } else if (object.ellipse) { body = Bodies.circle(ox + ow / 2, oy + oh / 2, ow / 2, options) } else if (object.polygon || object.polyline) { var originalPoints = object.polygon ? object.polygon : object.polyline; var points = originalPoints.map(function(p) { return { x: p.x * sx, y: p.y * sy } }); var vertices = Vertices.create(points); if (Vertices.isConvex(points)) { var center = Vertices.centre(vertices); ox += center.x; oy += center.y } body = Bodies.fromVertices(ox, oy, vertices, options) } if (body) { parts.push(body) } } if (parts.length === 1) { this.setBody(parts[0], options.addToWorld) } else if (parts.length > 1) { options.parts = parts; this.setBody(Body.create(options), options.addToWorld) } return this }, setBody: function(body, addToWorld) { if (addToWorld === undefined) { addToWorld = true } if (this.body) { this.removeBody() } this.body = body; this.body.gameObject = this; if (addToWorld) { this.world.add(this.body) } return this }, removeBody: function() { if (this.body) { this.world.remove(this.body); this.body.gameObject = undefined; this.body = undefined } return this }, destroy: function() { this.removeBody(); this.tile.physics.matterBody = undefined } }); module.exports = MatterTileBody }, function(module, exports, __webpack_require__) { var Detector = {}; module.exports = Detector; var SAT = __webpack_require__(207); var Pair = __webpack_require__(132); var Bounds = __webpack_require__(34); (function() { Detector.collisions = function(broadphasePairs, engine) { var collisions = [], pairsTable = engine.pairs.table; var metrics = engine.metrics; for (var i = 0; i < broadphasePairs.length; i++) { var bodyA = broadphasePairs[i][0], bodyB = broadphasePairs[i][1]; if ((bodyA.isStatic || bodyA.isSleeping) && (bodyB.isStatic || bodyB.isSleeping)) continue; if (!Detector.canCollide(bodyA.collisionFilter, bodyB.collisionFilter)) continue; metrics.midphaseTests += 1; if (Bounds.overlaps(bodyA.bounds, bodyB.bounds)) { for (var j = bodyA.parts.length > 1 ? 1 : 0; j < bodyA.parts.length; j++) { var partA = bodyA.parts[j]; for (var k = bodyB.parts.length > 1 ? 1 : 0; k < bodyB.parts.length; k++) { var partB = bodyB.parts[k]; if (partA === bodyA && partB === bodyB || Bounds.overlaps(partA.bounds, partB.bounds)) { var pairId = Pair.id(partA, partB), pair = pairsTable[pairId], previousCollision; if (pair && pair.isActive) { previousCollision = pair.collision } else { previousCollision = null } var collision = SAT.collides(partA, partB, previousCollision); metrics.narrowphaseTests += 1; if (collision.reused) metrics.narrowReuseCount += 1; if (collision.collided) { collisions.push(collision); metrics.narrowDetections += 1 } } } } } } return collisions }; Detector.canCollide = function(filterA, filterB) { if (filterA.group === filterB.group && filterA.group !== 0) return filterA.group > 0; return (filterA.mask & filterB.category) !== 0 && (filterB.mask & filterA.category) !== 0 } })() }, function(module, exports, __webpack_require__) { var SAT = {}; module.exports = SAT; var Vertices = __webpack_require__(32); var Vector = __webpack_require__(33); (function() { SAT.collides = function(bodyA, bodyB, previousCollision) { var overlapAB, overlapBA, minOverlap, collision, canReusePrevCol = false; if (previousCollision) { var parentA = bodyA.parent, parentB = bodyB.parent, motion = parentA.speed * parentA.speed + parentA.angularSpeed * parentA.angularSpeed + parentB.speed * parentB.speed + parentB.angularSpeed * parentB.angularSpeed; canReusePrevCol = previousCollision && previousCollision.collided && motion < .2; collision = previousCollision } else { collision = { collided: false, bodyA: bodyA, bodyB: bodyB } } if (previousCollision && canReusePrevCol) { var axisBodyA = collision.axisBody, axisBodyB = axisBodyA === bodyA ? bodyB : bodyA, axes = [axisBodyA.axes[previousCollision.axisNumber]]; minOverlap = SAT._overlapAxes(axisBodyA.vertices, axisBodyB.vertices, axes); collision.reused = true; if (minOverlap.overlap <= 0) { collision.collided = false; return collision } } else { overlapAB = SAT._overlapAxes(bodyA.vertices, bodyB.vertices, bodyA.axes); if (overlapAB.overlap <= 0) { collision.collided = false; return collision } overlapBA = SAT._overlapAxes(bodyB.vertices, bodyA.vertices, bodyB.axes); if (overlapBA.overlap <= 0) { collision.collided = false; return collision } if (overlapAB.overlap < overlapBA.overlap) { minOverlap = overlapAB; collision.axisBody = bodyA } else { minOverlap = overlapBA; collision.axisBody = bodyB } collision.axisNumber = minOverlap.axisNumber } collision.bodyA = bodyA.id < bodyB.id ? bodyA : bodyB; collision.bodyB = bodyA.id < bodyB.id ? bodyB : bodyA; collision.collided = true; collision.depth = minOverlap.overlap; collision.parentA = collision.bodyA.parent; collision.parentB = collision.bodyB.parent; bodyA = collision.bodyA; bodyB = collision.bodyB; if (Vector.dot(minOverlap.axis, Vector.sub(bodyB.position, bodyA.position)) < 0) { collision.normal = { x: minOverlap.axis.x, y: minOverlap.axis.y } } else { collision.normal = { x: -minOverlap.axis.x, y: -minOverlap.axis.y } } collision.tangent = Vector.perp(collision.normal); collision.penetration = collision.penetration || {}; collision.penetration.x = collision.normal.x * collision.depth; collision.penetration.y = collision.normal.y * collision.depth; var verticesB = SAT._findSupports(bodyA, bodyB, collision.normal), supports = []; if (Vertices.contains(bodyA.vertices, verticesB[0])) supports.push(verticesB[0]); if (Vertices.contains(bodyA.vertices, verticesB[1])) supports.push(verticesB[1]); if (supports.length < 2) { var verticesA = SAT._findSupports(bodyB, bodyA, Vector.neg(collision.normal)); if (Vertices.contains(bodyB.vertices, verticesA[0])) supports.push(verticesA[0]); if (supports.length < 2 && Vertices.contains(bodyB.vertices, verticesA[1])) supports.push(verticesA[1]) } if (supports.length < 1) supports = [verticesB[0]]; collision.supports = supports; return collision }; SAT._overlapAxes = function(verticesA, verticesB, axes) { var projectionA = Vector._temp[0], projectionB = Vector._temp[1], result = { overlap: Number.MAX_VALUE }, overlap, axis; for (var i = 0; i < axes.length; i++) { axis = axes[i]; SAT._projectToAxis(projectionA, verticesA, axis); SAT._projectToAxis(projectionB, verticesB, axis); overlap = Math.min(projectionA.max - projectionB.min, projectionB.max - projectionA.min); if (overlap <= 0) { result.overlap = overlap; return result } if (overlap < result.overlap) { result.overlap = overlap; result.axis = axis; result.axisNumber = i } } return result }; SAT._projectToAxis = function(projection, vertices, axis) { var min = Vector.dot(vertices[0], axis), max = min; for (var i = 1; i < vertices.length; i += 1) { var dot = Vector.dot(vertices[i], axis); if (dot > max) { max = dot } else if (dot < min) { min = dot } } projection.min = min; projection.max = max }; SAT._findSupports = function(bodyA, bodyB, normal) { var nearestDistance = Number.MAX_VALUE, vertexToBody = Vector._temp[0], vertices = bodyB.vertices, bodyAPosition = bodyA.position, distance, vertex, vertexA, vertexB; for (var i = 0; i < vertices.length; i++) { vertex = vertices[i]; vertexToBody.x = vertex.x - bodyAPosition.x; vertexToBody.y = vertex.y - bodyAPosition.y; distance = -Vector.dot(normal, vertexToBody); if (distance < nearestDistance) { nearestDistance = distance; vertexA = vertex } } var prevIndex = vertexA.index - 1 >= 0 ? vertexA.index - 1 : vertices.length - 1; vertex = vertices[prevIndex]; vertexToBody.x = vertex.x - bodyAPosition.x; vertexToBody.y = vertex.y - bodyAPosition.y; nearestDistance = -Vector.dot(normal, vertexToBody); vertexB = vertex; var nextIndex = (vertexA.index + 1) % vertices.length; vertex = vertices[nextIndex]; vertexToBody.x = vertex.x - bodyAPosition.x; vertexToBody.y = vertex.y - bodyAPosition.y; distance = -Vector.dot(normal, vertexToBody); if (distance < nearestDistance) { vertexB = vertex } return [vertexA, vertexB] } })() }, function(module, exports, __webpack_require__) { var Matter = __webpack_require__(441); Matter.Body = __webpack_require__(25); Matter.Composite = __webpack_require__(70); Matter.World = __webpack_require__(210); Matter.Detector = __webpack_require__(206); Matter.Grid = __webpack_require__(442); Matter.Pairs = __webpack_require__(443); Matter.Pair = __webpack_require__(132); Matter.Query = __webpack_require__(1070); Matter.Resolver = __webpack_require__(444); Matter.SAT = __webpack_require__(207); Matter.Constraint = __webpack_require__(88); Matter.Common = __webpack_require__(17); Matter.Engine = __webpack_require__(445); Matter.Events = __webpack_require__(87); Matter.Sleeping = __webpack_require__(103); Matter.Plugin = __webpack_require__(209); Matter.Bodies = __webpack_require__(58); Matter.Composites = __webpack_require__(438); Matter.Axes = __webpack_require__(204); Matter.Bounds = __webpack_require__(34); Matter.Svg = __webpack_require__(1072); Matter.Vector = __webpack_require__(33); Matter.Vertices = __webpack_require__(32); Matter.World.add = Matter.Composite.add; Matter.World.remove = Matter.Composite.remove; Matter.World.addComposite = Matter.Composite.addComposite; Matter.World.addBody = Matter.Composite.addBody; Matter.World.addConstraint = Matter.Composite.addConstraint; Matter.World.clear = Matter.Composite.clear; module.exports = Matter }, function(module, exports, __webpack_require__) { var Plugin = {}; module.exports = Plugin; var Common = __webpack_require__(17); (function() { Plugin._registry = {}; Plugin.register = function(plugin) { if (!Plugin.isPlugin(plugin)) { Common.warn("Plugin.register:", Plugin.toString(plugin), "does not implement all required fields.") } if (plugin.name in Plugin._registry) { var registered = Plugin._registry[plugin.name], pluginVersion = Plugin.versionParse(plugin.version).number, registeredVersion = Plugin.versionParse(registered.version).number; if (pluginVersion > registeredVersion) { Common.warn("Plugin.register:", Plugin.toString(registered), "was upgraded to", Plugin.toString(plugin)); Plugin._registry[plugin.name] = plugin } else if (pluginVersion < registeredVersion) { Common.warn("Plugin.register:", Plugin.toString(registered), "can not be downgraded to", Plugin.toString(plugin)) } else if (plugin !== registered) { Common.warn("Plugin.register:", Plugin.toString(plugin), "is already registered to different plugin object") } } else { Plugin._registry[plugin.name] = plugin } return plugin }; Plugin.resolve = function(dependency) { return Plugin._registry[Plugin.dependencyParse(dependency).name] }; Plugin.toString = function(plugin) { return typeof plugin === "string" ? plugin : (plugin.name || "anonymous") + "@" + (plugin.version || plugin.range || "0.0.0") }; Plugin.isPlugin = function(obj) { return obj && obj.name && obj.version && obj.install }; Plugin.isUsed = function(module, name) { return module.used.indexOf(name) > -1 }; Plugin.isFor = function(plugin, module) { var parsed = plugin.for && Plugin.dependencyParse(plugin.for); return !plugin.for || module.name === parsed.name && Plugin.versionSatisfies(module.version, parsed.range) }; Plugin.use = function(module, plugins) { module.uses = (module.uses || []).concat(plugins || []); if (module.uses.length === 0) { Common.warn("Plugin.use:", Plugin.toString(module), "does not specify any dependencies to install."); return } var dependencies = Plugin.dependencies(module), sortedDependencies = Common.topologicalSort(dependencies), status = []; for (var i = 0; i < sortedDependencies.length; i += 1) { if (sortedDependencies[i] === module.name) { continue } var plugin = Plugin.resolve(sortedDependencies[i]); if (!plugin) { status.push("❌ " + sortedDependencies[i]); continue } if (Plugin.isUsed(module, plugin.name)) { continue } if (!Plugin.isFor(plugin, module)) { Common.warn("Plugin.use:", Plugin.toString(plugin), "is for", plugin.for, "but installed on", Plugin.toString(module) + "."); plugin._warned = true } if (plugin.install) { plugin.install(module) } else { Common.warn("Plugin.use:", Plugin.toString(plugin), "does not specify an install function."); plugin._warned = true } if (plugin._warned) { status.push("🔶 " + Plugin.toString(plugin)); delete plugin._warned } else { status.push("✅ " + Plugin.toString(plugin)) } module.used.push(plugin.name) } if (status.length > 0 && !plugin.silent) { Common.info(status.join(" ")) } }; Plugin.dependencies = function(module, tracked) { var parsedBase = Plugin.dependencyParse(module), name = parsedBase.name; tracked = tracked || {}; if (name in tracked) { return } module = Plugin.resolve(module) || module; tracked[name] = Common.map(module.uses || [], function(dependency) { if (Plugin.isPlugin(dependency)) { Plugin.register(dependency) } var parsed = Plugin.dependencyParse(dependency), resolved = Plugin.resolve(dependency); if (resolved && !Plugin.versionSatisfies(resolved.version, parsed.range)) { Common.warn("Plugin.dependencies:", Plugin.toString(resolved), "does not satisfy", Plugin.toString(parsed), "used by", Plugin.toString(parsedBase) + "."); resolved._warned = true; module._warned = true } else if (!resolved) { Common.warn("Plugin.dependencies:", Plugin.toString(dependency), "used by", Plugin.toString(parsedBase), "could not be resolved."); module._warned = true } return parsed.name }); for (var i = 0; i < tracked[name].length; i += 1) { Plugin.dependencies(tracked[name][i], tracked) } return tracked }; Plugin.dependencyParse = function(dependency) { if (Common.isString(dependency)) { var pattern = /^[\w-]+(@(\*|[\^~]?\d+\.\d+\.\d+(-[0-9A-Za-z-]+)?))?$/; if (!pattern.test(dependency)) { Common.warn("Plugin.dependencyParse:", dependency, "is not a valid dependency string.") } return { name: dependency.split("@")[0], range: dependency.split("@")[1] || "*" } } return { name: dependency.name, range: dependency.range || dependency.version } }; Plugin.versionParse = function(range) { var pattern = /^\*|[\^~]?\d+\.\d+\.\d+(-[0-9A-Za-z-]+)?$/; if (!pattern.test(range)) { Common.warn("Plugin.versionParse:", range, "is not a valid version or range.") } var identifiers = range.split("-"); range = identifiers[0]; var isRange = isNaN(Number(range[0])), version = isRange ? range.substr(1) : range, parts = Common.map(version.split("."), function(part) { return Number(part) }); return { isRange: isRange, version: version, range: range, operator: isRange ? range[0] : "", parts: parts, prerelease: identifiers[1], number: parts[0] * 1e8 + parts[1] * 1e4 + parts[2] } }; Plugin.versionSatisfies = function(version, range) { range = range || "*"; var rangeParsed = Plugin.versionParse(range), rangeParts = rangeParsed.parts, versionParsed = Plugin.versionParse(version), versionParts = versionParsed.parts; if (rangeParsed.isRange) { if (rangeParsed.operator === "*" || version === "*") { return true } if (rangeParsed.operator === "~") { return versionParts[0] === rangeParts[0] && versionParts[1] === rangeParts[1] && versionParts[2] >= rangeParts[2] } if (rangeParsed.operator === "^") { if (rangeParts[0] > 0) { return versionParts[0] === rangeParts[0] && versionParsed.number >= rangeParsed.number } if (rangeParts[1] > 0) { return versionParts[1] === rangeParts[1] && versionParts[2] >= rangeParts[2] } return versionParts[2] === rangeParts[2] } } return version === range || version === "*" } })() }, function(module, exports, __webpack_require__) { var World = {}; module.exports = World; var Composite = __webpack_require__(70); var Constraint = __webpack_require__(88); var Common = __webpack_require__(17); (function() { World.create = function(options) { var composite = Composite.create(); var defaults = { label: "World", gravity: { x: 0, y: 1, scale: .001 }, bounds: { min: { x: -Infinity, y: -Infinity }, max: { x: Infinity, y: Infinity } } }; return Common.extend(composite, defaults, options) } })() }, function(module, exports, __webpack_require__) { var GetTileAt = __webpack_require__(134); var CalculateFacesAt = function(tileX, tileY, layer) { var tile = GetTileAt(tileX, tileY, true, layer); var above = GetTileAt(tileX, tileY - 1, true, layer); var below = GetTileAt(tileX, tileY + 1, true, layer); var left = GetTileAt(tileX - 1, tileY, true, layer); var right = GetTileAt(tileX + 1, tileY, true, layer); var tileCollides = tile && tile.collides; if (tileCollides) { tile.faceTop = true; tile.faceBottom = true; tile.faceLeft = true; tile.faceRight = true } if (above && above.collides) { if (tileCollides) { tile.faceTop = false } above.faceBottom = !tileCollides } if (below && below.collides) { if (tileCollides) { tile.faceBottom = false } below.faceTop = !tileCollides } if (left && left.collides) { if (tileCollides) { tile.faceLeft = false } left.faceRight = !tileCollides } if (right && right.collides) { if (tileCollides) { tile.faceRight = false } right.faceLeft = !tileCollides } if (tile && !tile.collides) { tile.resetFaces() } return tile }; module.exports = CalculateFacesAt }, function(module, exports, __webpack_require__) { var Tile = __webpack_require__(72); var IsInLayerBounds = __webpack_require__(104); var CalculateFacesAt = __webpack_require__(211); var SetTileCollision = __webpack_require__(71); var PutTileAt = function(tile, tileX, tileY, recalculateFaces, layer) { if (!IsInLayerBounds(tileX, tileY, layer)) { return null } if (recalculateFaces === undefined) { recalculateFaces = true } var oldTile = layer.data[tileY][tileX]; var oldTileCollides = oldTile && oldTile.collides; if (tile instanceof Tile) { if (layer.data[tileY][tileX] === null) { layer.data[tileY][tileX] = new Tile(layer, tile.index, tileX, tileY, tile.width, tile.height) } layer.data[tileY][tileX].copy(tile) } else { var index = tile; if (layer.data[tileY][tileX] === null) { layer.data[tileY][tileX] = new Tile(layer, index, tileX, tileY, layer.tileWidth, layer.tileHeight) } else { layer.data[tileY][tileX].index = index } } var newTile = layer.data[tileY][tileX]; var collides = layer.collideIndexes.indexOf(newTile.index) !== -1; SetTileCollision(newTile, collides); if (recalculateFaces && oldTileCollides !== newTile.collides) { CalculateFacesAt(tileX, tileY, layer) } return newTile }; module.exports = PutTileAt }, function(module, exports) { var SetLayerCollisionIndex = function(tileIndex, collides, layer) { var loc = layer.collideIndexes.indexOf(tileIndex); if (collides && loc === -1) { layer.collideIndexes.push(tileIndex) } else if (!collides && loc !== -1) { layer.collideIndexes.splice(loc, 1) } }; module.exports = SetLayerCollisionIndex }, function(module, exports, __webpack_require__) { var Formats = __webpack_require__(31); var LayerData = __webpack_require__(105); var MapData = __webpack_require__(106); var Tile = __webpack_require__(72); var Parse2DArray = function(name, data, tileWidth, tileHeight, insertNull) { var layerData = new LayerData({ tileWidth: tileWidth, tileHeight: tileHeight }); var mapData = new MapData({ name: name, tileWidth: tileWidth, tileHeight: tileHeight, format: Formats.ARRAY_2D, layers: [layerData] }); var tiles = []; var height = data.length; var width = 0; for (var y = 0; y < data.length; y++) { tiles[y] = []; var row = data[y]; for (var x = 0; x < row.length; x++) { var tileIndex = parseInt(row[x], 10); if (isNaN(tileIndex) || tileIndex === -1) { tiles[y][x] = insertNull ? null : new Tile(layerData, -1, x, y, tileWidth, tileHeight) } else { tiles[y][x] = new Tile(layerData, tileIndex, x, y, tileWidth, tileHeight) } } if (width === 0) { width = row.length } } mapData.width = layerData.width = width; mapData.height = layerData.height = height; mapData.widthInPixels = layerData.widthInPixels = width * tileWidth; mapData.heightInPixels = layerData.heightInPixels = height * tileHeight; layerData.data = tiles; return mapData }; module.exports = Parse2DArray }, function(module, exports, __webpack_require__) { var Formats = __webpack_require__(31); var MapData = __webpack_require__(106); var Parse = __webpack_require__(451); var Tilemap = __webpack_require__(459); var ParseToTilemap = function(scene, key, tileWidth, tileHeight, width, height, data, insertNull) { if (tileWidth === undefined) { tileWidth = 32 } if (tileHeight === undefined) { tileHeight = 32 } if (width === undefined) { width = 10 } if (height === undefined) { height = 10 } if (insertNull === undefined) { insertNull = false } var mapData = null; if (Array.isArray(data)) { var name = key !== undefined ? key : "map"; mapData = Parse(name, Formats.ARRAY_2D, data, tileWidth, tileHeight, insertNull) } else if (key !== undefined) { var tilemapData = scene.cache.tilemap.get(key); if (!tilemapData) { console.warn("No map data found for key " + key) } else { mapData = Parse(key, tilemapData.format, tilemapData.data, tileWidth, tileHeight, insertNull) } } if (mapData === null) { mapData = new MapData({ tileWidth: tileWidth, tileHeight: tileHeight, width: width, height: height }) } return new Tilemap(scene, mapData) }; module.exports = ParseToTilemap }, function(module, exports, __webpack_require__) { var GetValue = __webpack_require__(4); var GetTargets = function(config) { var targets = GetValue(config, "targets", null); if (targets === null) { return targets } if (typeof targets === "function") { targets = targets.call() } if (!Array.isArray(targets)) { targets = [targets] } return targets }; module.exports = GetTargets }, function(module, exports) { function hasGetStart(def) { return !!def.getStart && typeof def.getStart === "function" } function hasGetEnd(def) { return !!def.getEnd && typeof def.getEnd === "function" } function hasGetters(def) { return hasGetStart(def) || hasGetEnd(def) } var GetValueOp = function(key, propertyValue) { var callbacks; var getEnd = function(target, key, value) { return value }; var getStart = function(target, key, value) { return value }; var t = typeof propertyValue; if (t === "number") { getEnd = function() { return propertyValue } } else if (t === "string") { var op = propertyValue[0]; var num = parseFloat(propertyValue.substr(2)); switch (op) { case "+": getEnd = function(target, key, value) { return value + num }; break; case "-": getEnd = function(target, key, value) { return value - num }; break; case "*": getEnd = function(target, key, value) { return value * num }; break; case "/": getEnd = function(target, key, value) { return value / num }; break; default: getEnd = function() { return parseFloat(propertyValue) } } } else if (t === "function") { getEnd = propertyValue } else if (t === "object" && hasGetters(propertyValue)) { if (hasGetEnd(propertyValue)) { getEnd = propertyValue.getEnd } if (hasGetStart(propertyValue)) { getStart = propertyValue.getStart } } else if (propertyValue.hasOwnProperty("value")) { callbacks = GetValueOp(key, propertyValue.value) } if (!callbacks) { callbacks = { getEnd: getEnd, getStart: getStart } } return callbacks }; module.exports = GetValueOp }, function(module, exports) { var TWEEN_DEFAULTS = { targets: null, delay: 0, duration: 1e3, ease: "Power0", easeParams: null, hold: 0, repeat: 0, repeatDelay: 0, yoyo: false, flipX: false, flipY: false }; module.exports = TWEEN_DEFAULTS }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var GameObjectCreator = __webpack_require__(16); var GameObjectFactory = __webpack_require__(5); var TWEEN_CONST = __webpack_require__(99); var Tween = new Class({ initialize: function Tween(parent, data, targets) { this.parent = parent; this.parentIsTimeline = parent.hasOwnProperty("isTimeline"); this.data = data; this.totalData = data.length; this.targets = targets; this.totalTargets = targets.length; this.useFrames = false; this.timeScale = 1; this.loop = 0; this.loopDelay = 0; this.loopCounter = 0; this.completeDelay = 0; this.countdown = 0; this.offset = 0; this.calculatedOffset = 0; this.state = TWEEN_CONST.PENDING_ADD; this._pausedState = TWEEN_CONST.PENDING_ADD; this.paused = false; this.elapsed = 0; this.totalElapsed = 0; this.duration = 0; this.progress = 0; this.totalDuration = 0; this.totalProgress = 0; this.callbacks = { onComplete: null, onLoop: null, onRepeat: null, onStart: null, onUpdate: null, onYoyo: null }; this.callbackScope }, getValue: function() { return this.data[0].current }, setTimeScale: function(value) { this.timeScale = value; return this }, getTimeScale: function() { return this.timeScale }, isPlaying: function() { return this.state === TWEEN_CONST.ACTIVE }, isPaused: function() { return this.state === TWEEN_CONST.PAUSED }, hasTarget: function(target) { return this.targets.indexOf(target) !== -1 }, updateTo: function(key, value, startToCurrent) { for (var i = 0; i < this.totalData; i++) { var tweenData = this.data[i]; if (tweenData.key === key) { tweenData.end = value; if (startToCurrent) { tweenData.start = tweenData.current } break } } return this }, restart: function() { if (this.state === TWEEN_CONST.REMOVED) { this.seek(0); this.parent.makeActive(this) } else { this.stop(); this.play() } }, calcDuration: function() { var max = 0; var data = this.data; for (var i = 0; i < this.totalData; i++) { var tweenData = data[i]; tweenData.t1 = tweenData.duration + tweenData.hold; if (tweenData.yoyo) { tweenData.t1 += tweenData.duration } tweenData.t2 = tweenData.t1 + tweenData.repeatDelay; tweenData.totalDuration = tweenData.delay + tweenData.t1; if (tweenData.repeat === -1) { tweenData.totalDuration += tweenData.t2 * 999999999999 } else if (tweenData.repeat > 0) { tweenData.totalDuration += tweenData.t2 * tweenData.repeat } if (tweenData.totalDuration > max) { max = tweenData.totalDuration } } this.duration = max; this.loopCounter = this.loop === -1 ? 999999999999 : this.loop; if (this.loopCounter > 0) { this.totalDuration = this.duration + this.completeDelay + (this.duration + this.loopDelay) * this.loopCounter } else { this.totalDuration = this.duration + this.completeDelay } }, init: function() { var data = this.data; var totalTargets = this.totalTargets; for (var i = 0; i < this.totalData; i++) { var tweenData = data[i]; var target = tweenData.target; var gen = tweenData.gen; tweenData.delay = gen.delay(i, totalTargets, target); tweenData.duration = gen.duration(i, totalTargets, target); tweenData.hold = gen.hold(i, totalTargets, target); tweenData.repeat = gen.repeat(i, totalTargets, target); tweenData.repeatDelay = gen.repeatDelay(i, totalTargets, target) } this.calcDuration(); this.progress = 0; this.totalProgress = 0; this.elapsed = 0; this.totalElapsed = 0; if (this.paused && !this.parentIsTimeline) { this.state = TWEEN_CONST.PENDING_ADD; this._pausedState = TWEEN_CONST.INIT; return false } else { this.state = TWEEN_CONST.INIT; return true } }, nextState: function() { if (this.loopCounter > 0) { this.elapsed = 0; this.progress = 0; this.loopCounter--; var onLoop = this.callbacks.onLoop; if (onLoop) { onLoop.params[1] = this.targets; onLoop.func.apply(onLoop.scope, onLoop.params) } this.resetTweenData(true); if (this.loopDelay > 0) { this.countdown = this.loopDelay; this.state = TWEEN_CONST.LOOP_DELAY } else { this.state = TWEEN_CONST.ACTIVE } } else if (this.completeDelay > 0) { this.countdown = this.completeDelay; this.state = TWEEN_CONST.COMPLETE_DELAY } else { var onComplete = this.callbacks.onComplete; if (onComplete) { onComplete.params[1] = this.targets; onComplete.func.apply(onComplete.scope, onComplete.params) } this.state = TWEEN_CONST.PENDING_REMOVE } }, pause: function() { if (this.state === TWEEN_CONST.PAUSED) { return } this.paused = true; this._pausedState = this.state; this.state = TWEEN_CONST.PAUSED; return this }, play: function(resetFromTimeline) { if (this.state === TWEEN_CONST.ACTIVE) { return } else if (this.state === TWEEN_CONST.PENDING_REMOVE || this.state === TWEEN_CONST.REMOVED) { this.init(); this.parent.makeActive(this); resetFromTimeline = true } var onStart = this.callbacks.onStart; if (this.parentIsTimeline) { this.resetTweenData(resetFromTimeline); if (this.calculatedOffset === 0) { if (onStart) { onStart.params[1] = this.targets; onStart.func.apply(onStart.scope, onStart.params) } this.state = TWEEN_CONST.ACTIVE } else { this.countdown = this.calculatedOffset; this.state = TWEEN_CONST.OFFSET_DELAY } } else if (this.paused) { this.paused = false; this.parent.makeActive(this) } else { this.resetTweenData(resetFromTimeline); this.state = TWEEN_CONST.ACTIVE; if (onStart) { onStart.params[1] = this.targets; onStart.func.apply(onStart.scope, onStart.params) } this.parent.makeActive(this) } }, resetTweenData: function(resetFromLoop) { var data = this.data; for (var i = 0; i < this.totalData; i++) { var tweenData = data[i]; tweenData.progress = 0; tweenData.elapsed = 0; tweenData.repeatCounter = tweenData.repeat === -1 ? 999999999999 : tweenData.repeat; if (resetFromLoop) { tweenData.start = tweenData.getStartValue(tweenData.target, tweenData.key, tweenData.start); tweenData.end = tweenData.getEndValue(tweenData.target, tweenData.key, tweenData.end); tweenData.current = tweenData.start; tweenData.state = TWEEN_CONST.PLAYING_FORWARD } else if (tweenData.delay > 0) { tweenData.elapsed = tweenData.delay; tweenData.state = TWEEN_CONST.DELAY } else { tweenData.state = TWEEN_CONST.PENDING_RENDER } } }, resume: function() { if (this.state === TWEEN_CONST.PAUSED) { this.paused = false; this.state = this._pausedState } else { this.play() } return this }, seek: function(toPosition) { var data = this.data; for (var i = 0; i < this.totalData; i++) { var ms = this.totalDuration * toPosition; var tweenData = data[i]; var progress = 0; var elapsed = 0; if (ms <= tweenData.delay) { progress = 0; elapsed = 0 } else if (ms >= tweenData.totalDuration) { progress = 1; elapsed = tweenData.duration } else if (ms > tweenData.delay && ms <= tweenData.t1) { ms = Math.max(0, ms - tweenData.delay); progress = ms / tweenData.t1; elapsed = tweenData.duration * progress } else if (ms > tweenData.t1 && ms < tweenData.totalDuration) { ms -= tweenData.delay; ms -= tweenData.t1; ms = ms / tweenData.t2 % 1 * tweenData.t2; if (ms > tweenData.repeatDelay) { progress = ms / tweenData.t1; elapsed = tweenData.duration * progress } } tweenData.progress = progress; tweenData.elapsed = elapsed; var v = tweenData.ease(tweenData.progress); tweenData.current = tweenData.start + (tweenData.end - tweenData.start) * v; tweenData.target[tweenData.key] = tweenData.current } }, setCallback: function(type, callback, params, scope) { this.callbacks[type] = { func: callback, scope: scope, params: params }; return this }, complete: function(delay) { if (delay === undefined) { delay = 0 } if (delay) { this.countdown = delay; this.state = TWEEN_CONST.COMPLETE_DELAY } else { var onComplete = this.callbacks.onComplete; if (onComplete) { onComplete.params[1] = this.targets; onComplete.func.apply(onComplete.scope, onComplete.params) } this.state = TWEEN_CONST.PENDING_REMOVE } }, stop: function(resetTo) { if (this.state === TWEEN_CONST.ACTIVE) { if (resetTo !== undefined) { this.seek(resetTo) } } if (this.state !== TWEEN_CONST.REMOVED) { if (this.state === TWEEN_CONST.PAUSED || this.state === TWEEN_CONST.PENDING_ADD) { this.parent._destroy.push(this); this.parent._toProcess++ } this.state = TWEEN_CONST.PENDING_REMOVE } }, update: function(timestamp, delta) { if (this.state === TWEEN_CONST.PAUSED) { return false } if (this.useFrames) { delta = 1 * this.parent.timeScale } delta *= this.timeScale; this.elapsed += delta; this.progress = Math.min(this.elapsed / this.duration, 1); this.totalElapsed += delta; this.totalProgress = Math.min(this.totalElapsed / this.totalDuration, 1); switch (this.state) { case TWEEN_CONST.ACTIVE: var stillRunning = false; for (var i = 0; i < this.totalData; i++) { if (this.updateTweenData(this, this.data[i], delta)) { stillRunning = true } } if (!stillRunning) { this.nextState() } break; case TWEEN_CONST.LOOP_DELAY: this.countdown -= delta; if (this.countdown <= 0) { this.state = TWEEN_CONST.ACTIVE } break; case TWEEN_CONST.OFFSET_DELAY: this.countdown -= delta; if (this.countdown <= 0) { var onStart = this.callbacks.onStart; if (onStart) { onStart.params[1] = this.targets; onStart.func.apply(onStart.scope, onStart.params) } this.state = TWEEN_CONST.ACTIVE } break; case TWEEN_CONST.COMPLETE_DELAY: this.countdown -= delta; if (this.countdown <= 0) { var onComplete = this.callbacks.onComplete; if (onComplete) { onComplete.func.apply(onComplete.scope, onComplete.params) } this.state = TWEEN_CONST.PENDING_REMOVE } break } return this.state === TWEEN_CONST.PENDING_REMOVE }, setStateFromEnd: function(tween, tweenData, diff) { if (tweenData.yoyo) { tweenData.elapsed = diff; tweenData.progress = diff / tweenData.duration; if (tweenData.flipX) { tweenData.target.toggleFlipX() } if (tweenData.flipY) { tweenData.target.toggleFlipY() } var onYoyo = tween.callbacks.onYoyo; if (onYoyo) { onYoyo.params[1] = tweenData.target; onYoyo.func.apply(onYoyo.scope, onYoyo.params) } tweenData.start = tweenData.getStartValue(tweenData.target, tweenData.key, tweenData.start); return TWEEN_CONST.PLAYING_BACKWARD } else if (tweenData.repeatCounter > 0) { tweenData.repeatCounter--; tweenData.elapsed = diff; tweenData.progress = diff / tweenData.duration; if (tweenData.flipX) { tweenData.target.toggleFlipX() } if (tweenData.flipY) { tweenData.target.toggleFlipY() } var onRepeat = tween.callbacks.onRepeat; if (onRepeat) { onRepeat.params[1] = tweenData.target; onRepeat.func.apply(onRepeat.scope, onRepeat.params) } tweenData.start = tweenData.getStartValue(tweenData.target, tweenData.key, tweenData.start); tweenData.end = tweenData.getEndValue(tweenData.target, tweenData.key, tweenData.start); if (tweenData.repeatDelay > 0) { tweenData.elapsed = tweenData.repeatDelay - diff; tweenData.current = tweenData.start; tweenData.target[tweenData.key] = tweenData.current; return TWEEN_CONST.REPEAT_DELAY } else { return TWEEN_CONST.PLAYING_FORWARD } } return TWEEN_CONST.COMPLETE }, setStateFromStart: function(tween, tweenData, diff) { if (tweenData.repeatCounter > 0) { tweenData.repeatCounter--; tweenData.elapsed = diff; tweenData.progress = diff / tweenData.duration; if (tweenData.flipX) { tweenData.target.toggleFlipX() } if (tweenData.flipY) { tweenData.target.toggleFlipY() } var onRepeat = tween.callbacks.onRepeat; if (onRepeat) { onRepeat.params[1] = tweenData.target; onRepeat.func.apply(onRepeat.scope, onRepeat.params) } tweenData.end = tweenData.getEndValue(tweenData.target, tweenData.key, tweenData.start); if (tweenData.repeatDelay > 0) { tweenData.elapsed = tweenData.repeatDelay - diff; tweenData.current = tweenData.start; tweenData.target[tweenData.key] = tweenData.current; return TWEEN_CONST.REPEAT_DELAY } else { return TWEEN_CONST.PLAYING_FORWARD } } return TWEEN_CONST.COMPLETE }, updateTweenData: function(tween, tweenData, delta) { switch (tweenData.state) { case TWEEN_CONST.PLAYING_FORWARD: case TWEEN_CONST.PLAYING_BACKWARD: if (!tweenData.target) { tweenData.state = TWEEN_CONST.COMPLETE; break } var elapsed = tweenData.elapsed; var duration = tweenData.duration; var diff = 0; elapsed += delta; if (elapsed > duration) { diff = elapsed - duration; elapsed = duration } var forward = tweenData.state === TWEEN_CONST.PLAYING_FORWARD; var progress = elapsed / duration; var v; if (forward) { v = tweenData.ease(progress) } else { v = tweenData.ease(1 - progress) } tweenData.current = tweenData.start + (tweenData.end - tweenData.start) * v; tweenData.target[tweenData.key] = tweenData.current; tweenData.elapsed = elapsed; tweenData.progress = progress; var onUpdate = tween.callbacks.onUpdate; if (onUpdate) { onUpdate.params[1] = tweenData.target; onUpdate.func.apply(onUpdate.scope, onUpdate.params) } if (progress === 1) { if (forward) { if (tweenData.hold > 0) { tweenData.elapsed = tweenData.hold - diff; tweenData.state = TWEEN_CONST.HOLD_DELAY } else { tweenData.state = this.setStateFromEnd(tween, tweenData, diff) } } else { tweenData.state = this.setStateFromStart(tween, tweenData, diff) } } break; case TWEEN_CONST.DELAY: tweenData.elapsed -= delta; if (tweenData.elapsed <= 0) { tweenData.elapsed = Math.abs(tweenData.elapsed); tweenData.state = TWEEN_CONST.PENDING_RENDER } break; case TWEEN_CONST.REPEAT_DELAY: tweenData.elapsed -= delta; if (tweenData.elapsed <= 0) { tweenData.elapsed = Math.abs(tweenData.elapsed); tweenData.state = TWEEN_CONST.PLAYING_FORWARD } break; case TWEEN_CONST.HOLD_DELAY: tweenData.elapsed -= delta; if (tweenData.elapsed <= 0) { tweenData.state = this.setStateFromEnd(tween, tweenData, Math.abs(tweenData.elapsed)) } break; case TWEEN_CONST.PENDING_RENDER: if (tweenData.target) { tweenData.start = tweenData.getStartValue(tweenData.target, tweenData.key, tweenData.target[tweenData.key]); tweenData.end = tweenData.getEndValue(tweenData.target, tweenData.key, tweenData.start); tweenData.current = tweenData.start; tweenData.target[tweenData.key] = tweenData.start; tweenData.state = TWEEN_CONST.PLAYING_FORWARD } else { tweenData.state = TWEEN_CONST.COMPLETE } break } return tweenData.state !== TWEEN_CONST.COMPLETE } }); Tween.TYPES = ["onComplete", "onLoop", "onRepeat", "onStart", "onUpdate", "onYoyo"]; GameObjectFactory.register("tween", function(config) { return this.scene.sys.tweens.add(config) }); GameObjectCreator.register("tween", function(config) { return this.scene.sys.tweens.create(config) }); module.exports = Tween }, function(module, exports) { var TweenData = function(target, key, getEnd, getStart, ease, delay, duration, yoyo, hold, repeat, repeatDelay, flipX, flipY) { return { target: target, key: key, getEndValue: getEnd, getStartValue: getStart, ease: ease, duration: 0, totalDuration: 0, delay: 0, yoyo: yoyo, hold: 0, repeat: 0, repeatDelay: 0, flipX: flipX, flipY: flipY, progress: 0, elapsed: 0, repeatCounter: 0, start: 0, current: 0, end: 0, t1: 0, t2: 0, gen: { delay: delay, duration: duration, hold: hold, repeat: repeat, repeatDelay: repeatDelay }, state: 0 } }; module.exports = TweenData }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Matrix4 = __webpack_require__(202); var RandomXYZ = __webpack_require__(409); var RandomXYZW = __webpack_require__(410); var RotateVec3 = __webpack_require__(414); var Set = __webpack_require__(81); var Sprite3D = __webpack_require__(140); var Vector2 = __webpack_require__(3); var Vector3 = __webpack_require__(86); var Vector4 = __webpack_require__(125); var tmpVec3 = new Vector3; var tmpVec4 = new Vector4; var dirvec = new Vector3; var rightvec = new Vector3; var billboardMatrix = new Matrix4; var Camera = new Class({ initialize: function Camera(scene) { this.scene = scene; this.displayList = scene.sys.displayList; this.updateList = scene.sys.updateList; this.name = ""; this.direction = new Vector3(0, 0, -1); this.up = new Vector3(0, 1, 0); this.position = new Vector3; this.pixelScale = 128; this.projection = new Matrix4; this.view = new Matrix4; this.combined = new Matrix4; this.invProjectionView = new Matrix4; this.near = 1; this.far = 100; this.ray = { origin: new Vector3, direction: new Vector3 }; this.viewportWidth = 0; this.viewportHeight = 0; this.billboardMatrixDirty = true; this.children = new Set }, setPosition: function(x, y, z) { this.position.set(x, y, z); return this.update() }, setScene: function(scene) { this.scene = scene; return this }, setPixelScale: function(value) { this.pixelScale = value; return this.update() }, add: function(sprite3D) { this.children.set(sprite3D); this.displayList.add(sprite3D.gameObject); this.updateList.add(sprite3D.gameObject); this.updateChildren(); return sprite3D }, remove: function(child) { this.displayList.remove(child.gameObject); this.updateList.remove(child.gameObject); this.children.delete(child); return this }, clear: function() { var children = this.getChildren(); for (var i = 0; i < children.length; i++) { this.remove(children[i]) } return this }, getChildren: function() { return this.children.entries }, create: function(x, y, z, key, frame, visible) { if (visible === undefined) { visible = true } var child = new Sprite3D(this.scene, x, y, z, key, frame); this.displayList.add(child.gameObject); this.updateList.add(child.gameObject); child.visible = visible; this.children.set(child); this.updateChildren(); return child }, createMultiple: function(quantity, key, frame, visible) { if (visible === undefined) { visible = true } var output = []; for (var i = 0; i < quantity; i++) { var child = new Sprite3D(this.scene, 0, 0, 0, key, frame); this.displayList.add(child.gameObject); this.updateList.add(child.gameObject); child.visible = visible; this.children.set(child); output.push(child) } return output }, createRect: function(size, spacing, key, frame) { if (typeof size === "number") { size = { x: size, y: size, z: size } } if (typeof spacing === "number") { spacing = { x: spacing, y: spacing, z: spacing } } var quantity = size.x * size.y * size.z; var sprites = this.createMultiple(quantity, key, frame); var i = 0; for (var z = .5 - size.z / 2; z < size.z / 2; z++) { for (var y = .5 - size.y / 2; y < size.y / 2; y++) { for (var x = .5 - size.x / 2; x < size.x / 2; x++) { var bx = x * spacing.x; var by = y * spacing.y; var bz = z * spacing.z; sprites[i].position.set(bx, by, bz); i++ } } } this.update(); return sprites }, randomSphere: function(radius, sprites) { if (sprites === undefined) { sprites = this.getChildren() } for (var i = 0; i < sprites.length; i++) { RandomXYZ(sprites[i].position, radius) } return this.update() }, randomCube: function(scale, sprites) { if (sprites === undefined) { sprites = this.getChildren() } for (var i = 0; i < sprites.length; i++) { RandomXYZW(sprites[i].position, scale) } return this.update() }, translateChildren: function(vec3, sprites) { if (sprites === undefined) { sprites = this.getChildren() } for (var i = 0; i < sprites.length; i++) { sprites[i].position.add(vec3) } return this.update() }, transformChildren: function(mat4, sprites) { if (sprites === undefined) { sprites = this.getChildren() } for (var i = 0; i < sprites.length; i++) { sprites[i].position.transformMat4(mat4) } return this.update() }, setViewport: function(width, height) { this.viewportWidth = width; this.viewportHeight = height; return this.update() }, translate: function(x, y, z) { if (typeof x === "object") { this.position.x += x.x || 0; this.position.y += x.y || 0; this.position.z += x.z || 0 } else { this.position.x += x || 0; this.position.y += y || 0; this.position.z += z || 0 } return this.update() }, lookAt: function(x, y, z) { var dir = this.direction; var up = this.up; if (typeof x === "object") { dir.copy(x) } else { dir.set(x, y, z) } dir.subtract(this.position).normalize(); tmpVec3.copy(dir).cross(up).normalize(); up.copy(tmpVec3).cross(dir).normalize(); return this.update() }, rotate: function(radians, axis) { RotateVec3(this.direction, axis, radians); RotateVec3(this.up, axis, radians); return this.update() }, rotateAround: function(point, radians, axis) { tmpVec3.copy(point).subtract(this.position); this.translate(tmpVec3); this.rotate(radians, axis); this.translate(tmpVec3.negate()); return this.update() }, project: function(vec, out) { if (out === undefined) { out = new Vector4 } var viewportWidth = this.viewportWidth; var viewportHeight = this.viewportHeight; var n = Camera.NEAR_RANGE; var f = Camera.FAR_RANGE; tmpVec4.set(vec.x, vec.y, vec.z, 1); tmpVec4.transformMat4(this.combined); if (tmpVec4.w === 0) { tmpVec4.w = 1 } tmpVec4.x = tmpVec4.x / tmpVec4.w; tmpVec4.y = tmpVec4.y / tmpVec4.w; tmpVec4.z = tmpVec4.z / tmpVec4.w; out.x = viewportWidth / 2 * tmpVec4.x + (0 + viewportWidth / 2); out.y = viewportHeight / 2 * tmpVec4.y + (0 + viewportHeight / 2); out.z = (f - n) / 2 * tmpVec4.z + (f + n) / 2; if (out.w === 0 || out.w) { out.w = 1 / tmpVec4.w } return out }, unproject: function(vec, out) { if (out === undefined) { out = new Vector3 } var viewport = tmpVec4.set(0, 0, this.viewportWidth, this.viewportHeight); return out.copy(vec).unproject(viewport, this.invProjectionView) }, getPickRay: function(x, y) { var origin = this.ray.origin.set(x, y, 0); var direction = this.ray.direction.set(x, y, 1); var viewport = tmpVec4.set(0, 0, this.viewportWidth, this.viewportHeight); var mtx = this.invProjectionView; origin.unproject(viewport, mtx); direction.unproject(viewport, mtx); direction.subtract(origin).normalize(); return this.ray }, updateChildren: function() { var children = this.children.entries; for (var i = 0; i < children.length; i++) { children[i].project(this) } return this }, update: function() { return this.updateChildren() }, updateBillboardMatrix: function() { var dir = dirvec.set(this.direction).negate(); var right = rightvec.set(this.up).cross(dir).normalize(); var up = tmpVec3.set(dir).cross(right).normalize(); var out = billboardMatrix.val; out[0] = right.x; out[1] = right.y; out[2] = right.z; out[3] = 0; out[4] = up.x; out[5] = up.y; out[6] = up.z; out[7] = 0; out[8] = dir.x; out[9] = dir.y; out[10] = dir.z; out[11] = 0; out[12] = 0; out[13] = 0; out[14] = 0; out[15] = 1; this.billboardMatrixDirty = false }, getPointSize: function(vec, size, out) { if (out === undefined) { out = new Vector2 } if (this.billboardMatrixDirty) { this.updateBillboardMatrix() } var tmp = tmpVec3; var dx = size.x / this.pixelScale / 2; var dy = size.y / this.pixelScale / 2; tmp.set(-dx, -dy, 0).transformMat4(billboardMatrix).add(vec); this.project(tmp, tmp); var tlx = tmp.x; var tly = tmp.y; tmp.set(dx, dy, 0).transformMat4(billboardMatrix).add(vec); this.project(tmp, tmp); var brx = tmp.x; var bry = tmp.y; var w = brx - tlx; var h = bry - tly; return out.set(w, h) }, destroy: function() { this.children.clear(); this.scene = undefined; this.children = undefined }, setX: function(value) { this.position.x = value; return this.update() }, setY: function(value) { this.position.y = value; return this.update() }, setZ: function(value) { this.position.z = value; return this.update() }, x: { get: function() { return this.position.x }, set: function(value) { this.position.x = value; this.update() } }, y: { get: function() { return this.position.y }, set: function(value) { this.position.y = value; this.update() } }, z: { get: function() { return this.position.z }, set: function(value) { this.position.z = value; this.update() } } }); Camera.FAR_RANGE = 1; Camera.NEAR_RANGE = 0; module.exports = Camera }, function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__; var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__; var paper = function(self, undefined) { self = self || __webpack_require__(1156); var window = self.window, document = self.document; var Base = new function() { var hidden = /^(statics|enumerable|beans|preserve)$/, array = [], slice = array.slice, create = Object.create, describe = Object.getOwnPropertyDescriptor, define = Object.defineProperty, forEach = array.forEach || function(iter, bind) { for (var i = 0, l = this.length; i < l; i++) { iter.call(bind, this[i], i, this) } }, forIn = function(iter, bind) { for (var i in this) { if (this.hasOwnProperty(i)) iter.call(bind, this[i], i, this) } }, set = Object.assign || function(dst) { for (var i = 1, l = arguments.length; i < l; i++) { var src = arguments[i]; for (var key in src) { if (src.hasOwnProperty(key)) dst[key] = src[key] } } return dst }, each = function(obj, iter, bind) { if (obj) { var desc = describe(obj, "length"); (desc && typeof desc.value === "number" ? forEach : forIn).call(obj, iter, bind = bind || obj) } return bind }; function inject(dest, src, enumerable, beans, preserve) { var beansNames = {}; function field(name, val) { val = val || (val = describe(src, name)) && (val.get ? val : val.value); if (typeof val === "string" && val[0] === "#") val = dest[val.substring(1)] || val; var isFunc = typeof val === "function", res = val, prev = preserve || isFunc && !val.base ? val && val.get ? name in dest : dest[name] : null, bean; if (!preserve || !prev) { if (isFunc && prev) val.base = prev; if (isFunc && beans !== false && (bean = name.match(/^([gs]et|is)(([A-Z])(.*))$/))) beansNames[bean[3].toLowerCase() + bean[4]] = bean[2]; if (!res || isFunc || !res.get || typeof res.get !== "function" || !Base.isPlainObject(res)) { res = { value: res, writable: true } } if ((describe(dest, name) || { configurable: true }).configurable) { res.configurable = true; res.enumerable = enumerable != null ? enumerable : !bean } define(dest, name, res) } } if (src) { for (var name in src) { if (src.hasOwnProperty(name) && !hidden.test(name)) field(name) } for (var name in beansNames) { var part = beansNames[name], set = dest["set" + part], get = dest["get" + part] || set && dest["is" + part]; if (get && (beans === true || get.length === 0)) field(name, { get: get, set: set }) } } return dest } function Base() { for (var i = 0, l = arguments.length; i < l; i++) { var src = arguments[i]; if (src) set(this, src) } return this } return inject(Base, { inject: function(src) { if (src) { var statics = src.statics === true ? src : src.statics, beans = src.beans, preserve = src.preserve; if (statics !== src) inject(this.prototype, src, src.enumerable, beans, preserve); inject(this, statics, null, beans, preserve) } for (var i = 1, l = arguments.length; i < l; i++) this.inject(arguments[i]); return this }, extend: function() { var base = this, ctor, proto; for (var i = 0, obj, l = arguments.length; i < l && !(ctor && proto); i++) { obj = arguments[i]; ctor = ctor || obj.initialize; proto = proto || obj.prototype } ctor = ctor || function() { base.apply(this, arguments) }; proto = ctor.prototype = proto || create(this.prototype); define(proto, "constructor", { value: ctor, writable: true, configurable: true }); inject(ctor, this); if (arguments.length) this.inject.apply(ctor, arguments); ctor.base = base; return ctor } }).inject({ enumerable: false, initialize: Base, set: Base, inject: function() { for (var i = 0, l = arguments.length; i < l; i++) { var src = arguments[i]; if (src) { inject(this, src, src.enumerable, src.beans, src.preserve) } } return this }, extend: function() { var res = create(this); return res.inject.apply(res, arguments) }, each: function(iter, bind) { return each(this, iter, bind) }, clone: function() { return new this.constructor(this) }, statics: { set: set, each: each, create: create, define: define, describe: describe, clone: function(obj) { return set(new obj.constructor, obj) }, isPlainObject: function(obj) { var ctor = obj != null && obj.constructor; return ctor && (ctor === Object || ctor === Base || ctor.name === "Object") }, pick: function(a, b) { return a !== undefined ? a : b }, slice: function(list, begin, end) { return slice.call(list, begin, end) } } }) }; if (true) module.exports = Base; Base.inject({ enumerable: false, toString: function() { return this._id != null ? (this._class || "Object") + (this._name ? " '" + this._name + "'" : " @" + this._id) : "{ " + Base.each(this, function(value, key) { if (!/^_/.test(key)) { var type = typeof value; this.push(key + ": " + (type === "number" ? Formatter.instance.number(value) : type === "string" ? "'" + value + "'" : value)) } }, []).join(", ") + " }" }, getClassName: function() { return this._class || "" }, importJSON: function(json) { return Base.importJSON(json, this) }, exportJSON: function(options) { return Base.exportJSON(this, options) }, toJSON: function() { return Base.serialize(this) }, set: function(props, exclude) { if (props) Base.filter(this, props, exclude, this._prioritize); return this } }, { beans: false, statics: { exports: {}, extend: function extend() { var res = extend.base.apply(this, arguments), name = res.prototype._class; if (name && !Base.exports[name]) Base.exports[name] = res; return res }, equals: function(obj1, obj2) { if (obj1 === obj2) return true; if (obj1 && obj1.equals) return obj1.equals(obj2); if (obj2 && obj2.equals) return obj2.equals(obj1); if (obj1 && obj2 && typeof obj1 === "object" && typeof obj2 === "object") { if (Array.isArray(obj1) && Array.isArray(obj2)) { var length = obj1.length; if (length !== obj2.length) return false; while (length--) { if (!Base.equals(obj1[length], obj2[length])) return false } } else { var keys = Object.keys(obj1), length = keys.length; if (length !== Object.keys(obj2).length) return false; while (length--) { var key = keys[length]; if (!(obj2.hasOwnProperty(key) && Base.equals(obj1[key], obj2[key]))) return false } } return true } return false }, read: function(list, start, options, amount) { if (this === Base) { var value = this.peek(list, start); list.__index++; return value } var proto = this.prototype, readIndex = proto._readIndex, begin = start || readIndex && list.__index || 0, length = list.length, obj = list[begin]; amount = amount || length - begin; if (obj instanceof this || options && options.readNull && obj == null && amount <= 1) { if (readIndex) list.__index = begin + 1; return obj && options && options.clone ? obj.clone() : obj } obj = Base.create(proto); if (readIndex) obj.__read = true; obj = obj.initialize.apply(obj, begin > 0 || begin + amount < length ? Base.slice(list, begin, begin + amount) : list) || obj; if (readIndex) { list.__index = begin + obj.__read; var filtered = obj.__filtered; if (filtered) { list.__filtered = filtered; obj.__filtered = undefined } obj.__read = undefined } return obj }, peek: function(list, start) { return list[list.__index = start || list.__index || 0] }, remain: function(list) { return list.length - (list.__index || 0) }, readList: function(list, start, options, amount) { var res = [], entry, begin = start || 0, end = amount ? begin + amount : list.length; for (var i = begin; i < end; i++) { res.push(Array.isArray(entry = list[i]) ? this.read(entry, 0, options) : this.read(list, i, options, 1)) } return res }, readNamed: function(list, name, start, options, amount) { var value = this.getNamed(list, name), hasObject = value !== undefined; if (hasObject) { var filtered = list.__filtered; if (!filtered) { filtered = list.__filtered = Base.create(list[0]); filtered.__unfiltered = list[0] } filtered[name] = undefined } var l = hasObject ? [value] : list, res = this.read(l, start, options, amount); return res }, getNamed: function(list, name) { var arg = list[0]; if (list._hasObject === undefined) list._hasObject = list.length === 1 && Base.isPlainObject(arg); if (list._hasObject) return name ? arg[name] : list.__filtered || arg }, hasNamed: function(list, name) { return !!this.getNamed(list, name) }, filter: function(dest, source, exclude, prioritize) { var processed; function handleKey(key) { if (!(exclude && key in exclude) && !(processed && key in processed)) { var value = source[key]; if (value !== undefined) dest[key] = value } } if (prioritize) { var keys = {}; for (var i = 0, key, l = prioritize.length; i < l; i++) { if ((key = prioritize[i]) in source) { handleKey(key); keys[key] = true } } processed = keys } Object.keys(source.__unfiltered || source).forEach(handleKey); return dest }, isPlainValue: function(obj, asString) { return Base.isPlainObject(obj) || Array.isArray(obj) || asString && typeof obj === "string" }, serialize: function(obj, options, compact, dictionary) { options = options || {}; var isRoot = !dictionary, res; if (isRoot) { options.formatter = new Formatter(options.precision); dictionary = { length: 0, definitions: {}, references: {}, add: function(item, create) { var id = "#" + item._id, ref = this.references[id]; if (!ref) { this.length++; var res = create.call(item), name = item._class; if (name && res[0] !== name) res.unshift(name); this.definitions[id] = res; ref = this.references[id] = [id] } return ref } } } if (obj && obj._serialize) { res = obj._serialize(options, dictionary); var name = obj._class; if (name && !obj._compactSerialize && (isRoot || !compact) && res[0] !== name) { res.unshift(name) } } else if (Array.isArray(obj)) { res = []; for (var i = 0, l = obj.length; i < l; i++) res[i] = Base.serialize(obj[i], options, compact, dictionary) } else if (Base.isPlainObject(obj)) { res = {}; var keys = Object.keys(obj); for (var i = 0, l = keys.length; i < l; i++) { var key = keys[i]; res[key] = Base.serialize(obj[key], options, compact, dictionary) } } else if (typeof obj === "number") { res = options.formatter.number(obj, options.precision) } else { res = obj } return isRoot && dictionary.length > 0 ? [ ["dictionary", dictionary.definitions], res ] : res }, deserialize: function(json, create, _data, _setDictionary, _isRoot) { var res = json, isFirst = !_data, hasDictionary = isFirst && json && json.length && json[0][0] === "dictionary"; _data = _data || {}; if (Array.isArray(json)) { var type = json[0], isDictionary = type === "dictionary"; if (json.length == 1 && /^#/.test(type)) { return _data.dictionary[type] } type = Base.exports[type]; res = []; for (var i = type ? 1 : 0, l = json.length; i < l; i++) { res.push(Base.deserialize(json[i], create, _data, isDictionary, hasDictionary)) } if (type) { var args = res; if (create) { res = create(type, args, isFirst || _isRoot) } else { res = new type(args) } } } else if (Base.isPlainObject(json)) { res = {}; if (_setDictionary) _data.dictionary = res; for (var key in json) res[key] = Base.deserialize(json[key], create, _data) } return hasDictionary ? res[1] : res }, exportJSON: function(obj, options) { var json = Base.serialize(obj, options); return options && options.asString == false ? json : JSON.stringify(json) }, importJSON: function(json, target) { return Base.deserialize(typeof json === "string" ? JSON.parse(json) : json, function(ctor, args, isRoot) { var useTarget = isRoot && target && target.constructor === ctor, obj = useTarget ? target : Base.create(ctor.prototype); if (args.length === 1 && obj instanceof Item && (useTarget || !(obj instanceof Layer))) { var arg = args[0]; if (Base.isPlainObject(arg)) arg.insert = false }(useTarget ? obj.set : ctor).apply(obj, args); if (useTarget) target = null; return obj }) }, push: function(list, items) { var itemsLength = items.length; if (itemsLength < 4096) { list.push.apply(list, items) } else { var startLength = list.length; list.length += itemsLength; for (var i = 0; i < itemsLength; i++) { list[startLength + i] = items[i] } } return list }, splice: function(list, items, index, remove) { var amount = items && items.length, append = index === undefined; index = append ? list.length : index; if (index > list.length) index = list.length; for (var i = 0; i < amount; i++) items[i]._index = index + i; if (append) { Base.push(list, items); return [] } else { var args = [index, remove]; if (items) Base.push(args, items); var removed = list.splice.apply(list, args); for (var i = 0, l = removed.length; i < l; i++) removed[i]._index = undefined; for (var i = index + amount, l = list.length; i < l; i++) list[i]._index = i; return removed } }, capitalize: function(str) { return str.replace(/\b[a-z]/g, function(match) { return match.toUpperCase() }) }, camelize: function(str) { return str.replace(/-(.)/g, function(match, chr) { return chr.toUpperCase() }) }, hyphenate: function(str) { return str.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase() } } }); var Emitter = { on: function(type, func) { if (typeof type !== "string") { Base.each(type, function(value, key) { this.on(key, value) }, this) } else { var types = this._eventTypes, entry = types && types[type], handlers = this._callbacks = this._callbacks || {}; handlers = handlers[type] = handlers[type] || []; if (handlers.indexOf(func) === -1) { handlers.push(func); if (entry && entry.install && handlers.length === 1) entry.install.call(this, type) } } return this }, off: function(type, func) { if (typeof type !== "string") { Base.each(type, function(value, key) { this.off(key, value) }, this); return } var types = this._eventTypes, entry = types && types[type], handlers = this._callbacks && this._callbacks[type], index; if (handlers) { if (!func || (index = handlers.indexOf(func)) !== -1 && handlers.length === 1) { if (entry && entry.uninstall) entry.uninstall.call(this, type); delete this._callbacks[type] } else if (index !== -1) { handlers.splice(index, 1) } } return this }, once: function(type, func) { return this.on(type, function() { func.apply(this, arguments); this.off(type, func) }) }, emit: function(type, event) { var handlers = this._callbacks && this._callbacks[type]; if (!handlers) return false; var args = Base.slice(arguments, 1), setTarget = event && event.target && !event.currentTarget; handlers = handlers.slice(); if (setTarget) event.currentTarget = this; for (var i = 0, l = handlers.length; i < l; i++) { if (handlers[i].apply(this, args) == false) { if (event && event.stop) event.stop(); break } } if (setTarget) delete event.currentTarget; return true }, responds: function(type) { return !!(this._callbacks && this._callbacks[type]) }, attach: "#on", detach: "#off", fire: "#emit", _installEvents: function(install) { var types = this._eventTypes, handlers = this._callbacks, key = install ? "install" : "uninstall"; if (types) { for (var type in handlers) { if (handlers[type].length > 0) { var entry = types[type], func = entry && entry[key]; if (func) func.call(this, type) } } } }, statics: { inject: function inject(src) { var events = src._events; if (events) { var types = {}; Base.each(events, function(entry, key) { var isString = typeof entry === "string", name = isString ? entry : key, part = Base.capitalize(name), type = name.substring(2).toLowerCase(); types[type] = isString ? {} : entry; name = "_" + name; src["get" + part] = function() { return this[name] }; src["set" + part] = function(func) { var prev = this[name]; if (prev) this.off(type, prev); if (func) this.on(type, func); this[name] = func } }); src._eventTypes = types } return inject.base.apply(this, arguments) } } }; var PaperScope = Base.extend({ _class: "PaperScope", initialize: function PaperScope() { paper = this; this.settings = new Base({ applyMatrix: true, insertItems: true, handleSize: 4, hitTolerance: 0 }); this.project = null; this.projects = []; this.tools = []; this._id = PaperScope._id++; PaperScope._scopes[this._id] = this; var proto = PaperScope.prototype; if (!this.support) { var ctx = CanvasProvider.getContext(1, 1) || {}; proto.support = { nativeDash: "setLineDash" in ctx || "mozDash" in ctx, nativeBlendModes: BlendMode.nativeModes }; CanvasProvider.release(ctx) } if (!this.agent) { var user = self.navigator.userAgent.toLowerCase(), os = (/(darwin|win|mac|linux|freebsd|sunos)/.exec(user) || [])[0], platform = os === "darwin" ? "mac" : os, agent = proto.agent = proto.browser = { platform: platform }; if (platform) agent[platform] = true; user.replace(/(opera|chrome|safari|webkit|firefox|msie|trident|atom|node)\/?\s*([.\d]+)(?:.*version\/([.\d]+))?(?:.*rv\:v?([.\d]+))?/g, function(match, n, v1, v2, rv) { if (!agent.chrome) { var v = n === "opera" ? v2 : /^(node|trident)$/.test(n) ? rv : v1; agent.version = v; agent.versionNumber = parseFloat(v); n = n === "trident" ? "msie" : n; agent.name = n; agent[n] = true } }); if (agent.chrome) delete agent.webkit; if (agent.atom) delete agent.chrome } }, version: "0.11.8", getView: function() { var project = this.project; return project && project._view }, getPaper: function() { return this }, execute: function(code, options) { var exports = paper.PaperScript.execute(code, this, options); View.updateFocus(); return exports }, install: function(scope) { var that = this; Base.each(["project", "view", "tool"], function(key) { Base.define(scope, key, { configurable: true, get: function() { return that[key] } }) }); for (var key in this) if (!/^_/.test(key) && this[key]) scope[key] = this[key] }, setup: function(element) { paper = this; this.project = new Project(element); return this }, createCanvas: function(width, height) { return CanvasProvider.getCanvas(width, height) }, activate: function() { paper = this }, clear: function() { var projects = this.projects, tools = this.tools; for (var i = projects.length - 1; i >= 0; i--) projects[i].remove(); for (var i = tools.length - 1; i >= 0; i--) tools[i].remove() }, remove: function() { this.clear(); delete PaperScope._scopes[this._id] }, statics: new function() { function handleAttribute(name) { name += "Attribute"; return function(el, attr) { return el[name](attr) || el[name]("data-paper-" + attr) } } return { _scopes: {}, _id: 0, get: function(id) { return this._scopes[id] || null }, getAttribute: handleAttribute("get"), hasAttribute: handleAttribute("has") } } }); var PaperScopeItem = Base.extend(Emitter, { initialize: function(activate) { this._scope = paper; this._index = this._scope[this._list].push(this) - 1; if (activate || !this._scope[this._reference]) this.activate() }, activate: function() { if (!this._scope) return false; var prev = this._scope[this._reference]; if (prev && prev !== this) prev.emit("deactivate"); this._scope[this._reference] = this; this.emit("activate", prev); return true }, isActive: function() { return this._scope[this._reference] === this }, remove: function() { if (this._index == null) return false; Base.splice(this._scope[this._list], null, this._index, 1); if (this._scope[this._reference] == this) this._scope[this._reference] = null; this._scope = null; return true }, getView: function() { return this._scope.getView() } }); var Formatter = Base.extend({ initialize: function(precision) { this.precision = Base.pick(precision, 5); this.multiplier = Math.pow(10, this.precision) }, number: function(val) { return this.precision < 16 ? Math.round(val * this.multiplier) / this.multiplier : val }, pair: function(val1, val2, separator) { return this.number(val1) + (separator || ",") + this.number(val2) }, point: function(val, separator) { return this.number(val.x) + (separator || ",") + this.number(val.y) }, size: function(val, separator) { return this.number(val.width) + (separator || ",") + this.number(val.height) }, rectangle: function(val, separator) { return this.point(val, separator) + (separator || ",") + this.size(val, separator) } }); Formatter.instance = new Formatter; var Numerical = new function() { var abscissas = [ [.5773502691896257], [0, .7745966692414834], [.33998104358485626, .8611363115940526], [0, .5384693101056831, .906179845938664], [.2386191860831969, .6612093864662645, .932469514203152], [0, .4058451513773972, .7415311855993945, .9491079123427585], [.1834346424956498, .525532409916329, .7966664774136267, .9602898564975363], [0, .3242534234038089, .6133714327005904, .8360311073266358, .9681602395076261], [.14887433898163122, .4333953941292472, .6794095682990244, .8650633666889845, .9739065285171717], [0, .26954315595234496, .5190961292068118, .7301520055740494, .8870625997680953, .978228658146057], [.1252334085114689, .3678314989981802, .5873179542866175, .7699026741943047, .9041172563704749, .9815606342467192], [0, .2304583159551348, .44849275103644687, .6423493394403402, .8015780907333099, .9175983992229779, .9841830547185881], [.10805494870734367, .31911236892788974, .5152486363581541, .6872929048116855, .827201315069765, .9284348836635735, .9862838086968123], [0, .20119409399743451, .3941513470775634, .5709721726085388, .7244177313601701, .8482065834104272, .937273392400706, .9879925180204854], [.09501250983763744, .2816035507792589, .45801677765722737, .6178762444026438, .755404408355003, .8656312023878318, .9445750230732326, .9894009349916499] ]; var weights = [ [1], [.8888888888888888, .5555555555555556], [.6521451548625461, .34785484513745385], [.5688888888888889, .47862867049936647, .23692688505618908], [.46791393457269104, .3607615730481386, .17132449237917036], [.4179591836734694, .3818300505051189, .27970539148927664, .1294849661688697], [.362683783378362, .31370664587788727, .22238103445337448, .10122853629037626], [.3302393550012598, .31234707704000286, .26061069640293544, .1806481606948574, .08127438836157441], [.29552422471475287, .26926671930999635, .21908636251598204, .1494513491505806, .06667134430868814], [.2729250867779006, .26280454451024665, .23319376459199048, .18629021092773426, .1255803694649046, .05566856711617366], [.24914704581340277, .2334925365383548, .20316742672306592, .16007832854334622, .10693932599531843, .04717533638651183], [.2325515532308739, .22628318026289723, .2078160475368885, .17814598076194574, .13887351021978725, .09212149983772845, .04048400476531588], [.2152638534631578, .2051984637212956, .18553839747793782, .15720316715819355, .12151857068790319, .08015808715976021, .03511946033175186], [.2025782419255613, .19843148532711158, .1861610000155622, .16626920581699392, .13957067792615432, .10715922046717194, .07036604748810812, .03075324199611727], [.1894506104550685, .18260341504492358, .16915651939500254, .14959598881657674, .12462897125553388, .09515851168249279, .062253523938647894, .027152459411754096] ]; var abs = Math.abs, sqrt = Math.sqrt, pow = Math.pow, log2 = Math.log2 || function(x) { return Math.log(x) * Math.LOG2E }, EPSILON = 1e-12, MACHINE_EPSILON = 112e-18; function clamp(value, min, max) { return value < min ? min : value > max ? max : value } function getDiscriminant(a, b, c) { function split(v) { var x = v * 134217729, y = v - x, hi = y + x, lo = v - hi; return [hi, lo] } var D = b * b - a * c, E = b * b + a * c; if (abs(D) * 3 < E) { var ad = split(a), bd = split(b), cd = split(c), p = b * b, dp = bd[0] * bd[0] - p + 2 * bd[0] * bd[1] + bd[1] * bd[1], q = a * c, dq = ad[0] * cd[0] - q + ad[0] * cd[1] + ad[1] * cd[0] + ad[1] * cd[1]; D = p - q + (dp - dq) } return D } function getNormalizationFactor() { var norm = Math.max.apply(Math, arguments); return norm && (norm < 1e-8 || norm > 1e8) ? pow(2, -Math.round(log2(norm))) : 0 } return { EPSILON: EPSILON, MACHINE_EPSILON: MACHINE_EPSILON, CURVETIME_EPSILON: 1e-8, GEOMETRIC_EPSILON: 1e-7, TRIGONOMETRIC_EPSILON: 1e-8, KAPPA: 4 * (sqrt(2) - 1) / 3, isZero: function(val) { return val >= -EPSILON && val <= EPSILON }, clamp: clamp, integrate: function(f, a, b, n) { var x = abscissas[n - 2], w = weights[n - 2], A = (b - a) * .5, B = A + a, i = 0, m = n + 1 >> 1, sum = n & 1 ? w[i++] * f(B) : 0; while (i < m) { var Ax = A * x[i]; sum += w[i++] * (f(B + Ax) + f(B - Ax)) } return A * sum }, findRoot: function(f, df, x, a, b, n, tolerance) { for (var i = 0; i < n; i++) { var fx = f(x), dx = fx / df(x), nx = x - dx; if (abs(dx) < tolerance) { x = nx; break } if (fx > 0) { b = x; x = nx <= a ? (a + b) * .5 : nx } else { a = x; x = nx >= b ? (a + b) * .5 : nx } } return clamp(x, a, b) }, solveQuadratic: function(a, b, c, roots, min, max) { var x1, x2 = Infinity; if (abs(a) < EPSILON) { if (abs(b) < EPSILON) return abs(c) < EPSILON ? -1 : 0; x1 = -c / b } else { b *= -.5; var D = getDiscriminant(a, b, c); if (D && abs(D) < MACHINE_EPSILON) { var f = getNormalizationFactor(abs(a), abs(b), abs(c)); if (f) { a *= f; b *= f; c *= f; D = getDiscriminant(a, b, c) } } if (D >= -MACHINE_EPSILON) { var Q = D < 0 ? 0 : sqrt(D), R = b + (b < 0 ? -Q : Q); if (R === 0) { x1 = c / a; x2 = -x1 } else { x1 = R / a; x2 = c / R } } } var count = 0, boundless = min == null, minB = min - EPSILON, maxB = max + EPSILON; if (isFinite(x1) && (boundless || x1 > minB && x1 < maxB)) roots[count++] = boundless ? x1 : clamp(x1, min, max); if (x2 !== x1 && isFinite(x2) && (boundless || x2 > minB && x2 < maxB)) roots[count++] = boundless ? x2 : clamp(x2, min, max); return count }, solveCubic: function(a, b, c, d, roots, min, max) { var f = getNormalizationFactor(abs(a), abs(b), abs(c), abs(d)), x, b1, c2, qd, q; if (f) { a *= f; b *= f; c *= f; d *= f } function evaluate(x0) { x = x0; var tmp = a * x; b1 = tmp + b; c2 = b1 * x + c; qd = (tmp + b1) * x + c2; q = c2 * x + d } if (abs(a) < EPSILON) { a = b; b1 = c; c2 = d; x = Infinity } else if (abs(d) < EPSILON) { b1 = b; c2 = c; x = 0 } else { evaluate(-(b / a) / 3); var t = q / a, r = pow(abs(t), 1 / 3), s = t < 0 ? -1 : 1, td = -qd / a, rd = td > 0 ? 1.324717957244746 * Math.max(r, sqrt(td)) : r, x0 = x - s * rd; if (x0 !== x) { do { evaluate(x0); x0 = qd === 0 ? x : x - q / qd / (1 + MACHINE_EPSILON) } while (s * x0 > s * x); if (abs(a) * x * x > abs(d / x)) { c2 = -d / x; b1 = (c2 - c) / x } } } var count = Numerical.solveQuadratic(a, b1, c2, roots, min, max), boundless = min == null; if (isFinite(x) && (count === 0 || count > 0 && x !== roots[0] && x !== roots[1]) && (boundless || x > min - EPSILON && x < max + EPSILON)) roots[count++] = boundless ? x : clamp(x, min, max); return count } } }; var UID = { _id: 1, _pools: {}, get: function(name) { if (name) { var pool = this._pools[name]; if (!pool) pool = this._pools[name] = { _id: 1 }; return pool._id++ } else { return this._id++ } } }; var Point = Base.extend({ _class: "Point", _readIndex: true, initialize: function Point(arg0, arg1) { var type = typeof arg0, reading = this.__read, read = 0; if (type === "number") { var hasY = typeof arg1 === "number"; this._set(arg0, hasY ? arg1 : arg0); if (reading) read = hasY ? 2 : 1 } else if (type === "undefined" || arg0 === null) { this._set(0, 0); if (reading) read = arg0 === null ? 1 : 0 } else { var obj = type === "string" ? arg0.split(/[\s,]+/) || [] : arg0; read = 1; if (Array.isArray(obj)) { this._set(+obj[0], +(obj.length > 1 ? obj[1] : obj[0])) } else if ("x" in obj) { this._set(obj.x || 0, obj.y || 0) } else if ("width" in obj) { this._set(obj.width || 0, obj.height || 0) } else if ("angle" in obj) { this._set(obj.length || 0, 0); this.setAngle(obj.angle || 0) } else { this._set(0, 0); read = 0 } } if (reading) this.__read = read; return this }, set: "#initialize", _set: function(x, y) { this.x = x; this.y = y; return this }, equals: function(point) { return this === point || point && (this.x === point.x && this.y === point.y || Array.isArray(point) && this.x === point[0] && this.y === point[1]) || false }, clone: function() { return new Point(this.x, this.y) }, toString: function() { var f = Formatter.instance; return "{ x: " + f.number(this.x) + ", y: " + f.number(this.y) + " }" }, _serialize: function(options) { var f = options.formatter; return [f.number(this.x), f.number(this.y)] }, getLength: function() { return Math.sqrt(this.x * this.x + this.y * this.y) }, setLength: function(length) { if (this.isZero()) { var angle = this._angle || 0; this._set(Math.cos(angle) * length, Math.sin(angle) * length) } else { var scale = length / this.getLength(); if (Numerical.isZero(scale)) this.getAngle(); this._set(this.x * scale, this.y * scale) } }, getAngle: function() { return this.getAngleInRadians.apply(this, arguments) * 180 / Math.PI }, setAngle: function(angle) { this.setAngleInRadians.call(this, angle * Math.PI / 180) }, getAngleInDegrees: "#getAngle", setAngleInDegrees: "#setAngle", getAngleInRadians: function() { if (!arguments.length) { return this.isZero() ? this._angle || 0 : this._angle = Math.atan2(this.y, this.x) } else { var point = Point.read(arguments), div = this.getLength() * point.getLength(); if (Numerical.isZero(div)) { return NaN } else { var a = this.dot(point) / div; return Math.acos(a < -1 ? -1 : a > 1 ? 1 : a) } } }, setAngleInRadians: function(angle) { this._angle = angle; if (!this.isZero()) { var length = this.getLength(); this._set(Math.cos(angle) * length, Math.sin(angle) * length) } }, getQuadrant: function() { return this.x >= 0 ? this.y >= 0 ? 1 : 4 : this.y >= 0 ? 2 : 3 } }, { beans: false, getDirectedAngle: function() { var point = Point.read(arguments); return Math.atan2(this.cross(point), this.dot(point)) * 180 / Math.PI }, getDistance: function() { var point = Point.read(arguments), x = point.x - this.x, y = point.y - this.y, d = x * x + y * y, squared = Base.read(arguments); return squared ? d : Math.sqrt(d) }, normalize: function(length) { if (length === undefined) length = 1; var current = this.getLength(), scale = current !== 0 ? length / current : 0, point = new Point(this.x * scale, this.y * scale); if (scale >= 0) point._angle = this._angle; return point }, rotate: function(angle, center) { if (angle === 0) return this.clone(); angle = angle * Math.PI / 180; var point = center ? this.subtract(center) : this, sin = Math.sin(angle), cos = Math.cos(angle); point = new Point(point.x * cos - point.y * sin, point.x * sin + point.y * cos); return center ? point.add(center) : point }, transform: function(matrix) { return matrix ? matrix._transformPoint(this) : this }, add: function() { var point = Point.read(arguments); return new Point(this.x + point.x, this.y + point.y) }, subtract: function() { var point = Point.read(arguments); return new Point(this.x - point.x, this.y - point.y) }, multiply: function() { var point = Point.read(arguments); return new Point(this.x * point.x, this.y * point.y) }, divide: function() { var point = Point.read(arguments); return new Point(this.x / point.x, this.y / point.y) }, modulo: function() { var point = Point.read(arguments); return new Point(this.x % point.x, this.y % point.y) }, negate: function() { return new Point(-this.x, -this.y) }, isInside: function() { return Rectangle.read(arguments).contains(this) }, isClose: function() { var point = Point.read(arguments), tolerance = Base.read(arguments); return this.getDistance(point) <= tolerance }, isCollinear: function() { var point = Point.read(arguments); return Point.isCollinear(this.x, this.y, point.x, point.y) }, isColinear: "#isCollinear", isOrthogonal: function() { var point = Point.read(arguments); return Point.isOrthogonal(this.x, this.y, point.x, point.y) }, isZero: function() { var isZero = Numerical.isZero; return isZero(this.x) && isZero(this.y) }, isNaN: function() { return isNaN(this.x) || isNaN(this.y) }, isInQuadrant: function(q) { return this.x * (q > 1 && q < 4 ? -1 : 1) >= 0 && this.y * (q > 2 ? -1 : 1) >= 0 }, dot: function() { var point = Point.read(arguments); return this.x * point.x + this.y * point.y }, cross: function() { var point = Point.read(arguments); return this.x * point.y - this.y * point.x }, project: function() { var point = Point.read(arguments), scale = point.isZero() ? 0 : this.dot(point) / point.dot(point); return new Point(point.x * scale, point.y * scale) }, statics: { min: function() { var point1 = Point.read(arguments), point2 = Point.read(arguments); return new Point(Math.min(point1.x, point2.x), Math.min(point1.y, point2.y)) }, max: function() { var point1 = Point.read(arguments), point2 = Point.read(arguments); return new Point(Math.max(point1.x, point2.x), Math.max(point1.y, point2.y)) }, random: function() { return new Point(Math.random(), Math.random()) }, isCollinear: function(x1, y1, x2, y2) { return Math.abs(x1 * y2 - y1 * x2) <= Math.sqrt((x1 * x1 + y1 * y1) * (x2 * x2 + y2 * y2)) * 1e-8 }, isOrthogonal: function(x1, y1, x2, y2) { return Math.abs(x1 * x2 + y1 * y2) <= Math.sqrt((x1 * x1 + y1 * y1) * (x2 * x2 + y2 * y2)) * 1e-8 } } }, Base.each(["round", "ceil", "floor", "abs"], function(key) { var op = Math[key]; this[key] = function() { return new Point(op(this.x), op(this.y)) } }, {})); var LinkedPoint = Point.extend({ initialize: function Point(x, y, owner, setter) { this._x = x; this._y = y; this._owner = owner; this._setter = setter }, _set: function(x, y, _dontNotify) { this._x = x; this._y = y; if (!_dontNotify) this._owner[this._setter](this); return this }, getX: function() { return this._x }, setX: function(x) { this._x = x; this._owner[this._setter](this) }, getY: function() { return this._y }, setY: function(y) { this._y = y; this._owner[this._setter](this) }, isSelected: function() { return !!(this._owner._selection & this._getSelection()) }, setSelected: function(selected) { this._owner._changeSelection(this._getSelection(), selected) }, _getSelection: function() { return this._setter === "setPosition" ? 4 : 0 } }); var Size = Base.extend({ _class: "Size", _readIndex: true, initialize: function Size(arg0, arg1) { var type = typeof arg0, reading = this.__read, read = 0; if (type === "number") { var hasHeight = typeof arg1 === "number"; this._set(arg0, hasHeight ? arg1 : arg0); if (reading) read = hasHeight ? 2 : 1 } else if (type === "undefined" || arg0 === null) { this._set(0, 0); if (reading) read = arg0 === null ? 1 : 0 } else { var obj = type === "string" ? arg0.split(/[\s,]+/) || [] : arg0; read = 1; if (Array.isArray(obj)) { this._set(+obj[0], +(obj.length > 1 ? obj[1] : obj[0])) } else if ("width" in obj) { this._set(obj.width || 0, obj.height || 0) } else if ("x" in obj) { this._set(obj.x || 0, obj.y || 0) } else { this._set(0, 0); read = 0 } } if (reading) this.__read = read; return this }, set: "#initialize", _set: function(width, height) { this.width = width; this.height = height; return this }, equals: function(size) { return size === this || size && (this.width === size.width && this.height === size.height || Array.isArray(size) && this.width === size[0] && this.height === size[1]) || false }, clone: function() { return new Size(this.width, this.height) }, toString: function() { var f = Formatter.instance; return "{ width: " + f.number(this.width) + ", height: " + f.number(this.height) + " }" }, _serialize: function(options) { var f = options.formatter; return [f.number(this.width), f.number(this.height)] }, add: function() { var size = Size.read(arguments); return new Size(this.width + size.width, this.height + size.height) }, subtract: function() { var size = Size.read(arguments); return new Size(this.width - size.width, this.height - size.height) }, multiply: function() { var size = Size.read(arguments); return new Size(this.width * size.width, this.height * size.height) }, divide: function() { var size = Size.read(arguments); return new Size(this.width / size.width, this.height / size.height) }, modulo: function() { var size = Size.read(arguments); return new Size(this.width % size.width, this.height % size.height) }, negate: function() { return new Size(-this.width, -this.height) }, isZero: function() { var isZero = Numerical.isZero; return isZero(this.width) && isZero(this.height) }, isNaN: function() { return isNaN(this.width) || isNaN(this.height) }, statics: { min: function(size1, size2) { return new Size(Math.min(size1.width, size2.width), Math.min(size1.height, size2.height)) }, max: function(size1, size2) { return new Size(Math.max(size1.width, size2.width), Math.max(size1.height, size2.height)) }, random: function() { return new Size(Math.random(), Math.random()) } } }, Base.each(["round", "ceil", "floor", "abs"], function(key) { var op = Math[key]; this[key] = function() { return new Size(op(this.width), op(this.height)) } }, {})); var LinkedSize = Size.extend({ initialize: function Size(width, height, owner, setter) { this._width = width; this._height = height; this._owner = owner; this._setter = setter }, _set: function(width, height, _dontNotify) { this._width = width; this._height = height; if (!_dontNotify) this._owner[this._setter](this); return this }, getWidth: function() { return this._width }, setWidth: function(width) { this._width = width; this._owner[this._setter](this) }, getHeight: function() { return this._height }, setHeight: function(height) { this._height = height; this._owner[this._setter](this) } }); var Rectangle = Base.extend({ _class: "Rectangle", _readIndex: true, beans: true, initialize: function Rectangle(arg0, arg1, arg2, arg3) { var type = typeof arg0, read; if (type === "number") { this._set(arg0, arg1, arg2, arg3); read = 4 } else if (type === "undefined" || arg0 === null) { this._set(0, 0, 0, 0); read = arg0 === null ? 1 : 0 } else if (arguments.length === 1) { if (Array.isArray(arg0)) { this._set.apply(this, arg0); read = 1 } else if (arg0.x !== undefined || arg0.width !== undefined) { this._set(arg0.x || 0, arg0.y || 0, arg0.width || 0, arg0.height || 0); read = 1 } else if (arg0.from === undefined && arg0.to === undefined) { this._set(0, 0, 0, 0); Base.filter(this, arg0); read = 1 } } if (read === undefined) { var frm = Point.readNamed(arguments, "from"), next = Base.peek(arguments), x = frm.x, y = frm.y, width, height; if (next && next.x !== undefined || Base.hasNamed(arguments, "to")) { var to = Point.readNamed(arguments, "to"); width = to.x - x; height = to.y - y; if (width < 0) { x = to.x; width = -width } if (height < 0) { y = to.y; height = -height } } else { var size = Size.read(arguments); width = size.width; height = size.height } this._set(x, y, width, height); read = arguments.__index; var filtered = arguments.__filtered; if (filtered) this.__filtered = filtered } if (this.__read) this.__read = read; return this }, set: "#initialize", _set: function(x, y, width, height) { this.x = x; this.y = y; this.width = width; this.height = height; return this }, clone: function() { return new Rectangle(this.x, this.y, this.width, this.height) }, equals: function(rect) { var rt = Base.isPlainValue(rect) ? Rectangle.read(arguments) : rect; return rt === this || rt && this.x === rt.x && this.y === rt.y && this.width === rt.width && this.height === rt.height || false }, toString: function() { var f = Formatter.instance; return "{ x: " + f.number(this.x) + ", y: " + f.number(this.y) + ", width: " + f.number(this.width) + ", height: " + f.number(this.height) + " }" }, _serialize: function(options) { var f = options.formatter; return [f.number(this.x), f.number(this.y), f.number(this.width), f.number(this.height)] }, getPoint: function(_dontLink) { var ctor = _dontLink ? Point : LinkedPoint; return new ctor(this.x, this.y, this, "setPoint") }, setPoint: function() { var point = Point.read(arguments); this.x = point.x; this.y = point.y }, getSize: function(_dontLink) { var ctor = _dontLink ? Size : LinkedSize; return new ctor(this.width, this.height, this, "setSize") }, _fw: 1, _fh: 1, setSize: function() { var size = Size.read(arguments), sx = this._sx, sy = this._sy, w = size.width, h = size.height; if (sx) { this.x += (this.width - w) * sx } if (sy) { this.y += (this.height - h) * sy } this.width = w; this.height = h; this._fw = this._fh = 1 }, getLeft: function() { return this.x }, setLeft: function(left) { if (!this._fw) { var amount = left - this.x; this.width -= this._sx === .5 ? amount * 2 : amount } this.x = left; this._sx = this._fw = 0 }, getTop: function() { return this.y }, setTop: function(top) { if (!this._fh) { var amount = top - this.y; this.height -= this._sy === .5 ? amount * 2 : amount } this.y = top; this._sy = this._fh = 0 }, getRight: function() { return this.x + this.width }, setRight: function(right) { if (!this._fw) { var amount = right - this.x; this.width = this._sx === .5 ? amount * 2 : amount } this.x = right - this.width; this._sx = 1; this._fw = 0 }, getBottom: function() { return this.y + this.height }, setBottom: function(bottom) { if (!this._fh) { var amount = bottom - this.y; this.height = this._sy === .5 ? amount * 2 : amount } this.y = bottom - this.height; this._sy = 1; this._fh = 0 }, getCenterX: function() { return this.x + this.width / 2 }, setCenterX: function(x) { if (this._fw || this._sx === .5) { this.x = x - this.width / 2 } else { if (this._sx) { this.x += (x - this.x) * 2 * this._sx } this.width = (x - this.x) * 2 } this._sx = .5; this._fw = 0 }, getCenterY: function() { return this.y + this.height / 2 }, setCenterY: function(y) { if (this._fh || this._sy === .5) { this.y = y - this.height / 2 } else { if (this._sy) { this.y += (y - this.y) * 2 * this._sy } this.height = (y - this.y) * 2 } this._sy = .5; this._fh = 0 }, getCenter: function(_dontLink) { var ctor = _dontLink ? Point : LinkedPoint; return new ctor(this.getCenterX(), this.getCenterY(), this, "setCenter") }, setCenter: function() { var point = Point.read(arguments); this.setCenterX(point.x); this.setCenterY(point.y); return this }, getArea: function() { return this.width * this.height }, isEmpty: function() { return this.width === 0 || this.height === 0 }, contains: function(arg) { return arg && arg.width !== undefined || (Array.isArray(arg) ? arg : arguments).length === 4 ? this._containsRectangle(Rectangle.read(arguments)) : this._containsPoint(Point.read(arguments)) }, _containsPoint: function(point) { var x = point.x, y = point.y; return x >= this.x && y >= this.y && x <= this.x + this.width && y <= this.y + this.height }, _containsRectangle: function(rect) { var x = rect.x, y = rect.y; return x >= this.x && y >= this.y && x + rect.width <= this.x + this.width && y + rect.height <= this.y + this.height }, intersects: function() { var rect = Rectangle.read(arguments), epsilon = Base.read(arguments) || 0; return rect.x + rect.width > this.x - epsilon && rect.y + rect.height > this.y - epsilon && rect.x < this.x + this.width + epsilon && rect.y < this.y + this.height + epsilon }, intersect: function() { var rect = Rectangle.read(arguments), x1 = Math.max(this.x, rect.x), y1 = Math.max(this.y, rect.y), x2 = Math.min(this.x + this.width, rect.x + rect.width), y2 = Math.min(this.y + this.height, rect.y + rect.height); return new Rectangle(x1, y1, x2 - x1, y2 - y1) }, unite: function() { var rect = Rectangle.read(arguments), x1 = Math.min(this.x, rect.x), y1 = Math.min(this.y, rect.y), x2 = Math.max(this.x + this.width, rect.x + rect.width), y2 = Math.max(this.y + this.height, rect.y + rect.height); return new Rectangle(x1, y1, x2 - x1, y2 - y1) }, include: function() { var point = Point.read(arguments); var x1 = Math.min(this.x, point.x), y1 = Math.min(this.y, point.y), x2 = Math.max(this.x + this.width, point.x), y2 = Math.max(this.y + this.height, point.y); return new Rectangle(x1, y1, x2 - x1, y2 - y1) }, expand: function() { var amount = Size.read(arguments), hor = amount.width, ver = amount.height; return new Rectangle(this.x - hor / 2, this.y - ver / 2, this.width + hor, this.height + ver) }, scale: function(hor, ver) { return this.expand(this.width * hor - this.width, this.height * (ver === undefined ? hor : ver) - this.height) } }, Base.each([ ["Top", "Left"], ["Top", "Right"], ["Bottom", "Left"], ["Bottom", "Right"], ["Left", "Center"], ["Top", "Center"], ["Right", "Center"], ["Bottom", "Center"] ], function(parts, index) { var part = parts.join(""), xFirst = /^[RL]/.test(part); if (index >= 4) parts[1] += xFirst ? "Y" : "X"; var x = parts[xFirst ? 0 : 1], y = parts[xFirst ? 1 : 0], getX = "get" + x, getY = "get" + y, setX = "set" + x, setY = "set" + y, get = "get" + part, set = "set" + part; this[get] = function(_dontLink) { var ctor = _dontLink ? Point : LinkedPoint; return new ctor(this[getX](), this[getY](), this, set) }; this[set] = function() { var point = Point.read(arguments); this[setX](point.x); this[setY](point.y) } }, { beans: true })); var LinkedRectangle = Rectangle.extend({ initialize: function Rectangle(x, y, width, height, owner, setter) { this._set(x, y, width, height, true); this._owner = owner; this._setter = setter }, _set: function(x, y, width, height, _dontNotify) { this._x = x; this._y = y; this._width = width; this._height = height; if (!_dontNotify) this._owner[this._setter](this); return this } }, new function() { var proto = Rectangle.prototype; return Base.each(["x", "y", "width", "height"], function(key) { var part = Base.capitalize(key), internal = "_" + key; this["get" + part] = function() { return this[internal] }; this["set" + part] = function(value) { this[internal] = value; if (!this._dontNotify) this._owner[this._setter](this) } }, Base.each(["Point", "Size", "Center", "Left", "Top", "Right", "Bottom", "CenterX", "CenterY", "TopLeft", "TopRight", "BottomLeft", "BottomRight", "LeftCenter", "TopCenter", "RightCenter", "BottomCenter"], function(key) { var name = "set" + key; this[name] = function() { this._dontNotify = true; proto[name].apply(this, arguments); this._dontNotify = false; this._owner[this._setter](this) } }, { isSelected: function() { return !!(this._owner._selection & 2) }, setSelected: function(selected) { var owner = this._owner; if (owner._changeSelection) { owner._changeSelection(2, selected) } } })) }); var Matrix = Base.extend({ _class: "Matrix", initialize: function Matrix(arg, _dontNotify) { var count = arguments.length, ok = true; if (count >= 6) { this._set.apply(this, arguments) } else if (count === 1 || count === 2) { if (arg instanceof Matrix) { this._set(arg._a, arg._b, arg._c, arg._d, arg._tx, arg._ty, _dontNotify) } else if (Array.isArray(arg)) { this._set.apply(this, _dontNotify ? arg.concat([_dontNotify]) : arg) } else { ok = false } } else if (!count) { this.reset() } else { ok = false } if (!ok) { throw new Error("Unsupported matrix parameters") } return this }, set: "#initialize", _set: function(a, b, c, d, tx, ty, _dontNotify) { this._a = a; this._b = b; this._c = c; this._d = d; this._tx = tx; this._ty = ty; if (!_dontNotify) this._changed(); return this }, _serialize: function(options, dictionary) { return Base.serialize(this.getValues(), options, true, dictionary) }, _changed: function() { var owner = this._owner; if (owner) { if (owner._applyMatrix) { owner.transform(null, true) } else { owner._changed(25) } } }, clone: function() { return new Matrix(this._a, this._b, this._c, this._d, this._tx, this._ty) }, equals: function(mx) { return mx === this || mx && this._a === mx._a && this._b === mx._b && this._c === mx._c && this._d === mx._d && this._tx === mx._tx && this._ty === mx._ty }, toString: function() { var f = Formatter.instance; return "[[" + [f.number(this._a), f.number(this._c), f.number(this._tx)].join(", ") + "], [" + [f.number(this._b), f.number(this._d), f.number(this._ty)].join(", ") + "]]" }, reset: function(_dontNotify) { this._a = this._d = 1; this._b = this._c = this._tx = this._ty = 0; if (!_dontNotify) this._changed(); return this }, apply: function(recursively, _setApplyMatrix) { var owner = this._owner; if (owner) { owner.transform(null, true, Base.pick(recursively, true), _setApplyMatrix); return this.isIdentity() } return false }, translate: function() { var point = Point.read(arguments), x = point.x, y = point.y; this._tx += x * this._a + y * this._c; this._ty += x * this._b + y * this._d; this._changed(); return this }, scale: function() { var scale = Point.read(arguments), center = Point.read(arguments, 0, { readNull: true }); if (center) this.translate(center); this._a *= scale.x; this._b *= scale.x; this._c *= scale.y; this._d *= scale.y; if (center) this.translate(center.negate()); this._changed(); return this }, rotate: function(angle) { angle *= Math.PI / 180; var center = Point.read(arguments, 1), x = center.x, y = center.y, cos = Math.cos(angle), sin = Math.sin(angle), tx = x - x * cos + y * sin, ty = y - x * sin - y * cos, a = this._a, b = this._b, c = this._c, d = this._d; this._a = cos * a + sin * c; this._b = cos * b + sin * d; this._c = -sin * a + cos * c; this._d = -sin * b + cos * d; this._tx += tx * a + ty * c; this._ty += tx * b + ty * d; this._changed(); return this }, shear: function() { var shear = Point.read(arguments), center = Point.read(arguments, 0, { readNull: true }); if (center) this.translate(center); var a = this._a, b = this._b; this._a += shear.y * this._c; this._b += shear.y * this._d; this._c += shear.x * a; this._d += shear.x * b; if (center) this.translate(center.negate()); this._changed(); return this }, skew: function() { var skew = Point.read(arguments), center = Point.read(arguments, 0, { readNull: true }), toRadians = Math.PI / 180, shear = new Point(Math.tan(skew.x * toRadians), Math.tan(skew.y * toRadians)); return this.shear(shear, center) }, append: function(mx, _dontNotify) { if (mx) { var a1 = this._a, b1 = this._b, c1 = this._c, d1 = this._d, a2 = mx._a, b2 = mx._c, c2 = mx._b, d2 = mx._d, tx2 = mx._tx, ty2 = mx._ty; this._a = a2 * a1 + c2 * c1; this._c = b2 * a1 + d2 * c1; this._b = a2 * b1 + c2 * d1; this._d = b2 * b1 + d2 * d1; this._tx += tx2 * a1 + ty2 * c1; this._ty += tx2 * b1 + ty2 * d1; if (!_dontNotify) this._changed() } return this }, prepend: function(mx, _dontNotify) { if (mx) { var a1 = this._a, b1 = this._b, c1 = this._c, d1 = this._d, tx1 = this._tx, ty1 = this._ty, a2 = mx._a, b2 = mx._c, c2 = mx._b, d2 = mx._d, tx2 = mx._tx, ty2 = mx._ty; this._a = a2 * a1 + b2 * b1; this._c = a2 * c1 + b2 * d1; this._b = c2 * a1 + d2 * b1; this._d = c2 * c1 + d2 * d1; this._tx = a2 * tx1 + b2 * ty1 + tx2; this._ty = c2 * tx1 + d2 * ty1 + ty2; if (!_dontNotify) this._changed() } return this }, appended: function(mx) { return this.clone().append(mx) }, prepended: function(mx) { return this.clone().prepend(mx) }, invert: function() { var a = this._a, b = this._b, c = this._c, d = this._d, tx = this._tx, ty = this._ty, det = a * d - b * c, res = null; if (det && !isNaN(det) && isFinite(tx) && isFinite(ty)) { this._a = d / det; this._b = -b / det; this._c = -c / det; this._d = a / det; this._tx = (c * ty - d * tx) / det; this._ty = (b * tx - a * ty) / det; res = this } return res }, inverted: function() { return this.clone().invert() }, concatenate: "#append", preConcatenate: "#prepend", chain: "#appended", _shiftless: function() { return new Matrix(this._a, this._b, this._c, this._d, 0, 0) }, _orNullIfIdentity: function() { return this.isIdentity() ? null : this }, isIdentity: function() { return this._a === 1 && this._b === 0 && this._c === 0 && this._d === 1 && this._tx === 0 && this._ty === 0 }, isInvertible: function() { var det = this._a * this._d - this._c * this._b; return det && !isNaN(det) && isFinite(this._tx) && isFinite(this._ty) }, isSingular: function() { return !this.isInvertible() }, transform: function(src, dst, count) { return arguments.length < 3 ? this._transformPoint(Point.read(arguments)) : this._transformCoordinates(src, dst, count) }, _transformPoint: function(point, dest, _dontNotify) { var x = point.x, y = point.y; if (!dest) dest = new Point; return dest._set(x * this._a + y * this._c + this._tx, x * this._b + y * this._d + this._ty, _dontNotify) }, _transformCoordinates: function(src, dst, count) { for (var i = 0, max = 2 * count; i < max; i += 2) { var x = src[i], y = src[i + 1]; dst[i] = x * this._a + y * this._c + this._tx; dst[i + 1] = x * this._b + y * this._d + this._ty } return dst }, _transformCorners: function(rect) { var x1 = rect.x, y1 = rect.y, x2 = x1 + rect.width, y2 = y1 + rect.height, coords = [x1, y1, x2, y1, x2, y2, x1, y2]; return this._transformCoordinates(coords, coords, 4) }, _transformBounds: function(bounds, dest, _dontNotify) { var coords = this._transformCorners(bounds), min = coords.slice(0, 2), max = min.slice(); for (var i = 2; i < 8; i++) { var val = coords[i], j = i & 1; if (val < min[j]) { min[j] = val } else if (val > max[j]) { max[j] = val } } if (!dest) dest = new Rectangle; return dest._set(min[0], min[1], max[0] - min[0], max[1] - min[1], _dontNotify) }, inverseTransform: function() { return this._inverseTransform(Point.read(arguments)) }, _inverseTransform: function(point, dest, _dontNotify) { var a = this._a, b = this._b, c = this._c, d = this._d, tx = this._tx, ty = this._ty, det = a * d - b * c, res = null; if (det && !isNaN(det) && isFinite(tx) && isFinite(ty)) { var x = point.x - this._tx, y = point.y - this._ty; if (!dest) dest = new Point; res = dest._set((x * d - y * c) / det, (y * a - x * b) / det, _dontNotify) } return res }, decompose: function() { var a = this._a, b = this._b, c = this._c, d = this._d, det = a * d - b * c, sqrt = Math.sqrt, atan2 = Math.atan2, degrees = 180 / Math.PI, rotate, scale, skew; if (a !== 0 || b !== 0) { var r = sqrt(a * a + b * b); rotate = Math.acos(a / r) * (b > 0 ? 1 : -1); scale = [r, det / r]; skew = [atan2(a * c + b * d, r * r), 0] } else if (c !== 0 || d !== 0) { var s = sqrt(c * c + d * d); rotate = Math.asin(c / s) * (d > 0 ? 1 : -1); scale = [det / s, s]; skew = [0, atan2(a * c + b * d, s * s)] } else { rotate = 0; skew = scale = [0, 0] } return { translation: this.getTranslation(), rotation: rotate * degrees, scaling: new Point(scale), skewing: new Point(skew[0] * degrees, skew[1] * degrees) } }, getValues: function() { return [this._a, this._b, this._c, this._d, this._tx, this._ty] }, getTranslation: function() { return new Point(this._tx, this._ty) }, getScaling: function() { return (this.decompose() || {}).scaling }, getRotation: function() { return (this.decompose() || {}).rotation }, applyToContext: function(ctx) { if (!this.isIdentity()) { ctx.transform(this._a, this._b, this._c, this._d, this._tx, this._ty) } } }, Base.each(["a", "b", "c", "d", "tx", "ty"], function(key) { var part = Base.capitalize(key), prop = "_" + key; this["get" + part] = function() { return this[prop] }; this["set" + part] = function(value) { this[prop] = value; this._changed() } }, {})); var Line = Base.extend({ _class: "Line", initialize: function Line(arg0, arg1, arg2, arg3, arg4) { var asVector = false; if (arguments.length >= 4) { this._px = arg0; this._py = arg1; this._vx = arg2; this._vy = arg3; asVector = arg4 } else { this._px = arg0.x; this._py = arg0.y; this._vx = arg1.x; this._vy = arg1.y; asVector = arg2 } if (!asVector) { this._vx -= this._px; this._vy -= this._py } }, getPoint: function() { return new Point(this._px, this._py) }, getVector: function() { return new Point(this._vx, this._vy) }, getLength: function() { return this.getVector().getLength() }, intersect: function(line, isInfinite) { return Line.intersect(this._px, this._py, this._vx, this._vy, line._px, line._py, line._vx, line._vy, true, isInfinite) }, getSide: function(point, isInfinite) { return Line.getSide(this._px, this._py, this._vx, this._vy, point.x, point.y, true, isInfinite) }, getDistance: function(point) { return Math.abs(this.getSignedDistance(point)) }, getSignedDistance: function(point) { return Line.getSignedDistance(this._px, this._py, this._vx, this._vy, point.x, point.y, true) }, isCollinear: function(line) { return Point.isCollinear(this._vx, this._vy, line._vx, line._vy) }, isOrthogonal: function(line) { return Point.isOrthogonal(this._vx, this._vy, line._vx, line._vy) }, statics: { intersect: function(p1x, p1y, v1x, v1y, p2x, p2y, v2x, v2y, asVector, isInfinite) { if (!asVector) { v1x -= p1x; v1y -= p1y; v2x -= p2x; v2y -= p2y } var cross = v1x * v2y - v1y * v2x; if (!Numerical.isZero(cross)) { var dx = p1x - p2x, dy = p1y - p2y, u1 = (v2x * dy - v2y * dx) / cross, u2 = (v1x * dy - v1y * dx) / cross, epsilon = 1e-12, uMin = -epsilon, uMax = 1 + epsilon; if (isInfinite || uMin < u1 && u1 < uMax && uMin < u2 && u2 < uMax) { if (!isInfinite) { u1 = u1 <= 0 ? 0 : u1 >= 1 ? 1 : u1 } return new Point(p1x + u1 * v1x, p1y + u1 * v1y) } } }, getSide: function(px, py, vx, vy, x, y, asVector, isInfinite) { if (!asVector) { vx -= px; vy -= py } var v2x = x - px, v2y = y - py, ccw = v2x * vy - v2y * vx; if (!isInfinite && Numerical.isZero(ccw)) { ccw = (v2x * vx + v2x * vx) / (vx * vx + vy * vy); if (ccw >= 0 && ccw <= 1) ccw = 0 } return ccw < 0 ? -1 : ccw > 0 ? 1 : 0 }, getSignedDistance: function(px, py, vx, vy, x, y, asVector) { if (!asVector) { vx -= px; vy -= py } return vx === 0 ? vy > 0 ? x - px : px - x : vy === 0 ? vx < 0 ? y - py : py - y : ((x - px) * vy - (y - py) * vx) / Math.sqrt(vx * vx + vy * vy) }, getDistance: function(px, py, vx, vy, x, y, asVector) { return Math.abs(Line.getSignedDistance(px, py, vx, vy, x, y, asVector)) } } }); var Project = PaperScopeItem.extend({ _class: "Project", _list: "projects", _reference: "project", _compactSerialize: true, initialize: function Project(element) { PaperScopeItem.call(this, true); this._children = []; this._namedChildren = {}; this._activeLayer = null; this._currentStyle = new Style(null, null, this); this._view = View.create(this, element || CanvasProvider.getCanvas(1, 1)); this._selectionItems = {}; this._selectionCount = 0; this._updateVersion = 0 }, _serialize: function(options, dictionary) { return Base.serialize(this._children, options, true, dictionary) }, _changed: function(flags, item) { if (flags & 1) { var view = this._view; if (view) { view._needsUpdate = true; if (!view._requested && view._autoUpdate) view.requestUpdate() } } var changes = this._changes; if (changes && item) { var changesById = this._changesById, id = item._id, entry = changesById[id]; if (entry) { entry.flags |= flags } else { changes.push(changesById[id] = { item: item, flags: flags }) } } }, clear: function() { var children = this._children; for (var i = children.length - 1; i >= 0; i--) children[i].remove() }, isEmpty: function() { return !this._children.length }, remove: function remove() { if (!remove.base.call(this)) return false; if (this._view) this._view.remove(); return true }, getView: function() { return this._view }, getCurrentStyle: function() { return this._currentStyle }, setCurrentStyle: function(style) { this._currentStyle.set(style) }, getIndex: function() { return this._index }, getOptions: function() { return this._scope.settings }, getLayers: function() { return this._children }, getActiveLayer: function() { return this._activeLayer || new Layer({ project: this, insert: true }) }, getSymbolDefinitions: function() { var definitions = [], ids = {}; this.getItems({ class: SymbolItem, match: function(item) { var definition = item._definition, id = definition._id; if (!ids[id]) { ids[id] = true; definitions.push(definition) } return false } }); return definitions }, getSymbols: "getSymbolDefinitions", getSelectedItems: function() { var selectionItems = this._selectionItems, items = []; for (var id in selectionItems) { var item = selectionItems[id], selection = item._selection; if (selection & 1 && item.isInserted()) { items.push(item) } else if (!selection) { this._updateSelection(item) } } return items }, _updateSelection: function(item) { var id = item._id, selectionItems = this._selectionItems; if (item._selection) { if (selectionItems[id] !== item) { this._selectionCount++; selectionItems[id] = item } } else if (selectionItems[id] === item) { this._selectionCount--; delete selectionItems[id] } }, selectAll: function() { var children = this._children; for (var i = 0, l = children.length; i < l; i++) children[i].setFullySelected(true) }, deselectAll: function() { var selectionItems = this._selectionItems; for (var i in selectionItems) selectionItems[i].setFullySelected(false) }, addLayer: function(layer) { return this.insertLayer(undefined, layer) }, insertLayer: function(index, layer) { if (layer instanceof Layer) { layer._remove(false, true); Base.splice(this._children, [layer], index, 0); layer._setProject(this, true); var name = layer._name; if (name) layer.setName(name); if (this._changes) layer._changed(5); if (!this._activeLayer) this._activeLayer = layer } else { layer = null } return layer }, _insertItem: function(index, item, _created) { item = this.insertLayer(index, item) || (this._activeLayer || this._insertItem(undefined, new Layer(Item.NO_INSERT), true)).insertChild(index, item); if (_created && item.activate) item.activate(); return item }, getItems: function(options) { return Item._getItems(this, options) }, getItem: function(options) { return Item._getItems(this, options, null, null, true)[0] || null }, importJSON: function(json) { this.activate(); var layer = this._activeLayer; return Base.importJSON(json, layer && layer.isEmpty() && layer) }, removeOn: function(type) { var sets = this._removeSets; if (sets) { if (type === "mouseup") sets.mousedrag = null; var set = sets[type]; if (set) { for (var id in set) { var item = set[id]; for (var key in sets) { var other = sets[key]; if (other && other != set) delete other[item._id] } item.remove() } sets[type] = null } } }, draw: function(ctx, matrix, pixelRatio) { this._updateVersion++; ctx.save(); matrix.applyToContext(ctx); var children = this._children, param = new Base({ offset: new Point(0, 0), pixelRatio: pixelRatio, viewMatrix: matrix.isIdentity() ? null : matrix, matrices: [new Matrix], updateMatrix: true }); for (var i = 0, l = children.length; i < l; i++) { children[i].draw(ctx, param) } ctx.restore(); if (this._selectionCount > 0) { ctx.save(); ctx.strokeWidth = 1; var items = this._selectionItems, size = this._scope.settings.handleSize, version = this._updateVersion; for (var id in items) { items[id]._drawSelection(ctx, matrix, size, items, version) } ctx.restore() } } }); var Item = Base.extend(Emitter, { statics: { extend: function extend(src) { if (src._serializeFields) src._serializeFields = Base.set({}, this.prototype._serializeFields, src._serializeFields); return extend.base.apply(this, arguments) }, NO_INSERT: { insert: false } }, _class: "Item", _name: null, _applyMatrix: true, _canApplyMatrix: true, _canScaleStroke: false, _pivot: null, _visible: true, _blendMode: "normal", _opacity: 1, _locked: false, _guide: false, _clipMask: false, _selection: 0, _selectBounds: true, _selectChildren: false, _serializeFields: { name: null, applyMatrix: null, matrix: new Matrix, pivot: null, visible: true, blendMode: "normal", opacity: 1, locked: false, guide: false, clipMask: false, selected: false, data: {} }, _prioritize: ["applyMatrix"] }, new function() { var handlers = ["onMouseDown", "onMouseUp", "onMouseDrag", "onClick", "onDoubleClick", "onMouseMove", "onMouseEnter", "onMouseLeave"]; return Base.each(handlers, function(name) { this._events[name] = { install: function(type) { this.getView()._countItemEvent(type, 1) }, uninstall: function(type) { this.getView()._countItemEvent(type, -1) } } }, { _events: { onFrame: { install: function() { this.getView()._animateItem(this, true) }, uninstall: function() { this.getView()._animateItem(this, false) } }, onLoad: {}, onError: {} }, statics: { _itemHandlers: handlers } }) }, { initialize: function Item() {}, _initialize: function(props, point) { var hasProps = props && Base.isPlainObject(props), internal = hasProps && props.internal === true, matrix = this._matrix = new Matrix, project = hasProps && props.project || paper.project, settings = paper.settings; this._id = internal ? null : UID.get(); this._parent = this._index = null; this._applyMatrix = this._canApplyMatrix && settings.applyMatrix; if (point) matrix.translate(point); matrix._owner = this; this._style = new Style(project._currentStyle, this, project); if (internal || hasProps && props.insert == false || !settings.insertItems && !(hasProps && props.insert === true)) { this._setProject(project) } else { (hasProps && props.parent || project)._insertItem(undefined, this, true) } if (hasProps && props !== Item.NO_INSERT) { this.set(props, { internal: true, insert: true, project: true, parent: true }) } return hasProps }, _serialize: function(options, dictionary) { var props = {}, that = this; function serialize(fields) { for (var key in fields) { var value = that[key]; if (!Base.equals(value, key === "leading" ? fields.fontSize * 1.2 : fields[key])) { props[key] = Base.serialize(value, options, key !== "data", dictionary) } } } serialize(this._serializeFields); if (!(this instanceof Group)) serialize(this._style._defaults); return [this._class, props] }, _changed: function(flags) { var symbol = this._symbol, cacheParent = this._parent || symbol, project = this._project; if (flags & 8) { this._bounds = this._position = this._decomposed = undefined } if (flags & 16) { this._globalMatrix = undefined } if (cacheParent && flags & 72) { Item._clearBoundsCache(cacheParent) } if (flags & 2) { Item._clearBoundsCache(this) } if (project) project._changed(flags, this); if (symbol) symbol._changed(flags) }, getId: function() { return this._id }, getName: function() { return this._name }, setName: function(name) { if (this._name) this._removeNamed(); if (name === +name + "") throw new Error("Names consisting only of numbers are not supported."); var owner = this._getOwner(); if (name && owner) { var children = owner._children, namedChildren = owner._namedChildren; (namedChildren[name] = namedChildren[name] || []).push(this); if (!(name in children)) children[name] = this } this._name = name || undefined; this._changed(256) }, getStyle: function() { return this._style }, setStyle: function(style) { this.getStyle().set(style) } }, Base.each(["locked", "visible", "blendMode", "opacity", "guide"], function(name) { var part = Base.capitalize(name), key = "_" + name, flags = { locked: 256, visible: 265 }; this["get" + part] = function() { return this[key] }; this["set" + part] = function(value) { if (value != this[key]) { this[key] = value; this._changed(flags[name] || 257) } } }, {}), { beans: true, getSelection: function() { return this._selection }, setSelection: function(selection) { if (selection !== this._selection) { this._selection = selection; var project = this._project; if (project) { project._updateSelection(this); this._changed(257) } } }, _changeSelection: function(flag, selected) { var selection = this._selection; this.setSelection(selected ? selection | flag : selection & ~flag) }, isSelected: function() { if (this._selectChildren) { var children = this._children; for (var i = 0, l = children.length; i < l; i++) if (children[i].isSelected()) return true } return !!(this._selection & 1) }, setSelected: function(selected) { if (this._selectChildren) { var children = this._children; for (var i = 0, l = children.length; i < l; i++) children[i].setSelected(selected) } this._changeSelection(1, selected) }, isFullySelected: function() { var children = this._children, selected = !!(this._selection & 1); if (children && selected) { for (var i = 0, l = children.length; i < l; i++) if (!children[i].isFullySelected()) return false; return true } return selected }, setFullySelected: function(selected) { var children = this._children; if (children) { for (var i = 0, l = children.length; i < l; i++) children[i].setFullySelected(selected) } this._changeSelection(1, selected) }, isClipMask: function() { return this._clipMask }, setClipMask: function(clipMask) { if (this._clipMask != (clipMask = !!clipMask)) { this._clipMask = clipMask; if (clipMask) { this.setFillColor(null); this.setStrokeColor(null) } this._changed(257); if (this._parent) this._parent._changed(2048) } }, getData: function() { if (!this._data) this._data = {}; return this._data }, setData: function(data) { this._data = data }, getPosition: function(_dontLink) { var ctor = _dontLink ? Point : LinkedPoint; var position = this._position || (this._position = this._getPositionFromBounds()); return new ctor(position.x, position.y, this, "setPosition") }, setPosition: function() { this.translate(Point.read(arguments).subtract(this.getPosition(true))) }, _getPositionFromBounds: function(bounds) { return this._pivot ? this._matrix._transformPoint(this._pivot) : (bounds || this.getBounds()).getCenter(true) }, getPivot: function() { var pivot = this._pivot; return pivot ? new LinkedPoint(pivot.x, pivot.y, this, "setPivot") : null }, setPivot: function() { this._pivot = Point.read(arguments, 0, { clone: true, readNull: true }); this._position = undefined } }, Base.each({ getStrokeBounds: { stroke: true }, getHandleBounds: { handle: true }, getInternalBounds: { internal: true } }, function(options, key) { this[key] = function(matrix) { return this.getBounds(matrix, options) } }, { beans: true, getBounds: function(matrix, options) { var hasMatrix = options || matrix instanceof Matrix, opts = Base.set({}, hasMatrix ? options : matrix, this._boundsOptions); if (!opts.stroke || this.getStrokeScaling()) opts.cacheItem = this; var rect = this._getCachedBounds(hasMatrix && matrix, opts).rect; return !arguments.length ? new LinkedRectangle(rect.x, rect.y, rect.width, rect.height, this, "setBounds") : rect }, setBounds: function() { var rect = Rectangle.read(arguments), bounds = this.getBounds(), _matrix = this._matrix, matrix = new Matrix, center = rect.getCenter(); matrix.translate(center); if (rect.width != bounds.width || rect.height != bounds.height) { if (!_matrix.isInvertible()) { _matrix.set(_matrix._backup || (new Matrix).translate(_matrix.getTranslation())); bounds = this.getBounds() } matrix.scale(bounds.width !== 0 ? rect.width / bounds.width : 0, bounds.height !== 0 ? rect.height / bounds.height : 0) } center = bounds.getCenter(); matrix.translate(-center.x, -center.y); this.transform(matrix) }, _getBounds: function(matrix, options) { var children = this._children; if (!children || !children.length) return new Rectangle; Item._updateBoundsCache(this, options.cacheItem); return Item._getBounds(children, matrix, options) }, _getBoundsCacheKey: function(options, internal) { return [options.stroke ? 1 : 0, options.handle ? 1 : 0, internal ? 1 : 0].join("") }, _getCachedBounds: function(matrix, options, noInternal) { matrix = matrix && matrix._orNullIfIdentity(); var internal = options.internal && !noInternal, cacheItem = options.cacheItem, _matrix = internal ? null : this._matrix._orNullIfIdentity(), cacheKey = cacheItem && (!matrix || matrix.equals(_matrix)) && this._getBoundsCacheKey(options, internal), bounds = this._bounds; Item._updateBoundsCache(this._parent || this._symbol, cacheItem); if (cacheKey && bounds && cacheKey in bounds) { var cached = bounds[cacheKey]; return { rect: cached.rect.clone(), nonscaling: cached.nonscaling } } var res = this._getBounds(matrix || _matrix, options), rect = res.rect || res, style = this._style, nonscaling = res.nonscaling || style.hasStroke() && !style.getStrokeScaling(); if (cacheKey) { if (!bounds) { this._bounds = bounds = {} } var cached = bounds[cacheKey] = { rect: rect.clone(), nonscaling: nonscaling, internal: internal } } return { rect: rect, nonscaling: nonscaling } }, _getStrokeMatrix: function(matrix, options) { var parent = this.getStrokeScaling() ? null : options && options.internal ? this : this._parent || this._symbol && this._symbol._item, mx = parent ? parent.getViewMatrix().invert() : matrix; return mx && mx._shiftless() }, statics: { _updateBoundsCache: function(parent, item) { if (parent && item) { var id = item._id, ref = parent._boundsCache = parent._boundsCache || { ids: {}, list: [] }; if (!ref.ids[id]) { ref.list.push(item); ref.ids[id] = item } } }, _clearBoundsCache: function(item) { var cache = item._boundsCache; if (cache) { item._bounds = item._position = item._boundsCache = undefined; for (var i = 0, list = cache.list, l = list.length; i < l; i++) { var other = list[i]; if (other !== item) { other._bounds = other._position = undefined; if (other._boundsCache) Item._clearBoundsCache(other) } } } }, _getBounds: function(items, matrix, options) { var x1 = Infinity, x2 = -x1, y1 = x1, y2 = x2, nonscaling = false; options = options || {}; for (var i = 0, l = items.length; i < l; i++) { var item = items[i]; if (item._visible && !item.isEmpty()) { var bounds = item._getCachedBounds(matrix && matrix.appended(item._matrix), options, true), rect = bounds.rect; x1 = Math.min(rect.x, x1); y1 = Math.min(rect.y, y1); x2 = Math.max(rect.x + rect.width, x2); y2 = Math.max(rect.y + rect.height, y2); if (bounds.nonscaling) nonscaling = true } } return { rect: isFinite(x1) ? new Rectangle(x1, y1, x2 - x1, y2 - y1) : new Rectangle, nonscaling: nonscaling } } } }), { beans: true, _decompose: function() { return this._applyMatrix ? null : this._decomposed || (this._decomposed = this._matrix.decompose()) }, getRotation: function() { var decomposed = this._decompose(); return decomposed ? decomposed.rotation : 0 }, setRotation: function(rotation) { var current = this.getRotation(); if (current != null && rotation != null) { var decomposed = this._decomposed; this.rotate(rotation - current); if (decomposed) { decomposed.rotation = rotation; this._decomposed = decomposed } } }, getScaling: function() { var decomposed = this._decompose(), s = decomposed && decomposed.scaling; return new LinkedPoint(s ? s.x : 1, s ? s.y : 1, this, "setScaling") }, setScaling: function() { var current = this.getScaling(), scaling = Point.read(arguments, 0, { clone: true, readNull: true }); if (current && scaling && !current.equals(scaling)) { var rotation = this.getRotation(), decomposed = this._decomposed, matrix = new Matrix, center = this.getPosition(true); matrix.translate(center); if (rotation) matrix.rotate(rotation); matrix.scale(scaling.x / current.x, scaling.y / current.y); if (rotation) matrix.rotate(-rotation); matrix.translate(center.negate()); this.transform(matrix); if (decomposed) { decomposed.scaling = scaling; this._decomposed = decomposed } } }, getMatrix: function() { return this._matrix }, setMatrix: function() { var matrix = this._matrix; matrix.initialize.apply(matrix, arguments) }, getGlobalMatrix: function(_dontClone) { var matrix = this._globalMatrix; if (matrix) { var parent = this._parent; var parents = []; while (parent) { if (!parent._globalMatrix) { matrix = null; for (var i = 0, l = parents.length; i < l; i++) { parents[i]._globalMatrix = null } break } parents.push(parent); parent = parent._parent } } if (!matrix) { matrix = this._globalMatrix = this._matrix.clone(); var parent = this._parent; if (parent) matrix.prepend(parent.getGlobalMatrix(true)) } return _dontClone ? matrix : matrix.clone() }, getViewMatrix: function() { return this.getGlobalMatrix().prepend(this.getView()._matrix) }, getApplyMatrix: function() { return this._applyMatrix }, setApplyMatrix: function(apply) { if (this._applyMatrix = this._canApplyMatrix && !!apply) this.transform(null, true) }, getTransformContent: "#getApplyMatrix", setTransformContent: "#setApplyMatrix" }, { getProject: function() { return this._project }, _setProject: function(project, installEvents) { if (this._project !== project) { if (this._project) this._installEvents(false); this._project = project; var children = this._children; for (var i = 0, l = children && children.length; i < l; i++) children[i]._setProject(project); installEvents = true } if (installEvents) this._installEvents(true) }, getView: function() { return this._project._view }, _installEvents: function _installEvents(install) { _installEvents.base.call(this, install); var children = this._children; for (var i = 0, l = children && children.length; i < l; i++) children[i]._installEvents(install) }, getLayer: function() { var parent = this; while (parent = parent._parent) { if (parent instanceof Layer) return parent } return null }, getParent: function() { return this._parent }, setParent: function(item) { return item.addChild(this) }, _getOwner: "#getParent", getChildren: function() { return this._children }, setChildren: function(items) { this.removeChildren(); this.addChildren(items) }, getFirstChild: function() { return this._children && this._children[0] || null }, getLastChild: function() { return this._children && this._children[this._children.length - 1] || null }, getNextSibling: function() { var owner = this._getOwner(); return owner && owner._children[this._index + 1] || null }, getPreviousSibling: function() { var owner = this._getOwner(); return owner && owner._children[this._index - 1] || null }, getIndex: function() { return this._index }, equals: function(item) { return item === this || item && this._class === item._class && this._style.equals(item._style) && this._matrix.equals(item._matrix) && this._locked === item._locked && this._visible === item._visible && this._blendMode === item._blendMode && this._opacity === item._opacity && this._clipMask === item._clipMask && this._guide === item._guide && this._equals(item) || false }, _equals: function(item) { return Base.equals(this._children, item._children) }, clone: function(options) { var copy = new this.constructor(Item.NO_INSERT), children = this._children, insert = Base.pick(options ? options.insert : undefined, options === undefined || options === true), deep = Base.pick(options ? options.deep : undefined, true); if (children) copy.copyAttributes(this); if (!children || deep) copy.copyContent(this); if (!children) copy.copyAttributes(this); if (insert) copy.insertAbove(this); var name = this._name, parent = this._parent; if (name && parent) { var children = parent._children, orig = name, i = 1; while (children[name]) name = orig + " " + i++; if (name !== orig) copy.setName(name) } return copy }, copyContent: function(source) { var children = source._children; for (var i = 0, l = children && children.length; i < l; i++) { this.addChild(children[i].clone(false), true) } }, copyAttributes: function(source, excludeMatrix) { this.setStyle(source._style); var keys = ["_locked", "_visible", "_blendMode", "_opacity", "_clipMask", "_guide"]; for (var i = 0, l = keys.length; i < l; i++) { var key = keys[i]; if (source.hasOwnProperty(key)) this[key] = source[key] } if (!excludeMatrix) this._matrix.set(source._matrix, true); this.setApplyMatrix(source._applyMatrix); this.setPivot(source._pivot); this.setSelection(source._selection); var data = source._data, name = source._name; this._data = data ? Base.clone(data) : null; if (name) this.setName(name) }, rasterize: function(resolution, insert) { var bounds = this.getStrokeBounds(), scale = (resolution || this.getView().getResolution()) / 72, topLeft = bounds.getTopLeft().floor(), bottomRight = bounds.getBottomRight().ceil(), size = new Size(bottomRight.subtract(topLeft)), raster = new Raster(Item.NO_INSERT); if (!size.isZero()) { var canvas = CanvasProvider.getCanvas(size.multiply(scale)), ctx = canvas.getContext("2d"), matrix = (new Matrix).scale(scale).translate(topLeft.negate()); ctx.save(); matrix.applyToContext(ctx); this.draw(ctx, new Base({ matrices: [matrix] })); ctx.restore(); raster.setCanvas(canvas) } raster.transform((new Matrix).translate(topLeft.add(size.divide(2))).scale(1 / scale)); if (insert === undefined || insert) raster.insertAbove(this); return raster }, contains: function() { return !!this._contains(this._matrix._inverseTransform(Point.read(arguments))) }, _contains: function(point) { var children = this._children; if (children) { for (var i = children.length - 1; i >= 0; i--) { if (children[i].contains(point)) return true } return false } return point.isInside(this.getInternalBounds()) }, isInside: function() { return Rectangle.read(arguments).contains(this.getBounds()) }, _asPathItem: function() { return new Path.Rectangle({ rectangle: this.getInternalBounds(), matrix: this._matrix, insert: false }) }, intersects: function(item, _matrix) { if (!(item instanceof Item)) return false; return this._asPathItem().getIntersections(item._asPathItem(), null, _matrix, true).length > 0 } }, new function() { function hitTest() { return this._hitTest(Point.read(arguments), HitResult.getOptions(arguments)) } function hitTestAll() { var point = Point.read(arguments), options = HitResult.getOptions(arguments), all = []; this._hitTest(point, Base.set({ all: all }, options)); return all } function hitTestChildren(point, options, viewMatrix, _exclude) { var children = this._children; if (children) { for (var i = children.length - 1; i >= 0; i--) { var child = children[i]; var res = child !== _exclude && child._hitTest(point, options, viewMatrix); if (res && !options.all) return res } } return null } Project.inject({ hitTest: hitTest, hitTestAll: hitTestAll, _hitTest: hitTestChildren }); return { hitTest: hitTest, hitTestAll: hitTestAll, _hitTestChildren: hitTestChildren } }, { _hitTest: function(point, options, parentViewMatrix) { if (this._locked || !this._visible || this._guide && !options.guides || this.isEmpty()) { return null } var matrix = this._matrix, viewMatrix = parentViewMatrix ? parentViewMatrix.appended(matrix) : this.getGlobalMatrix().prepend(this.getView()._matrix), tolerance = Math.max(options.tolerance, 1e-12), tolerancePadding = options._tolerancePadding = new Size(Path._getStrokePadding(tolerance, matrix._shiftless().invert())); point = matrix._inverseTransform(point); if (!point || !this._children && !this.getBounds({ internal: true, stroke: true, handle: true }).expand(tolerancePadding.multiply(2))._containsPoint(point)) { return null } var checkSelf = !(options.guides && !this._guide || options.selected && !this.isSelected() || options.type && options.type !== Base.hyphenate(this._class) || options.class && !(this instanceof options.class)), match = options.match, that = this, bounds, res; function filter(hit) { if (hit && match && !match(hit)) hit = null; if (hit && options.all) options.all.push(hit); return hit } function checkPoint(type, part) { var pt = part ? bounds["get" + part]() : that.getPosition(); if (point.subtract(pt).divide(tolerancePadding).length <= 1) { return new HitResult(type, that, { name: part ? Base.hyphenate(part) : type, point: pt }) } } var checkPosition = options.position, checkCenter = options.center, checkBounds = options.bounds; if (checkSelf && this._parent && (checkPosition || checkCenter || checkBounds)) { if (checkCenter || checkBounds) { bounds = this.getInternalBounds() } res = checkPosition && checkPoint("position") || checkCenter && checkPoint("center", "Center"); if (!res && checkBounds) { var points = ["TopLeft", "TopRight", "BottomLeft", "BottomRight", "LeftCenter", "TopCenter", "RightCenter", "BottomCenter"]; for (var i = 0; i < 8 && !res; i++) { res = checkPoint("bounds", points[i]) } } res = filter(res) } if (!res) { res = this._hitTestChildren(point, options, viewMatrix) || checkSelf && filter(this._hitTestSelf(point, options, viewMatrix, this.getStrokeScaling() ? null : viewMatrix._shiftless().invert())) || null } if (res && res.point) { res.point = matrix.transform(res.point) } return res }, _hitTestSelf: function(point, options) { if (options.fill && this.hasFill() && this._contains(point)) return new HitResult("fill", this) }, matches: function(name, compare) { function matchObject(obj1, obj2) { for (var i in obj1) { if (obj1.hasOwnProperty(i)) { var val1 = obj1[i], val2 = obj2[i]; if (Base.isPlainObject(val1) && Base.isPlainObject(val2)) { if (!matchObject(val1, val2)) return false } else if (!Base.equals(val1, val2)) { return false } } } return true } var type = typeof name; if (type === "object") { for (var key in name) { if (name.hasOwnProperty(key) && !this.matches(key, name[key])) return false } return true } else if (type === "function") { return name(this) } else if (name === "match") { return compare(this) } else { var value = /^(empty|editable)$/.test(name) ? this["is" + Base.capitalize(name)]() : name === "type" ? Base.hyphenate(this._class) : this[name]; if (name === "class") { if (typeof compare === "function") return this instanceof compare; value = this._class } if (typeof compare === "function") { return !!compare(value) } else if (compare) { if (compare.test) { return compare.test(value) } else if (Base.isPlainObject(compare)) { return matchObject(compare, value) } } return Base.equals(value, compare) } }, getItems: function(options) { return Item._getItems(this, options, this._matrix) }, getItem: function(options) { return Item._getItems(this, options, this._matrix, null, true)[0] || null }, statics: { _getItems: function _getItems(item, options, matrix, param, firstOnly) { if (!param) { var obj = typeof options === "object" && options, overlapping = obj && obj.overlapping, inside = obj && obj.inside, bounds = overlapping || inside, rect = bounds && Rectangle.read([bounds]); param = { items: [], recursive: obj && obj.recursive !== false, inside: !!inside, overlapping: !!overlapping, rect: rect, path: overlapping && new Path.Rectangle({ rectangle: rect, insert: false }) }; if (obj) { options = Base.filter({}, options, { recursive: true, inside: true, overlapping: true }) } } var children = item._children, items = param.items, rect = param.rect; matrix = rect && (matrix || new Matrix); for (var i = 0, l = children && children.length; i < l; i++) { var child = children[i], childMatrix = matrix && matrix.appended(child._matrix), add = true; if (rect) { var bounds = child.getBounds(childMatrix); if (!rect.intersects(bounds)) continue; if (!(rect.contains(bounds) || param.overlapping && (bounds.contains(rect) || param.path.intersects(child, childMatrix)))) add = false } if (add && child.matches(options)) { items.push(child); if (firstOnly) break } if (param.recursive !== false) { _getItems(child, options, childMatrix, param, firstOnly) } if (firstOnly && items.length > 0) break } return items } } }, { importJSON: function(json) { var res = Base.importJSON(json, this); return res !== this ? this.addChild(res) : res }, addChild: function(item) { return this.insertChild(undefined, item) }, insertChild: function(index, item) { var res = item ? this.insertChildren(index, [item]) : null; return res && res[0] }, addChildren: function(items) { return this.insertChildren(this._children.length, items) }, insertChildren: function(index, items) { var children = this._children; if (children && items && items.length > 0) { items = Base.slice(items); var inserted = {}; for (var i = items.length - 1; i >= 0; i--) { var item = items[i], id = item && item._id; if (!item || inserted[id]) { items.splice(i, 1) } else { item._remove(false, true); inserted[id] = true } } Base.splice(children, items, index, 0); var project = this._project, notifySelf = project._changes; for (var i = 0, l = items.length; i < l; i++) { var item = items[i], name = item._name; item._parent = this; item._setProject(project, true); if (name) item.setName(name); if (notifySelf) item._changed(5) } this._changed(11) } else { items = null } return items }, _insertItem: "#insertChild", _insertAt: function(item, offset) { var owner = item && item._getOwner(), res = item !== this && owner ? this : null; if (res) { res._remove(false, true); owner._insertItem(item._index + offset, res) } return res }, insertAbove: function(item) { return this._insertAt(item, 1) }, insertBelow: function(item) { return this._insertAt(item, 0) }, sendToBack: function() { var owner = this._getOwner(); return owner ? owner._insertItem(0, this) : null }, bringToFront: function() { var owner = this._getOwner(); return owner ? owner._insertItem(undefined, this) : null }, appendTop: "#addChild", appendBottom: function(item) { return this.insertChild(0, item) }, moveAbove: "#insertAbove", moveBelow: "#insertBelow", addTo: function(owner) { return owner._insertItem(undefined, this) }, copyTo: function(owner) { return this.clone(false).addTo(owner) }, reduce: function(options) { var children = this._children; if (children && children.length === 1) { var child = children[0].reduce(options); if (this._parent) { child.insertAbove(this); this.remove() } else { child.remove() } return child } return this }, _removeNamed: function() { var owner = this._getOwner(); if (owner) { var children = owner._children, namedChildren = owner._namedChildren, name = this._name, namedArray = namedChildren[name], index = namedArray ? namedArray.indexOf(this) : -1; if (index !== -1) { if (children[name] == this) delete children[name]; namedArray.splice(index, 1); if (namedArray.length) { children[name] = namedArray[0] } else { delete namedChildren[name] } } } }, _remove: function(notifySelf, notifyParent) { var owner = this._getOwner(), project = this._project, index = this._index; if (this._style) this._style._dispose(); if (owner) { if (this._name) this._removeNamed(); if (index != null) { if (project._activeLayer === this) project._activeLayer = this.getNextSibling() || this.getPreviousSibling(); Base.splice(owner._children, null, index, 1) } this._installEvents(false); if (notifySelf && project._changes) this._changed(5); if (notifyParent) owner._changed(11, this); this._parent = null; return true } return false }, remove: function() { return this._remove(true, true) }, replaceWith: function(item) { var ok = item && item.insertBelow(this); if (ok) this.remove(); return ok }, removeChildren: function(start, end) { if (!this._children) return null; start = start || 0; end = Base.pick(end, this._children.length); var removed = Base.splice(this._children, null, start, end - start); for (var i = removed.length - 1; i >= 0; i--) { removed[i]._remove(true, false) } if (removed.length > 0) this._changed(11); return removed }, clear: "#removeChildren", reverseChildren: function() { if (this._children) { this._children.reverse(); for (var i = 0, l = this._children.length; i < l; i++) this._children[i]._index = i; this._changed(11) } }, isEmpty: function() { var children = this._children; return !children || !children.length }, isEditable: function() { var item = this; while (item) { if (!item._visible || item._locked) return false; item = item._parent } return true }, hasFill: function() { return this.getStyle().hasFill() }, hasStroke: function() { return this.getStyle().hasStroke() }, hasShadow: function() { return this.getStyle().hasShadow() }, _getOrder: function(item) { function getList(item) { var list = []; do { list.unshift(item) } while (item = item._parent); return list } var list1 = getList(this), list2 = getList(item); for (var i = 0, l = Math.min(list1.length, list2.length); i < l; i++) { if (list1[i] != list2[i]) { return list1[i]._index < list2[i]._index ? 1 : -1 } } return 0 }, hasChildren: function() { return this._children && this._children.length > 0 }, isInserted: function() { return this._parent ? this._parent.isInserted() : false }, isAbove: function(item) { return this._getOrder(item) === -1 }, isBelow: function(item) { return this._getOrder(item) === 1 }, isParent: function(item) { return this._parent === item }, isChild: function(item) { return item && item._parent === this }, isDescendant: function(item) { var parent = this; while (parent = parent._parent) { if (parent === item) return true } return false }, isAncestor: function(item) { return item ? item.isDescendant(this) : false }, isSibling: function(item) { return this._parent === item._parent }, isGroupedWith: function(item) { var parent = this._parent; while (parent) { if (parent._parent && /^(Group|Layer|CompoundPath)$/.test(parent._class) && item.isDescendant(parent)) return true; parent = parent._parent } return false } }, Base.each(["rotate", "scale", "shear", "skew"], function(key) { var rotate = key === "rotate"; this[key] = function() { var value = (rotate ? Base : Point).read(arguments), center = Point.read(arguments, 0, { readNull: true }); return this.transform((new Matrix)[key](value, center || this.getPosition(true))) } }, { translate: function() { var mx = new Matrix; return this.transform(mx.translate.apply(mx, arguments)) }, transform: function(matrix, _applyMatrix, _applyRecursively, _setApplyMatrix) { var _matrix = this._matrix, transformMatrix = matrix && !matrix.isIdentity(), applyMatrix = (_applyMatrix || this._applyMatrix) && (!_matrix.isIdentity() || transformMatrix || _applyMatrix && _applyRecursively && this._children); if (!transformMatrix && !applyMatrix) return this; if (transformMatrix) { if (!matrix.isInvertible() && _matrix.isInvertible()) _matrix._backup = _matrix.getValues(); _matrix.prepend(matrix, true); var style = this._style, fillColor = style.getFillColor(true), strokeColor = style.getStrokeColor(true); if (fillColor) fillColor.transform(matrix); if (strokeColor) strokeColor.transform(matrix) } if (applyMatrix && (applyMatrix = this._transformContent(_matrix, _applyRecursively, _setApplyMatrix))) { var pivot = this._pivot; if (pivot) _matrix._transformPoint(pivot, pivot, true); _matrix.reset(true); if (_setApplyMatrix && this._canApplyMatrix) this._applyMatrix = true } var bounds = this._bounds, position = this._position; if (transformMatrix || applyMatrix) { this._changed(25) } var decomp = transformMatrix && bounds && matrix.decompose(); if (decomp && decomp.skewing.isZero() && decomp.rotation % 90 === 0) { for (var key in bounds) { var cache = bounds[key]; if (cache.nonscaling) { delete bounds[key] } else if (applyMatrix || !cache.internal) { var rect = cache.rect; matrix._transformBounds(rect, rect) } } this._bounds = bounds; var cached = bounds[this._getBoundsCacheKey(this._boundsOptions || {})]; if (cached) { this._position = this._getPositionFromBounds(cached.rect) } } else if (transformMatrix && position && this._pivot) { this._position = matrix._transformPoint(position, position) } return this }, _transformContent: function(matrix, applyRecursively, setApplyMatrix) { var children = this._children; if (children) { for (var i = 0, l = children.length; i < l; i++) children[i].transform(matrix, true, applyRecursively, setApplyMatrix); return true } }, globalToLocal: function() { return this.getGlobalMatrix(true)._inverseTransform(Point.read(arguments)) }, localToGlobal: function() { return this.getGlobalMatrix(true)._transformPoint(Point.read(arguments)) }, parentToLocal: function() { return this._matrix._inverseTransform(Point.read(arguments)) }, localToParent: function() { return this._matrix._transformPoint(Point.read(arguments)) }, fitBounds: function(rectangle, fill) { rectangle = Rectangle.read(arguments); var bounds = this.getBounds(), itemRatio = bounds.height / bounds.width, rectRatio = rectangle.height / rectangle.width, scale = (fill ? itemRatio > rectRatio : itemRatio < rectRatio) ? rectangle.width / bounds.width : rectangle.height / bounds.height, newBounds = new Rectangle(new Point, new Size(bounds.width * scale, bounds.height * scale)); newBounds.setCenter(rectangle.getCenter()); this.setBounds(newBounds) } }), { _setStyles: function(ctx, param, viewMatrix) { var style = this._style, matrix = this._matrix; if (style.hasFill()) { ctx.fillStyle = style.getFillColor().toCanvasStyle(ctx, matrix) } if (style.hasStroke()) { ctx.strokeStyle = style.getStrokeColor().toCanvasStyle(ctx, matrix); ctx.lineWidth = style.getStrokeWidth(); var strokeJoin = style.getStrokeJoin(), strokeCap = style.getStrokeCap(), miterLimit = style.getMiterLimit(); if (strokeJoin) ctx.lineJoin = strokeJoin; if (strokeCap) ctx.lineCap = strokeCap; if (miterLimit) ctx.miterLimit = miterLimit; if (paper.support.nativeDash) { var dashArray = style.getDashArray(), dashOffset = style.getDashOffset(); if (dashArray && dashArray.length) { if ("setLineDash" in ctx) { ctx.setLineDash(dashArray); ctx.lineDashOffset = dashOffset } else { ctx.mozDash = dashArray; ctx.mozDashOffset = dashOffset } } } } if (style.hasShadow()) { var pixelRatio = param.pixelRatio || 1, mx = viewMatrix._shiftless().prepend((new Matrix).scale(pixelRatio, pixelRatio)), blur = mx.transform(new Point(style.getShadowBlur(), 0)), offset = mx.transform(this.getShadowOffset()); ctx.shadowColor = style.getShadowColor().toCanvasStyle(ctx); ctx.shadowBlur = blur.getLength(); ctx.shadowOffsetX = offset.x; ctx.shadowOffsetY = offset.y } }, draw: function(ctx, param, parentStrokeMatrix) { var updateVersion = this._updateVersion = this._project._updateVersion; if (!this._visible || this._opacity === 0) return; var matrices = param.matrices, viewMatrix = param.viewMatrix, matrix = this._matrix, globalMatrix = matrices[matrices.length - 1].appended(matrix); if (!globalMatrix.isInvertible()) return; viewMatrix = viewMatrix ? viewMatrix.appended(globalMatrix) : globalMatrix; matrices.push(globalMatrix); if (param.updateMatrix) { this._globalMatrix = globalMatrix } var blendMode = this._blendMode, opacity = this._opacity, normalBlend = blendMode === "normal", nativeBlend = BlendMode.nativeModes[blendMode], direct = normalBlend && opacity === 1 || param.dontStart || param.clip || (nativeBlend || normalBlend && opacity < 1) && this._canComposite(), pixelRatio = param.pixelRatio || 1, mainCtx, itemOffset, prevOffset; if (!direct) { var bounds = this.getStrokeBounds(viewMatrix); if (!bounds.width || !bounds.height) { matrices.pop(); return } prevOffset = param.offset; itemOffset = param.offset = bounds.getTopLeft().floor(); mainCtx = ctx; ctx = CanvasProvider.getContext(bounds.getSize().ceil().add(1).multiply(pixelRatio)); if (pixelRatio !== 1) ctx.scale(pixelRatio, pixelRatio) } ctx.save(); var strokeMatrix = parentStrokeMatrix ? parentStrokeMatrix.appended(matrix) : this._canScaleStroke && !this.getStrokeScaling(true) && viewMatrix, clip = !direct && param.clipItem, transform = !strokeMatrix || clip; if (direct) { ctx.globalAlpha = opacity; if (nativeBlend) ctx.globalCompositeOperation = blendMode } else if (transform) { ctx.translate(-itemOffset.x, -itemOffset.y) } if (transform) { (direct ? matrix : viewMatrix).applyToContext(ctx) } if (clip) { param.clipItem.draw(ctx, param.extend({ clip: true })) } if (strokeMatrix) { ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0); var offset = param.offset; if (offset) ctx.translate(-offset.x, -offset.y) } this._draw(ctx, param, viewMatrix, strokeMatrix); ctx.restore(); matrices.pop(); if (param.clip && !param.dontFinish) ctx.clip(); if (!direct) { BlendMode.process(blendMode, ctx, mainCtx, opacity, itemOffset.subtract(prevOffset).multiply(pixelRatio)); CanvasProvider.release(ctx); param.offset = prevOffset } }, _isUpdated: function(updateVersion) { var parent = this._parent; if (parent instanceof CompoundPath) return parent._isUpdated(updateVersion); var updated = this._updateVersion === updateVersion; if (!updated && parent && parent._visible && parent._isUpdated(updateVersion)) { this._updateVersion = updateVersion; updated = true } return updated }, _drawSelection: function(ctx, matrix, size, selectionItems, updateVersion) { var selection = this._selection, itemSelected = selection & 1, boundsSelected = selection & 2 || itemSelected && this._selectBounds, positionSelected = selection & 4; if (!this._drawSelected) itemSelected = false; if ((itemSelected || boundsSelected || positionSelected) && this._isUpdated(updateVersion)) { var layer, color = this.getSelectedColor(true) || (layer = this.getLayer()) && layer.getSelectedColor(true), mx = matrix.appended(this.getGlobalMatrix(true)), half = size / 2; ctx.strokeStyle = ctx.fillStyle = color ? color.toCanvasStyle(ctx) : "#009dec"; if (itemSelected) this._drawSelected(ctx, mx, selectionItems); if (positionSelected) { var pos = this.getPosition(true), parent = this._parent, point = parent ? parent.localToGlobal(pos) : pos, x = point.x, y = point.y; ctx.beginPath(); ctx.arc(x, y, half, 0, Math.PI * 2, true); ctx.stroke(); var deltas = [ [0, -1], [1, 0], [0, 1], [-1, 0] ], start = half, end = size + 1; for (var i = 0; i < 4; i++) { var delta = deltas[i], dx = delta[0], dy = delta[1]; ctx.moveTo(x + dx * start, y + dy * start); ctx.lineTo(x + dx * end, y + dy * end); ctx.stroke() } } if (boundsSelected) { var coords = mx._transformCorners(this.getInternalBounds()); ctx.beginPath(); for (var i = 0; i < 8; i++) { ctx[!i ? "moveTo" : "lineTo"](coords[i], coords[++i]) } ctx.closePath(); ctx.stroke(); for (var i = 0; i < 8; i++) { ctx.fillRect(coords[i] - half, coords[++i] - half, size, size) } } } }, _canComposite: function() { return false } }, Base.each(["down", "drag", "up", "move"], function(key) { this["removeOn" + Base.capitalize(key)] = function() { var hash = {}; hash[key] = true; return this.removeOn(hash) } }, { removeOn: function(obj) { for (var name in obj) { if (obj[name]) { var key = "mouse" + name, project = this._project, sets = project._removeSets = project._removeSets || {}; sets[key] = sets[key] || {}; sets[key][this._id] = this } } return this } })); var Group = Item.extend({ _class: "Group", _selectBounds: false, _selectChildren: true, _serializeFields: { children: [] }, initialize: function Group(arg) { this._children = []; this._namedChildren = {}; if (!this._initialize(arg)) this.addChildren(Array.isArray(arg) ? arg : arguments) }, _changed: function _changed(flags) { _changed.base.call(this, flags); if (flags & 2050) { this._clipItem = undefined } }, _getClipItem: function() { var clipItem = this._clipItem; if (clipItem === undefined) { clipItem = null; var children = this._children; for (var i = 0, l = children.length; i < l; i++) { if (children[i]._clipMask) { clipItem = children[i]; break } } this._clipItem = clipItem } return clipItem }, isClipped: function() { return !!this._getClipItem() }, setClipped: function(clipped) { var child = this.getFirstChild(); if (child) child.setClipMask(clipped) }, _getBounds: function _getBounds(matrix, options) { var clipItem = this._getClipItem(); return clipItem ? clipItem._getCachedBounds(matrix && matrix.appended(clipItem._matrix), Base.set({}, options, { stroke: false })) : _getBounds.base.call(this, matrix, options) }, _hitTestChildren: function _hitTestChildren(point, options, viewMatrix) { var clipItem = this._getClipItem(); return (!clipItem || clipItem.contains(point)) && _hitTestChildren.base.call(this, point, options, viewMatrix, clipItem) }, _draw: function(ctx, param) { var clip = param.clip, clipItem = !clip && this._getClipItem(); param = param.extend({ clipItem: clipItem, clip: false }); if (clip) { ctx.beginPath(); param.dontStart = param.dontFinish = true } else if (clipItem) { clipItem.draw(ctx, param.extend({ clip: true })) } var children = this._children; for (var i = 0, l = children.length; i < l; i++) { var item = children[i]; if (item !== clipItem) item.draw(ctx, param) } } }); var Layer = Group.extend({ _class: "Layer", initialize: function Layer() { Group.apply(this, arguments) }, _getOwner: function() { return this._parent || this._index != null && this._project }, isInserted: function isInserted() { return this._parent ? isInserted.base.call(this) : this._index != null }, activate: function() { this._project._activeLayer = this }, _hitTestSelf: function() {} }); var Shape = Item.extend({ _class: "Shape", _applyMatrix: false, _canApplyMatrix: false, _canScaleStroke: true, _serializeFields: { type: null, size: null, radius: null }, initialize: function Shape(props, point) { this._initialize(props, point) }, _equals: function(item) { return this._type === item._type && this._size.equals(item._size) && Base.equals(this._radius, item._radius) }, copyContent: function(source) { this.setType(source._type); this.setSize(source._size); this.setRadius(source._radius) }, getType: function() { return this._type }, setType: function(type) { this._type = type }, getShape: "#getType", setShape: "#setType", getSize: function() { var size = this._size; return new LinkedSize(size.width, size.height, this, "setSize") }, setSize: function() { var size = Size.read(arguments); if (!this._size) { this._size = size.clone() } else if (!this._size.equals(size)) { var type = this._type, width = size.width, height = size.height; if (type === "rectangle") { this._radius.set(Size.min(this._radius, size.divide(2))) } else if (type === "circle") { width = height = (width + height) / 2; this._radius = width / 2 } else if (type === "ellipse") { this._radius._set(width / 2, height / 2) } this._size._set(width, height); this._changed(9) } }, getRadius: function() { var rad = this._radius; return this._type === "circle" ? rad : new LinkedSize(rad.width, rad.height, this, "setRadius") }, setRadius: function(radius) { var type = this._type; if (type === "circle") { if (radius === this._radius) return; var size = radius * 2; this._radius = radius; this._size._set(size, size) } else { radius = Size.read(arguments); if (!this._radius) { this._radius = radius.clone() } else { if (this._radius.equals(radius)) return; this._radius.set(radius); if (type === "rectangle") { var size = Size.max(this._size, radius.multiply(2)); this._size.set(size) } else if (type === "ellipse") { this._size._set(radius.width * 2, radius.height * 2) } } } this._changed(9) }, isEmpty: function() { return false }, toPath: function(insert) { var path = new(Path[Base.capitalize(this._type)])({ center: new Point, size: this._size, radius: this._radius, insert: false }); path.copyAttributes(this); if (paper.settings.applyMatrix) path.setApplyMatrix(true); if (insert === undefined || insert) path.insertAbove(this); return path }, toShape: "#clone", _asPathItem: function() { return this.toPath(false) }, _draw: function(ctx, param, viewMatrix, strokeMatrix) { var style = this._style, hasFill = style.hasFill(), hasStroke = style.hasStroke(), dontPaint = param.dontFinish || param.clip, untransformed = !strokeMatrix; if (hasFill || hasStroke || dontPaint) { var type = this._type, radius = this._radius, isCircle = type === "circle"; if (!param.dontStart) ctx.beginPath(); if (untransformed && isCircle) { ctx.arc(0, 0, radius, 0, Math.PI * 2, true) } else { var rx = isCircle ? radius : radius.width, ry = isCircle ? radius : radius.height, size = this._size, width = size.width, height = size.height; if (untransformed && type === "rectangle" && rx === 0 && ry === 0) { ctx.rect(-width / 2, -height / 2, width, height) } else { var x = width / 2, y = height / 2, kappa = 1 - .5522847498307936, cx = rx * kappa, cy = ry * kappa, c = [-x, -y + ry, -x, -y + cy, -x + cx, -y, -x + rx, -y, x - rx, -y, x - cx, -y, x, -y + cy, x, -y + ry, x, y - ry, x, y - cy, x - cx, y, x - rx, y, -x + rx, y, -x + cx, y, -x, y - cy, -x, y - ry]; if (strokeMatrix) strokeMatrix.transform(c, c, 32); ctx.moveTo(c[0], c[1]); ctx.bezierCurveTo(c[2], c[3], c[4], c[5], c[6], c[7]); if (x !== rx) ctx.lineTo(c[8], c[9]); ctx.bezierCurveTo(c[10], c[11], c[12], c[13], c[14], c[15]); if (y !== ry) ctx.lineTo(c[16], c[17]); ctx.bezierCurveTo(c[18], c[19], c[20], c[21], c[22], c[23]); if (x !== rx) ctx.lineTo(c[24], c[25]); ctx.bezierCurveTo(c[26], c[27], c[28], c[29], c[30], c[31]) } } ctx.closePath() } if (!dontPaint && (hasFill || hasStroke)) { this._setStyles(ctx, param, viewMatrix); if (hasFill) { ctx.fill(style.getFillRule()); ctx.shadowColor = "rgba(0,0,0,0)" } if (hasStroke) ctx.stroke() } }, _canComposite: function() { return !(this.hasFill() && this.hasStroke()) }, _getBounds: function(matrix, options) { var rect = new Rectangle(this._size).setCenter(0, 0), style = this._style, strokeWidth = options.stroke && style.hasStroke() && style.getStrokeWidth(); if (matrix) rect = matrix._transformBounds(rect); return strokeWidth ? rect.expand(Path._getStrokePadding(strokeWidth, this._getStrokeMatrix(matrix, options))) : rect } }, new function() { function getCornerCenter(that, point, expand) { var radius = that._radius; if (!radius.isZero()) { var halfSize = that._size.divide(2); for (var q = 1; q <= 4; q++) { var dir = new Point(q > 1 && q < 4 ? -1 : 1, q > 2 ? -1 : 1), corner = dir.multiply(halfSize), center = corner.subtract(dir.multiply(radius)), rect = new Rectangle(expand ? corner.add(dir.multiply(expand)) : corner, center); if (rect.contains(point)) return { point: center, quadrant: q } } } } function isOnEllipseStroke(point, radius, padding, quadrant) { var vector = point.divide(radius); return (!quadrant || vector.isInQuadrant(quadrant)) && vector.subtract(vector.normalize()).multiply(radius).divide(padding).length <= 1 } return { _contains: function _contains(point) { if (this._type === "rectangle") { var center = getCornerCenter(this, point); return center ? point.subtract(center.point).divide(this._radius).getLength() <= 1 : _contains.base.call(this, point) } else { return point.divide(this.size).getLength() <= .5 } }, _hitTestSelf: function _hitTestSelf(point, options, viewMatrix, strokeMatrix) { var hit = false, style = this._style, hitStroke = options.stroke && style.hasStroke(), hitFill = options.fill && style.hasFill(); if (hitStroke || hitFill) { var type = this._type, radius = this._radius, strokeRadius = hitStroke ? style.getStrokeWidth() / 2 : 0, strokePadding = options._tolerancePadding.add(Path._getStrokePadding(strokeRadius, !style.getStrokeScaling() && strokeMatrix)); if (type === "rectangle") { var padding = strokePadding.multiply(2), center = getCornerCenter(this, point, padding); if (center) { hit = isOnEllipseStroke(point.subtract(center.point), radius, strokePadding, center.quadrant) } else { var rect = new Rectangle(this._size).setCenter(0, 0), outer = rect.expand(padding), inner = rect.expand(padding.negate()); hit = outer._containsPoint(point) && !inner._containsPoint(point) } } else { hit = isOnEllipseStroke(point, radius, strokePadding) } } return hit ? new HitResult(hitStroke ? "stroke" : "fill", this) : _hitTestSelf.base.apply(this, arguments) } } }, { statics: new function() { function createShape(type, point, size, radius, args) { var item = new Shape(Base.getNamed(args), point); item._type = type; item._size = size; item._radius = radius; return item } return { Circle: function() { var center = Point.readNamed(arguments, "center"), radius = Base.readNamed(arguments, "radius"); return createShape("circle", center, new Size(radius * 2), radius, arguments) }, Rectangle: function() { var rect = Rectangle.readNamed(arguments, "rectangle"), radius = Size.min(Size.readNamed(arguments, "radius"), rect.getSize(true).divide(2)); return createShape("rectangle", rect.getCenter(true), rect.getSize(true), radius, arguments) }, Ellipse: function() { var ellipse = Shape._readEllipse(arguments), radius = ellipse.radius; return createShape("ellipse", ellipse.center, radius.multiply(2), radius, arguments) }, _readEllipse: function(args) { var center, radius; if (Base.hasNamed(args, "radius")) { center = Point.readNamed(args, "center"); radius = Size.readNamed(args, "radius") } else { var rect = Rectangle.readNamed(args, "rectangle"); center = rect.getCenter(true); radius = rect.getSize(true).divide(2) } return { center: center, radius: radius } } } } }); var Raster = Item.extend({ _class: "Raster", _applyMatrix: false, _canApplyMatrix: false, _boundsOptions: { stroke: false, handle: false }, _serializeFields: { crossOrigin: null, source: null }, _prioritize: ["crossOrigin"], _smoothing: true, initialize: function Raster(object, position) { if (!this._initialize(object, position !== undefined && Point.read(arguments, 1))) { var image = typeof object === "string" ? document.getElementById(object) : object; if (image) { this.setImage(image) } else { this.setSource(object) } } if (!this._size) { this._size = new Size; this._loaded = false } }, _equals: function(item) { return this.getSource() === item.getSource() }, copyContent: function(source) { var image = source._image, canvas = source._canvas; if (image) { this._setImage(image) } else if (canvas) { var copyCanvas = CanvasProvider.getCanvas(source._size); copyCanvas.getContext("2d").drawImage(canvas, 0, 0); this._setImage(copyCanvas) } this._crossOrigin = source._crossOrigin }, getSize: function() { var size = this._size; return new LinkedSize(size ? size.width : 0, size ? size.height : 0, this, "setSize") }, setSize: function() { var size = Size.read(arguments); if (!size.equals(this._size)) { if (size.width > 0 && size.height > 0) { var element = this.getElement(); this._setImage(CanvasProvider.getCanvas(size)); if (element) this.getContext(true).drawImage(element, 0, 0, size.width, size.height) } else { if (this._canvas) CanvasProvider.release(this._canvas); this._size = size.clone() } } }, getWidth: function() { return this._size ? this._size.width : 0 }, setWidth: function(width) { this.setSize(width, this.getHeight()) }, getHeight: function() { return this._size ? this._size.height : 0 }, setHeight: function(height) { this.setSize(this.getWidth(), height) }, getLoaded: function() { return this._loaded }, isEmpty: function() { var size = this._size; return !size || size.width === 0 && size.height === 0 }, getResolution: function() { var matrix = this._matrix, orig = new Point(0, 0).transform(matrix), u = new Point(1, 0).transform(matrix).subtract(orig), v = new Point(0, 1).transform(matrix).subtract(orig); return new Size(72 / u.getLength(), 72 / v.getLength()) }, getPpi: "#getResolution", getImage: function() { return this._image }, setImage: function(image) { var that = this; function emit(event) { var view = that.getView(), type = event && event.type || "load"; if (view && that.responds(type)) { paper = view._scope; that.emit(type, new Event(event)) } } this._setImage(image); if (this._loaded) { setTimeout(emit, 0) } else if (image) { DomEvent.add(image, { load: function(event) { that._setImage(image); emit(event) }, error: emit }) } }, _setImage: function(image) { if (this._canvas) CanvasProvider.release(this._canvas); if (image && image.getContext) { this._image = null; this._canvas = image; this._loaded = true } else { this._image = image; this._canvas = null; this._loaded = !!(image && image.src && image.complete) } this._size = new Size(image ? image.naturalWidth || image.width : 0, image ? image.naturalHeight || image.height : 0); this._context = null; this._changed(1033) }, getCanvas: function() { if (!this._canvas) { var ctx = CanvasProvider.getContext(this._size); try { if (this._image) ctx.drawImage(this._image, 0, 0); this._canvas = ctx.canvas } catch (e) { CanvasProvider.release(ctx) } } return this._canvas }, setCanvas: "#setImage", getContext: function(modify) { if (!this._context) this._context = this.getCanvas().getContext("2d"); if (modify) { this._image = null; this._changed(1025) } return this._context }, setContext: function(context) { this._context = context }, getSource: function() { var image = this._image; return image && image.src || this.toDataURL() }, setSource: function(src) { var image = new self.Image, crossOrigin = this._crossOrigin; if (crossOrigin) image.crossOrigin = crossOrigin; image.src = src; this.setImage(image) }, getCrossOrigin: function() { var image = this._image; return image && image.crossOrigin || this._crossOrigin || "" }, setCrossOrigin: function(crossOrigin) { this._crossOrigin = crossOrigin; var image = this._image; if (image) image.crossOrigin = crossOrigin }, getSmoothing: function() { return this._smoothing }, setSmoothing: function(smoothing) { this._smoothing = smoothing; this._changed(257) }, getElement: function() { return this._canvas || this._loaded && this._image } }, { beans: false, getSubCanvas: function() { var rect = Rectangle.read(arguments), ctx = CanvasProvider.getContext(rect.getSize()); ctx.drawImage(this.getCanvas(), rect.x, rect.y, rect.width, rect.height, 0, 0, rect.width, rect.height); return ctx.canvas }, getSubRaster: function() { var rect = Rectangle.read(arguments), raster = new Raster(Item.NO_INSERT); raster._setImage(this.getSubCanvas(rect)); raster.translate(rect.getCenter().subtract(this.getSize().divide(2))); raster._matrix.prepend(this._matrix); raster.insertAbove(this); return raster }, toDataURL: function() { var image = this._image, src = image && image.src; if (/^data:/.test(src)) return src; var canvas = this.getCanvas(); return canvas ? canvas.toDataURL.apply(canvas, arguments) : null }, drawImage: function(image) { var point = Point.read(arguments, 1); this.getContext(true).drawImage(image, point.x, point.y) }, getAverageColor: function(object) { var bounds, path; if (!object) { bounds = this.getBounds() } else if (object instanceof PathItem) { path = object; bounds = object.getBounds() } else if (typeof object === "object") { if ("width" in object) { bounds = new Rectangle(object) } else if ("x" in object) { bounds = new Rectangle(object.x - .5, object.y - .5, 1, 1) } } if (!bounds) return null; var sampleSize = 32, width = Math.min(bounds.width, sampleSize), height = Math.min(bounds.height, sampleSize); var ctx = Raster._sampleContext; if (!ctx) { ctx = Raster._sampleContext = CanvasProvider.getContext(new Size(sampleSize)) } else { ctx.clearRect(0, 0, sampleSize + 1, sampleSize + 1) } ctx.save(); var matrix = (new Matrix).scale(width / bounds.width, height / bounds.height).translate(-bounds.x, -bounds.y); matrix.applyToContext(ctx); if (path) path.draw(ctx, new Base({ clip: true, matrices: [matrix] })); this._matrix.applyToContext(ctx); var element = this.getElement(), size = this._size; if (element) ctx.drawImage(element, -size.width / 2, -size.height / 2); ctx.restore(); var pixels = ctx.getImageData(.5, .5, Math.ceil(width), Math.ceil(height)).data, channels = [0, 0, 0], total = 0; for (var i = 0, l = pixels.length; i < l; i += 4) { var alpha = pixels[i + 3]; total += alpha; alpha /= 255; channels[0] += pixels[i] * alpha; channels[1] += pixels[i + 1] * alpha; channels[2] += pixels[i + 2] * alpha } for (var i = 0; i < 3; i++) channels[i] /= total; return total ? Color.read(channels) : null }, getPixel: function() { var point = Point.read(arguments); var data = this.getContext().getImageData(point.x, point.y, 1, 1).data; return new Color("rgb", [data[0] / 255, data[1] / 255, data[2] / 255], data[3] / 255) }, setPixel: function() { var point = Point.read(arguments), color = Color.read(arguments), components = color._convert("rgb"), alpha = color._alpha, ctx = this.getContext(true), imageData = ctx.createImageData(1, 1), data = imageData.data; data[0] = components[0] * 255; data[1] = components[1] * 255; data[2] = components[2] * 255; data[3] = alpha != null ? alpha * 255 : 255; ctx.putImageData(imageData, point.x, point.y) }, createImageData: function() { var size = Size.read(arguments); return this.getContext().createImageData(size.width, size.height) }, getImageData: function() { var rect = Rectangle.read(arguments); if (rect.isEmpty()) rect = new Rectangle(this._size); return this.getContext().getImageData(rect.x, rect.y, rect.width, rect.height) }, setImageData: function(data) { var point = Point.read(arguments, 1); this.getContext(true).putImageData(data, point.x, point.y) }, _getBounds: function(matrix, options) { var rect = new Rectangle(this._size).setCenter(0, 0); return matrix ? matrix._transformBounds(rect) : rect }, _hitTestSelf: function(point) { if (this._contains(point)) { var that = this; return new HitResult("pixel", that, { offset: point.add(that._size.divide(2)).round(), color: { get: function() { return that.getPixel(this.offset) } } }) } }, _draw: function(ctx, param, viewMatrix) { var element = this.getElement(); if (element) { ctx.globalAlpha = this._opacity; this._setStyles(ctx, param, viewMatrix); DomElement.setPrefixed(ctx, "imageSmoothingEnabled", this._smoothing); ctx.drawImage(element, -this._size.width / 2, -this._size.height / 2) } }, _canComposite: function() { return true } }); var SymbolItem = Item.extend({ _class: "SymbolItem", _applyMatrix: false, _canApplyMatrix: false, _boundsOptions: { stroke: true }, _serializeFields: { symbol: null }, initialize: function SymbolItem(arg0, arg1) { if (!this._initialize(arg0, arg1 !== undefined && Point.read(arguments, 1))) this.setDefinition(arg0 instanceof SymbolDefinition ? arg0 : new SymbolDefinition(arg0)) }, _equals: function(item) { return this._definition === item._definition }, copyContent: function(source) { this.setDefinition(source._definition) }, getDefinition: function() { return this._definition }, setDefinition: function(definition) { this._definition = definition; this._changed(9) }, getSymbol: "#getDefinition", setSymbol: "#setDefinition", isEmpty: function() { return this._definition._item.isEmpty() }, _getBounds: function(matrix, options) { var item = this._definition._item; return item._getCachedBounds(item._matrix.prepended(matrix), options) }, _hitTestSelf: function(point, options, viewMatrix) { var res = this._definition._item._hitTest(point, options, viewMatrix); if (res) res.item = this; return res }, _draw: function(ctx, param) { this._definition._item.draw(ctx, param) } }); var SymbolDefinition = Base.extend({ _class: "SymbolDefinition", initialize: function SymbolDefinition(item, dontCenter) { this._id = UID.get(); this.project = paper.project; if (item) this.setItem(item, dontCenter) }, _serialize: function(options, dictionary) { return dictionary.add(this, function() { return Base.serialize([this._class, this._item], options, false, dictionary) }) }, _changed: function(flags) { if (flags & 8) Item._clearBoundsCache(this); if (flags & 1) this.project._changed(flags) }, getItem: function() { return this._item }, setItem: function(item, _dontCenter) { if (item._symbol) item = item.clone(); if (this._item) this._item._symbol = null; this._item = item; item.remove(); item.setSelected(false); if (!_dontCenter) item.setPosition(new Point); item._symbol = this; this._changed(9) }, getDefinition: "#getItem", setDefinition: "#setItem", place: function(position) { return new SymbolItem(this, position) }, clone: function() { return new SymbolDefinition(this._item.clone(false)) }, equals: function(symbol) { return symbol === this || symbol && this._item.equals(symbol._item) || false } }); var HitResult = Base.extend({ _class: "HitResult", initialize: function HitResult(type, item, values) { this.type = type; this.item = item; if (values) this.inject(values) }, statics: { getOptions: function(args) { var options = args && Base.read(args); return Base.set({ type: null, tolerance: paper.settings.hitTolerance, fill: !options, stroke: !options, segments: !options, handles: false, ends: false, position: false, center: false, bounds: false, guides: false, selected: false }, options) } } }); var Segment = Base.extend({ _class: "Segment", beans: true, _selection: 0, initialize: function Segment(arg0, arg1, arg2, arg3, arg4, arg5) { var count = arguments.length, point, handleIn, handleOut, selection; if (count > 0) { if (arg0 == null || typeof arg0 === "object") { if (count === 1 && arg0 && "point" in arg0) { point = arg0.point; handleIn = arg0.handleIn; handleOut = arg0.handleOut; selection = arg0.selection } else { point = arg0; handleIn = arg1; handleOut = arg2; selection = arg3 } } else { point = [arg0, arg1]; handleIn = arg2 !== undefined ? [arg2, arg3] : null; handleOut = arg4 !== undefined ? [arg4, arg5] : null } } new SegmentPoint(point, this, "_point"); new SegmentPoint(handleIn, this, "_handleIn"); new SegmentPoint(handleOut, this, "_handleOut"); if (selection) this.setSelection(selection) }, _serialize: function(options, dictionary) { var point = this._point, selection = this._selection, obj = selection || this.hasHandles() ? [point, this._handleIn, this._handleOut] : point; if (selection) obj.push(selection); return Base.serialize(obj, options, true, dictionary) }, _changed: function(point) { var path = this._path; if (!path) return; var curves = path._curves, index = this._index, curve; if (curves) { if ((!point || point === this._point || point === this._handleIn) && (curve = index > 0 ? curves[index - 1] : path._closed ? curves[curves.length - 1] : null)) curve._changed(); if ((!point || point === this._point || point === this._handleOut) && (curve = curves[index])) curve._changed() } path._changed(41) }, getPoint: function() { return this._point }, setPoint: function() { this._point.set(Point.read(arguments)) }, getHandleIn: function() { return this._handleIn }, setHandleIn: function() { this._handleIn.set(Point.read(arguments)) }, getHandleOut: function() { return this._handleOut }, setHandleOut: function() { this._handleOut.set(Point.read(arguments)) }, hasHandles: function() { return !this._handleIn.isZero() || !this._handleOut.isZero() }, isSmooth: function() { var handleIn = this._handleIn, handleOut = this._handleOut; return !handleIn.isZero() && !handleOut.isZero() && handleIn.isCollinear(handleOut) }, clearHandles: function() { this._handleIn._set(0, 0); this._handleOut._set(0, 0) }, getSelection: function() { return this._selection }, setSelection: function(selection) { var oldSelection = this._selection, path = this._path; this._selection = selection = selection || 0; if (path && selection !== oldSelection) { path._updateSelection(this, oldSelection, selection); path._changed(257) } }, _changeSelection: function(flag, selected) { var selection = this._selection; this.setSelection(selected ? selection | flag : selection & ~flag) }, isSelected: function() { return !!(this._selection & 7) }, setSelected: function(selected) { this._changeSelection(7, selected) }, getIndex: function() { return this._index !== undefined ? this._index : null }, getPath: function() { return this._path || null }, getCurve: function() { var path = this._path, index = this._index; if (path) { if (index > 0 && !path._closed && index === path._segments.length - 1) index--; return path.getCurves()[index] || null } return null }, getLocation: function() { var curve = this.getCurve(); return curve ? new CurveLocation(curve, this === curve._segment1 ? 0 : 1) : null }, getNext: function() { var segments = this._path && this._path._segments; return segments && (segments[this._index + 1] || this._path._closed && segments[0]) || null }, smooth: function(options, _first, _last) { var opts = options || {}, type = opts.type, factor = opts.factor, prev = this.getPrevious(), next = this.getNext(), p0 = (prev || this)._point, p1 = this._point, p2 = (next || this)._point, d1 = p0.getDistance(p1), d2 = p1.getDistance(p2); if (!type || type === "catmull-rom") { var a = factor === undefined ? .5 : factor, d1_a = Math.pow(d1, a), d1_2a = d1_a * d1_a, d2_a = Math.pow(d2, a), d2_2a = d2_a * d2_a; if (!_first && prev) { var A = 2 * d2_2a + 3 * d2_a * d1_a + d1_2a, N = 3 * d2_a * (d2_a + d1_a); this.setHandleIn(N !== 0 ? new Point((d2_2a * p0._x + A * p1._x - d1_2a * p2._x) / N - p1._x, (d2_2a * p0._y + A * p1._y - d1_2a * p2._y) / N - p1._y) : new Point) } if (!_last && next) { var A = 2 * d1_2a + 3 * d1_a * d2_a + d2_2a, N = 3 * d1_a * (d1_a + d2_a); this.setHandleOut(N !== 0 ? new Point((d1_2a * p2._x + A * p1._x - d2_2a * p0._x) / N - p1._x, (d1_2a * p2._y + A * p1._y - d2_2a * p0._y) / N - p1._y) : new Point) } } else if (type === "geometric") { if (prev && next) { var vector = p0.subtract(p2), t = factor === undefined ? .4 : factor, k = t * d1 / (d1 + d2); if (!_first) this.setHandleIn(vector.multiply(k)); if (!_last) this.setHandleOut(vector.multiply(k - t)) } } else { throw new Error("Smoothing method '" + type + "' not supported.") } }, getPrevious: function() { var segments = this._path && this._path._segments; return segments && (segments[this._index - 1] || this._path._closed && segments[segments.length - 1]) || null }, isFirst: function() { return !this._index }, isLast: function() { var path = this._path; return path && this._index === path._segments.length - 1 || false }, reverse: function() { var handleIn = this._handleIn, handleOut = this._handleOut, tmp = handleIn.clone(); handleIn.set(handleOut); handleOut.set(tmp) }, reversed: function() { return new Segment(this._point, this._handleOut, this._handleIn) }, remove: function() { return this._path ? !!this._path.removeSegment(this._index) : false }, clone: function() { return new Segment(this._point, this._handleIn, this._handleOut) }, equals: function(segment) { return segment === this || segment && this._class === segment._class && this._point.equals(segment._point) && this._handleIn.equals(segment._handleIn) && this._handleOut.equals(segment._handleOut) || false }, toString: function() { var parts = ["point: " + this._point]; if (!this._handleIn.isZero()) parts.push("handleIn: " + this._handleIn); if (!this._handleOut.isZero()) parts.push("handleOut: " + this._handleOut); return "{ " + parts.join(", ") + " }" }, transform: function(matrix) { this._transformCoordinates(matrix, new Array(6), true); this._changed() }, interpolate: function(from, to, factor) { var u = 1 - factor, v = factor, point1 = from._point, point2 = to._point, handleIn1 = from._handleIn, handleIn2 = to._handleIn, handleOut2 = to._handleOut, handleOut1 = from._handleOut; this._point._set(u * point1._x + v * point2._x, u * point1._y + v * point2._y, true); this._handleIn._set(u * handleIn1._x + v * handleIn2._x, u * handleIn1._y + v * handleIn2._y, true); this._handleOut._set(u * handleOut1._x + v * handleOut2._x, u * handleOut1._y + v * handleOut2._y, true); this._changed() }, _transformCoordinates: function(matrix, coords, change) { var point = this._point, handleIn = !change || !this._handleIn.isZero() ? this._handleIn : null, handleOut = !change || !this._handleOut.isZero() ? this._handleOut : null, x = point._x, y = point._y, i = 2; coords[0] = x; coords[1] = y; if (handleIn) { coords[i++] = handleIn._x + x; coords[i++] = handleIn._y + y } if (handleOut) { coords[i++] = handleOut._x + x; coords[i++] = handleOut._y + y } if (matrix) { matrix._transformCoordinates(coords, coords, i / 2); x = coords[0]; y = coords[1]; if (change) { point._x = x; point._y = y; i = 2; if (handleIn) { handleIn._x = coords[i++] - x; handleIn._y = coords[i++] - y } if (handleOut) { handleOut._x = coords[i++] - x; handleOut._y = coords[i++] - y } } else { if (!handleIn) { coords[i++] = x; coords[i++] = y } if (!handleOut) { coords[i++] = x; coords[i++] = y } } } return coords } }); var SegmentPoint = Point.extend({ initialize: function SegmentPoint(point, owner, key) { var x, y, selected; if (!point) { x = y = 0 } else if ((x = point[0]) !== undefined) { y = point[1] } else { var pt = point; if ((x = pt.x) === undefined) { pt = Point.read(arguments); x = pt.x } y = pt.y; selected = pt.selected } this._x = x; this._y = y; this._owner = owner; owner[key] = this; if (selected) this.setSelected(true) }, _set: function(x, y) { this._x = x; this._y = y; this._owner._changed(this); return this }, getX: function() { return this._x }, setX: function(x) { this._x = x; this._owner._changed(this) }, getY: function() { return this._y }, setY: function(y) { this._y = y; this._owner._changed(this) }, isZero: function() { var isZero = Numerical.isZero; return isZero(this._x) && isZero(this._y) }, isSelected: function() { return !!(this._owner._selection & this._getSelection()) }, setSelected: function(selected) { this._owner._changeSelection(this._getSelection(), selected) }, _getSelection: function() { var owner = this._owner; return this === owner._point ? 1 : this === owner._handleIn ? 2 : this === owner._handleOut ? 4 : 0 } }); var Curve = Base.extend({ _class: "Curve", beans: true, initialize: function Curve(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7) { var count = arguments.length, seg1, seg2, point1, point2, handle1, handle2; if (count === 3) { this._path = arg0; seg1 = arg1; seg2 = arg2 } else if (!count) { seg1 = new Segment; seg2 = new Segment } else if (count === 1) { if ("segment1" in arg0) { seg1 = new Segment(arg0.segment1); seg2 = new Segment(arg0.segment2) } else if ("point1" in arg0) { point1 = arg0.point1; handle1 = arg0.handle1; handle2 = arg0.handle2; point2 = arg0.point2 } else if (Array.isArray(arg0)) { point1 = [arg0[0], arg0[1]]; point2 = [arg0[6], arg0[7]]; handle1 = [arg0[2] - arg0[0], arg0[3] - arg0[1]]; handle2 = [arg0[4] - arg0[6], arg0[5] - arg0[7]] } } else if (count === 2) { seg1 = new Segment(arg0); seg2 = new Segment(arg1) } else if (count === 4) { point1 = arg0; handle1 = arg1; handle2 = arg2; point2 = arg3 } else if (count === 8) { point1 = [arg0, arg1]; point2 = [arg6, arg7]; handle1 = [arg2 - arg0, arg3 - arg1]; handle2 = [arg4 - arg6, arg5 - arg7] } this._segment1 = seg1 || new Segment(point1, null, handle1); this._segment2 = seg2 || new Segment(point2, handle2, null) }, _serialize: function(options, dictionary) { return Base.serialize(this.hasHandles() ? [this.getPoint1(), this.getHandle1(), this.getHandle2(), this.getPoint2()] : [this.getPoint1(), this.getPoint2()], options, true, dictionary) }, _changed: function() { this._length = this._bounds = undefined }, clone: function() { return new Curve(this._segment1, this._segment2) }, toString: function() { var parts = ["point1: " + this._segment1._point]; if (!this._segment1._handleOut.isZero()) parts.push("handle1: " + this._segment1._handleOut); if (!this._segment2._handleIn.isZero()) parts.push("handle2: " + this._segment2._handleIn); parts.push("point2: " + this._segment2._point); return "{ " + parts.join(", ") + " }" }, classify: function() { return Curve.classify(this.getValues()) }, remove: function() { var removed = false; if (this._path) { var segment2 = this._segment2, handleOut = segment2._handleOut; removed = segment2.remove(); if (removed) this._segment1._handleOut.set(handleOut) } return removed }, getPoint1: function() { return this._segment1._point }, setPoint1: function() { this._segment1._point.set(Point.read(arguments)) }, getPoint2: function() { return this._segment2._point }, setPoint2: function() { this._segment2._point.set(Point.read(arguments)) }, getHandle1: function() { return this._segment1._handleOut }, setHandle1: function() { this._segment1._handleOut.set(Point.read(arguments)) }, getHandle2: function() { return this._segment2._handleIn }, setHandle2: function() { this._segment2._handleIn.set(Point.read(arguments)) }, getSegment1: function() { return this._segment1 }, getSegment2: function() { return this._segment2 }, getPath: function() { return this._path }, getIndex: function() { return this._segment1._index }, getNext: function() { var curves = this._path && this._path._curves; return curves && (curves[this._segment1._index + 1] || this._path._closed && curves[0]) || null }, getPrevious: function() { var curves = this._path && this._path._curves; return curves && (curves[this._segment1._index - 1] || this._path._closed && curves[curves.length - 1]) || null }, isFirst: function() { return !this._segment1._index }, isLast: function() { var path = this._path; return path && this._segment1._index === path._curves.length - 1 || false }, isSelected: function() { return this.getPoint1().isSelected() && this.getHandle1().isSelected() && this.getHandle2().isSelected() && this.getPoint2().isSelected() }, setSelected: function(selected) { this.getPoint1().setSelected(selected); this.getHandle1().setSelected(selected); this.getHandle2().setSelected(selected); this.getPoint2().setSelected(selected) }, getValues: function(matrix) { return Curve.getValues(this._segment1, this._segment2, matrix) }, getPoints: function() { var coords = this.getValues(), points = []; for (var i = 0; i < 8; i += 2) points.push(new Point(coords[i], coords[i + 1])); return points } }, { getLength: function() { if (this._length == null) this._length = Curve.getLength(this.getValues(), 0, 1); return this._length }, getArea: function() { return Curve.getArea(this.getValues()) }, getLine: function() { return new Line(this._segment1._point, this._segment2._point) }, getPart: function(from, to) { return new Curve(Curve.getPart(this.getValues(), from, to)) }, getPartLength: function(from, to) { return Curve.getLength(this.getValues(), from, to) }, divideAt: function(location) { return this.divideAtTime(location && location.curve === this ? location.time : this.getTimeAt(location)) }, divideAtTime: function(time, _setHandles) { var tMin = 1e-8, tMax = 1 - tMin, res = null; if (time >= tMin && time <= tMax) { var parts = Curve.subdivide(this.getValues(), time), left = parts[0], right = parts[1], setHandles = _setHandles || this.hasHandles(), seg1 = this._segment1, seg2 = this._segment2, path = this._path; if (setHandles) { seg1._handleOut._set(left[2] - left[0], left[3] - left[1]); seg2._handleIn._set(right[4] - right[6], right[5] - right[7]) } var x = left[6], y = left[7], segment = new Segment(new Point(x, y), setHandles && new Point(left[4] - x, left[5] - y), setHandles && new Point(right[2] - x, right[3] - y)); if (path) { path.insert(seg1._index + 1, segment); res = this.getNext() } else { this._segment2 = segment; this._changed(); res = new Curve(segment, seg2) } } return res }, splitAt: function(location) { var path = this._path; return path ? path.splitAt(location) : null }, splitAtTime: function(time) { return this.splitAt(this.getLocationAtTime(time)) }, divide: function(offset, isTime) { return this.divideAtTime(offset === undefined ? .5 : isTime ? offset : this.getTimeAt(offset)) }, split: function(offset, isTime) { return this.splitAtTime(offset === undefined ? .5 : isTime ? offset : this.getTimeAt(offset)) }, reversed: function() { return new Curve(this._segment2.reversed(), this._segment1.reversed()) }, clearHandles: function() { this._segment1._handleOut._set(0, 0); this._segment2._handleIn._set(0, 0) }, statics: { getValues: function(segment1, segment2, matrix, straight) { var p1 = segment1._point, h1 = segment1._handleOut, h2 = segment2._handleIn, p2 = segment2._point, x1 = p1.x, y1 = p1.y, x2 = p2.x, y2 = p2.y, values = straight ? [x1, y1, x1, y1, x2, y2, x2, y2] : [x1, y1, x1 + h1._x, y1 + h1._y, x2 + h2._x, y2 + h2._y, x2, y2]; if (matrix) matrix._transformCoordinates(values, values, 4); return values }, subdivide: function(v, t) { var x0 = v[0], y0 = v[1], x1 = v[2], y1 = v[3], x2 = v[4], y2 = v[5], x3 = v[6], y3 = v[7]; if (t === undefined) t = .5; var u = 1 - t, x4 = u * x0 + t * x1, y4 = u * y0 + t * y1, x5 = u * x1 + t * x2, y5 = u * y1 + t * y2, x6 = u * x2 + t * x3, y6 = u * y2 + t * y3, x7 = u * x4 + t * x5, y7 = u * y4 + t * y5, x8 = u * x5 + t * x6, y8 = u * y5 + t * y6, x9 = u * x7 + t * x8, y9 = u * y7 + t * y8; return [ [x0, y0, x4, y4, x7, y7, x9, y9], [x9, y9, x8, y8, x6, y6, x3, y3] ] }, getMonoCurves: function(v, dir) { var curves = [], io = dir ? 0 : 1, o0 = v[io + 0], o1 = v[io + 2], o2 = v[io + 4], o3 = v[io + 6]; if (o0 >= o1 === o1 >= o2 && o1 >= o2 === o2 >= o3 || Curve.isStraight(v)) { curves.push(v) } else { var a = 3 * (o1 - o2) - o0 + o3, b = 2 * (o0 + o2) - 4 * o1, c = o1 - o0, tMin = 1e-8, tMax = 1 - tMin, roots = [], n = Numerical.solveQuadratic(a, b, c, roots, tMin, tMax); if (!n) { curves.push(v) } else { roots.sort(); var t = roots[0], parts = Curve.subdivide(v, t); curves.push(parts[0]); if (n > 1) { t = (roots[1] - t) / (1 - t); parts = Curve.subdivide(parts[1], t); curves.push(parts[0]) } curves.push(parts[1]) } } return curves }, solveCubic: function(v, coord, val, roots, min, max) { var v0 = v[coord], v1 = v[coord + 2], v2 = v[coord + 4], v3 = v[coord + 6], res = 0; if (!(v0 < val && v3 < val && v1 < val && v2 < val || v0 > val && v3 > val && v1 > val && v2 > val)) { var c = 3 * (v1 - v0), b = 3 * (v2 - v1) - c, a = v3 - v0 - c - b; res = Numerical.solveCubic(a, b, c, v0 - val, roots, min, max) } return res }, getTimeOf: function(v, point) { var p0 = new Point(v[0], v[1]), p3 = new Point(v[6], v[7]), epsilon = 1e-12, geomEpsilon = 1e-7, t = point.isClose(p0, epsilon) ? 0 : point.isClose(p3, epsilon) ? 1 : null; if (t === null) { var coords = [point.x, point.y], roots = []; for (var c = 0; c < 2; c++) { var count = Curve.solveCubic(v, c, coords[c], roots, 0, 1); for (var i = 0; i < count; i++) { var u = roots[i]; if (point.isClose(Curve.getPoint(v, u), geomEpsilon)) return u } } } return point.isClose(p0, geomEpsilon) ? 0 : point.isClose(p3, geomEpsilon) ? 1 : null }, getNearestTime: function(v, point) { if (Curve.isStraight(v)) { var x0 = v[0], y0 = v[1], x3 = v[6], y3 = v[7], vx = x3 - x0, vy = y3 - y0, det = vx * vx + vy * vy; if (det === 0) return 0; var u = ((point.x - x0) * vx + (point.y - y0) * vy) / det; return u < 1e-12 ? 0 : u > .999999999999 ? 1 : Curve.getTimeOf(v, new Point(x0 + u * vx, y0 + u * vy)) } var count = 100, minDist = Infinity, minT = 0; function refine(t) { if (t >= 0 && t <= 1) { var dist = point.getDistance(Curve.getPoint(v, t), true); if (dist < minDist) { minDist = dist; minT = t; return true } } } for (var i = 0; i <= count; i++) refine(i / count); var step = 1 / (count * 2); while (step > 1e-8) { if (!refine(minT - step) && !refine(minT + step)) step /= 2 } return minT }, getPart: function(v, from, to) { var flip = from > to; if (flip) { var tmp = from; from = to; to = tmp } if (from > 0) v = Curve.subdivide(v, from)[1]; if (to < 1) v = Curve.subdivide(v, (to - from) / (1 - from))[0]; return flip ? [v[6], v[7], v[4], v[5], v[2], v[3], v[0], v[1]] : v }, isFlatEnough: function(v, flatness) { var x0 = v[0], y0 = v[1], x1 = v[2], y1 = v[3], x2 = v[4], y2 = v[5], x3 = v[6], y3 = v[7], ux = 3 * x1 - 2 * x0 - x3, uy = 3 * y1 - 2 * y0 - y3, vx = 3 * x2 - 2 * x3 - x0, vy = 3 * y2 - 2 * y3 - y0; return Math.max(ux * ux, vx * vx) + Math.max(uy * uy, vy * vy) <= 16 * flatness * flatness }, getArea: function(v) { var x0 = v[0], y0 = v[1], x1 = v[2], y1 = v[3], x2 = v[4], y2 = v[5], x3 = v[6], y3 = v[7]; return 3 * ((y3 - y0) * (x1 + x2) - (x3 - x0) * (y1 + y2) + y1 * (x0 - x2) - x1 * (y0 - y2) + y3 * (x2 + x0 / 3) - x3 * (y2 + y0 / 3)) / 20 }, getBounds: function(v) { var min = v.slice(0, 2), max = min.slice(), roots = [0, 0]; for (var i = 0; i < 2; i++) Curve._addBounds(v[i], v[i + 2], v[i + 4], v[i + 6], i, 0, min, max, roots); return new Rectangle(min[0], min[1], max[0] - min[0], max[1] - min[1]) }, _addBounds: function(v0, v1, v2, v3, coord, padding, min, max, roots) { function add(value, padding) { var left = value - padding, right = value + padding; if (left < min[coord]) min[coord] = left; if (right > max[coord]) max[coord] = right } padding /= 2; var minPad = min[coord] - padding, maxPad = max[coord] + padding; if (v0 < minPad || v1 < minPad || v2 < minPad || v3 < minPad || v0 > maxPad || v1 > maxPad || v2 > maxPad || v3 > maxPad) { if (v1 < v0 != v1 < v3 && v2 < v0 != v2 < v3) { add(v0, padding); add(v3, padding) } else { var a = 3 * (v1 - v2) - v0 + v3, b = 2 * (v0 + v2) - 4 * v1, c = v1 - v0, count = Numerical.solveQuadratic(a, b, c, roots), tMin = 1e-8, tMax = 1 - tMin; add(v3, 0); for (var i = 0; i < count; i++) { var t = roots[i], u = 1 - t; if (tMin <= t && t <= tMax) add(u * u * u * v0 + 3 * u * u * t * v1 + 3 * u * t * t * v2 + t * t * t * v3, padding) } } } } } }, Base.each(["getBounds", "getStrokeBounds", "getHandleBounds"], function(name) { this[name] = function() { if (!this._bounds) this._bounds = {}; var bounds = this._bounds[name]; if (!bounds) { bounds = this._bounds[name] = Path[name]([this._segment1, this._segment2], false, this._path) } return bounds.clone() } }, {}), Base.each({ isStraight: function(p1, h1, h2, p2) { if (h1.isZero() && h2.isZero()) { return true } else { var v = p2.subtract(p1); if (v.isZero()) { return false } else if (v.isCollinear(h1) && v.isCollinear(h2)) { var l = new Line(p1, p2), epsilon = 1e-7; if (l.getDistance(p1.add(h1)) < epsilon && l.getDistance(p2.add(h2)) < epsilon) { var div = v.dot(v), s1 = v.dot(h1) / div, s2 = v.dot(h2) / div; return s1 >= 0 && s1 <= 1 && s2 <= 0 && s2 >= -1 } } } return false }, isLinear: function(p1, h1, h2, p2) { var third = p2.subtract(p1).divide(3); return h1.equals(third) && h2.negate().equals(third) } }, function(test, name) { this[name] = function(epsilon) { var seg1 = this._segment1, seg2 = this._segment2; return test(seg1._point, seg1._handleOut, seg2._handleIn, seg2._point, epsilon) }; this.statics[name] = function(v, epsilon) { var x0 = v[0], y0 = v[1], x3 = v[6], y3 = v[7]; return test(new Point(x0, y0), new Point(v[2] - x0, v[3] - y0), new Point(v[4] - x3, v[5] - y3), new Point(x3, y3), epsilon) } }, { statics: {}, hasHandles: function() { return !this._segment1._handleOut.isZero() || !this._segment2._handleIn.isZero() }, hasLength: function(epsilon) { return (!this.getPoint1().equals(this.getPoint2()) || this.hasHandles()) && this.getLength() > (epsilon || 0) }, isCollinear: function(curve) { return curve && this.isStraight() && curve.isStraight() && this.getLine().isCollinear(curve.getLine()) }, isHorizontal: function() { return this.isStraight() && Math.abs(this.getTangentAtTime(.5).y) < 1e-8 }, isVertical: function() { return this.isStraight() && Math.abs(this.getTangentAtTime(.5).x) < 1e-8 } }), { beans: false, getLocationAt: function(offset, _isTime) { return this.getLocationAtTime(_isTime ? offset : this.getTimeAt(offset)) }, getLocationAtTime: function(t) { return t != null && t >= 0 && t <= 1 ? new CurveLocation(this, t) : null }, getTimeAt: function(offset, start) { return Curve.getTimeAt(this.getValues(), offset, start) }, getParameterAt: "#getTimeAt", getTimesWithTangent: function() { var tangent = Point.read(arguments); return tangent.isZero() ? [] : Curve.getTimesWithTangent(this.getValues(), tangent) }, getOffsetAtTime: function(t) { return this.getPartLength(0, t) }, getLocationOf: function() { return this.getLocationAtTime(this.getTimeOf(Point.read(arguments))) }, getOffsetOf: function() { var loc = this.getLocationOf.apply(this, arguments); return loc ? loc.getOffset() : null }, getTimeOf: function() { return Curve.getTimeOf(this.getValues(), Point.read(arguments)) }, getParameterOf: "#getTimeOf", getNearestLocation: function() { var point = Point.read(arguments), values = this.getValues(), t = Curve.getNearestTime(values, point), pt = Curve.getPoint(values, t); return new CurveLocation(this, t, pt, null, point.getDistance(pt)) }, getNearestPoint: function() { var loc = this.getNearestLocation.apply(this, arguments); return loc ? loc.getPoint() : loc } }, new function() { var methods = ["getPoint", "getTangent", "getNormal", "getWeightedTangent", "getWeightedNormal", "getCurvature"]; return Base.each(methods, function(name) { this[name + "At"] = function(location, _isTime) { var values = this.getValues(); return Curve[name](values, _isTime ? location : Curve.getTimeAt(values, location)) }; this[name + "AtTime"] = function(time) { return Curve[name](this.getValues(), time) } }, { statics: { _evaluateMethods: methods } }) }, new function() { function getLengthIntegrand(v) { var x0 = v[0], y0 = v[1], x1 = v[2], y1 = v[3], x2 = v[4], y2 = v[5], x3 = v[6], y3 = v[7], ax = 9 * (x1 - x2) + 3 * (x3 - x0), bx = 6 * (x0 + x2) - 12 * x1, cx = 3 * (x1 - x0), ay = 9 * (y1 - y2) + 3 * (y3 - y0), by = 6 * (y0 + y2) - 12 * y1, cy = 3 * (y1 - y0); return function(t) { var dx = (ax * t + bx) * t + cx, dy = (ay * t + by) * t + cy; return Math.sqrt(dx * dx + dy * dy) } } function getIterations(a, b) { return Math.max(2, Math.min(16, Math.ceil(Math.abs(b - a) * 32))) } function evaluate(v, t, type, normalized) { if (t == null || t < 0 || t > 1) return null; var x0 = v[0], y0 = v[1], x1 = v[2], y1 = v[3], x2 = v[4], y2 = v[5], x3 = v[6], y3 = v[7], isZero = Numerical.isZero; if (isZero(x1 - x0) && isZero(y1 - y0)) { x1 = x0; y1 = y0 } if (isZero(x2 - x3) && isZero(y2 - y3)) { x2 = x3; y2 = y3 } var cx = 3 * (x1 - x0), bx = 3 * (x2 - x1) - cx, ax = x3 - x0 - cx - bx, cy = 3 * (y1 - y0), by = 3 * (y2 - y1) - cy, ay = y3 - y0 - cy - by, x, y; if (type === 0) { x = t === 0 ? x0 : t === 1 ? x3 : ((ax * t + bx) * t + cx) * t + x0; y = t === 0 ? y0 : t === 1 ? y3 : ((ay * t + by) * t + cy) * t + y0 } else { var tMin = 1e-8, tMax = 1 - tMin; if (t < tMin) { x = cx; y = cy } else if (t > tMax) { x = 3 * (x3 - x2); y = 3 * (y3 - y2) } else { x = (3 * ax * t + 2 * bx) * t + cx; y = (3 * ay * t + 2 * by) * t + cy } if (normalized) { if (x === 0 && y === 0 && (t < tMin || t > tMax)) { x = x2 - x1; y = y2 - y1 } var len = Math.sqrt(x * x + y * y); if (len) { x /= len; y /= len } } if (type === 3) { var x2 = 6 * ax * t + 2 * bx, y2 = 6 * ay * t + 2 * by, d = Math.pow(x * x + y * y, 3 / 2); x = d !== 0 ? (x * y2 - y * x2) / d : 0; y = 0 } } return type === 2 ? new Point(y, -x) : new Point(x, y) } return { statics: { classify: function(v) { var x0 = v[0], y0 = v[1], x1 = v[2], y1 = v[3], x2 = v[4], y2 = v[5], x3 = v[6], y3 = v[7], a1 = x0 * (y3 - y2) + y0 * (x2 - x3) + x3 * y2 - y3 * x2, a2 = x1 * (y0 - y3) + y1 * (x3 - x0) + x0 * y3 - y0 * x3, a3 = x2 * (y1 - y0) + y2 * (x0 - x1) + x1 * y0 - y1 * x0, d3 = 3 * a3, d2 = d3 - a2, d1 = d2 - a2 + a1, l = Math.sqrt(d1 * d1 + d2 * d2 + d3 * d3), s = l !== 0 ? 1 / l : 0, isZero = Numerical.isZero, serpentine = "serpentine"; d1 *= s; d2 *= s; d3 *= s; function type(type, t1, t2) { var hasRoots = t1 !== undefined, t1Ok = hasRoots && t1 > 0 && t1 < 1, t2Ok = hasRoots && t2 > 0 && t2 < 1; if (hasRoots && (!(t1Ok || t2Ok) || type === "loop" && !(t1Ok && t2Ok))) { type = "arch"; t1Ok = t2Ok = false } return { type: type, roots: t1Ok || t2Ok ? t1Ok && t2Ok ? t1 < t2 ? [t1, t2] : [t2, t1] : [t1Ok ? t1 : t2] : null } } if (isZero(d1)) { return isZero(d2) ? type(isZero(d3) ? "line" : "quadratic") : type(serpentine, d3 / (3 * d2)) } var d = 3 * d2 * d2 - 4 * d1 * d3; if (isZero(d)) { return type("cusp", d2 / (2 * d1)) } var f1 = d > 0 ? Math.sqrt(d / 3) : Math.sqrt(-d), f2 = 2 * d1; return type(d > 0 ? serpentine : "loop", (d2 + f1) / f2, (d2 - f1) / f2) }, getLength: function(v, a, b, ds) { if (a === undefined) a = 0; if (b === undefined) b = 1; if (Curve.isStraight(v)) { var c = v; if (b < 1) { c = Curve.subdivide(c, b)[0]; a /= b } if (a > 0) { c = Curve.subdivide(c, a)[1] } var dx = c[6] - c[0], dy = c[7] - c[1]; return Math.sqrt(dx * dx + dy * dy) } return Numerical.integrate(ds || getLengthIntegrand(v), a, b, getIterations(a, b)) }, getTimeAt: function(v, offset, start) { if (start === undefined) start = offset < 0 ? 1 : 0; if (offset === 0) return start; var abs = Math.abs, epsilon = 1e-12, forward = offset > 0, a = forward ? start : 0, b = forward ? 1 : start, ds = getLengthIntegrand(v), rangeLength = Curve.getLength(v, a, b, ds), diff = abs(offset) - rangeLength; if (abs(diff) < epsilon) { return forward ? b : a } else if (diff > epsilon) { return null } var guess = offset / rangeLength, length = 0; function f(t) { length += Numerical.integrate(ds, start, t, getIterations(start, t)); start = t; return length - offset } return Numerical.findRoot(f, ds, start + guess, a, b, 32, 1e-12) }, getPoint: function(v, t) { return evaluate(v, t, 0, false) }, getTangent: function(v, t) { return evaluate(v, t, 1, true) }, getWeightedTangent: function(v, t) { return evaluate(v, t, 1, false) }, getNormal: function(v, t) { return evaluate(v, t, 2, true) }, getWeightedNormal: function(v, t) { return evaluate(v, t, 2, false) }, getCurvature: function(v, t) { return evaluate(v, t, 3, false).x }, getPeaks: function(v) { var x0 = v[0], y0 = v[1], x1 = v[2], y1 = v[3], x2 = v[4], y2 = v[5], x3 = v[6], y3 = v[7], ax = -x0 + 3 * x1 - 3 * x2 + x3, bx = 3 * x0 - 6 * x1 + 3 * x2, cx = -3 * x0 + 3 * x1, ay = -y0 + 3 * y1 - 3 * y2 + y3, by = 3 * y0 - 6 * y1 + 3 * y2, cy = -3 * y0 + 3 * y1, tMin = 1e-8, tMax = 1 - tMin, roots = []; Numerical.solveCubic(9 * (ax * ax + ay * ay), 9 * (ax * bx + by * ay), 2 * (bx * bx + by * by) + 3 * (cx * ax + cy * ay), cx * bx + by * cy, roots, tMin, tMax); return roots.sort() } } } }, new function() { function addLocation(locations, include, c1, t1, c2, t2, overlap) { var excludeStart = !overlap && c1.getPrevious() === c2, excludeEnd = !overlap && c1 !== c2 && c1.getNext() === c2, tMin = 1e-8, tMax = 1 - tMin; if (t1 !== null && t1 >= (excludeStart ? tMin : 0) && t1 <= (excludeEnd ? tMax : 1)) { if (t2 !== null && t2 >= (excludeEnd ? tMin : 0) && t2 <= (excludeStart ? tMax : 1)) { var loc1 = new CurveLocation(c1, t1, null, overlap), loc2 = new CurveLocation(c2, t2, null, overlap); loc1._intersection = loc2; loc2._intersection = loc1; if (!include || include(loc1)) { CurveLocation.insert(locations, loc1, true) } } } } function addCurveIntersections(v1, v2, c1, c2, locations, include, flip, recursion, calls, tMin, tMax, uMin, uMax) { if (++calls >= 4096 || ++recursion >= 40) return calls; var fatLineEpsilon = 1e-9, q0x = v2[0], q0y = v2[1], q3x = v2[6], q3y = v2[7], getSignedDistance = Line.getSignedDistance, d1 = getSignedDistance(q0x, q0y, q3x, q3y, v2[2], v2[3]), d2 = getSignedDistance(q0x, q0y, q3x, q3y, v2[4], v2[5]), factor = d1 * d2 > 0 ? 3 / 4 : 4 / 9, dMin = factor * Math.min(0, d1, d2), dMax = factor * Math.max(0, d1, d2), dp0 = getSignedDistance(q0x, q0y, q3x, q3y, v1[0], v1[1]), dp1 = getSignedDistance(q0x, q0y, q3x, q3y, v1[2], v1[3]), dp2 = getSignedDistance(q0x, q0y, q3x, q3y, v1[4], v1[5]), dp3 = getSignedDistance(q0x, q0y, q3x, q3y, v1[6], v1[7]), hull = getConvexHull(dp0, dp1, dp2, dp3), top = hull[0], bottom = hull[1], tMinClip, tMaxClip; if (d1 === 0 && d2 === 0 && dp0 === 0 && dp1 === 0 && dp2 === 0 && dp3 === 0 || (tMinClip = clipConvexHull(top, bottom, dMin, dMax)) == null || (tMaxClip = clipConvexHull(top.reverse(), bottom.reverse(), dMin, dMax)) == null) return calls; var tMinNew = tMin + (tMax - tMin) * tMinClip, tMaxNew = tMin + (tMax - tMin) * tMaxClip; if (Math.max(uMax - uMin, tMaxNew - tMinNew) < fatLineEpsilon) { var t = (tMinNew + tMaxNew) / 2, u = (uMin + uMax) / 2; addLocation(locations, include, flip ? c2 : c1, flip ? u : t, flip ? c1 : c2, flip ? t : u) } else { v1 = Curve.getPart(v1, tMinClip, tMaxClip); if (tMaxClip - tMinClip > .8) { if (tMaxNew - tMinNew > uMax - uMin) { var parts = Curve.subdivide(v1, .5), t = (tMinNew + tMaxNew) / 2; calls = addCurveIntersections(v2, parts[0], c2, c1, locations, include, !flip, recursion, calls, uMin, uMax, tMinNew, t); calls = addCurveIntersections(v2, parts[1], c2, c1, locations, include, !flip, recursion, calls, uMin, uMax, t, tMaxNew) } else { var parts = Curve.subdivide(v2, .5), u = (uMin + uMax) / 2; calls = addCurveIntersections(parts[0], v1, c2, c1, locations, include, !flip, recursion, calls, uMin, u, tMinNew, tMaxNew); calls = addCurveIntersections(parts[1], v1, c2, c1, locations, include, !flip, recursion, calls, u, uMax, tMinNew, tMaxNew) } } else { if (uMax - uMin >= fatLineEpsilon) { calls = addCurveIntersections(v2, v1, c2, c1, locations, include, !flip, recursion, calls, uMin, uMax, tMinNew, tMaxNew) } else { calls = addCurveIntersections(v1, v2, c1, c2, locations, include, flip, recursion, calls, tMinNew, tMaxNew, uMin, uMax) } } } return calls } function getConvexHull(dq0, dq1, dq2, dq3) { var p0 = [0, dq0], p1 = [1 / 3, dq1], p2 = [2 / 3, dq2], p3 = [1, dq3], dist1 = dq1 - (2 * dq0 + dq3) / 3, dist2 = dq2 - (dq0 + 2 * dq3) / 3, hull; if (dist1 * dist2 < 0) { hull = [ [p0, p1, p3], [p0, p2, p3] ] } else { var distRatio = dist1 / dist2; hull = [distRatio >= 2 ? [p0, p1, p3] : distRatio <= .5 ? [p0, p2, p3] : [p0, p1, p2, p3], [p0, p3] ] } return (dist1 || dist2) < 0 ? hull.reverse() : hull } function clipConvexHull(hullTop, hullBottom, dMin, dMax) { if (hullTop[0][1] < dMin) { return clipConvexHullPart(hullTop, true, dMin) } else if (hullBottom[0][1] > dMax) { return clipConvexHullPart(hullBottom, false, dMax) } else { return hullTop[0][0] } } function clipConvexHullPart(part, top, threshold) { var px = part[0][0], py = part[0][1]; for (var i = 1, l = part.length; i < l; i++) { var qx = part[i][0], qy = part[i][1]; if (top ? qy >= threshold : qy <= threshold) { return qy === threshold ? qx : px + (threshold - py) * (qx - px) / (qy - py) } px = qx; py = qy } return null } function getCurveLineIntersections(v, px, py, vx, vy) { var isZero = Numerical.isZero; if (isZero(vx) && isZero(vy)) { var t = Curve.getTimeOf(v, new Point(px, py)); return t === null ? [] : [t] } var angle = Math.atan2(-vy, vx), sin = Math.sin(angle), cos = Math.cos(angle), rv = [], roots = []; for (var i = 0; i < 8; i += 2) { var x = v[i] - px, y = v[i + 1] - py; rv.push(x * cos - y * sin, x * sin + y * cos) } Curve.solveCubic(rv, 1, 0, roots, 0, 1); return roots } function addCurveLineIntersections(v1, v2, c1, c2, locations, include, flip) { var x1 = v2[0], y1 = v2[1], x2 = v2[6], y2 = v2[7], roots = getCurveLineIntersections(v1, x1, y1, x2 - x1, y2 - y1); for (var i = 0, l = roots.length; i < l; i++) { var t1 = roots[i], p1 = Curve.getPoint(v1, t1), t2 = Curve.getTimeOf(v2, p1); if (t2 !== null) { addLocation(locations, include, flip ? c2 : c1, flip ? t2 : t1, flip ? c1 : c2, flip ? t1 : t2) } } } function addLineIntersection(v1, v2, c1, c2, locations, include) { var pt = Line.intersect(v1[0], v1[1], v1[6], v1[7], v2[0], v2[1], v2[6], v2[7]); if (pt) { addLocation(locations, include, c1, Curve.getTimeOf(v1, pt), c2, Curve.getTimeOf(v2, pt)) } } function getCurveIntersections(v1, v2, c1, c2, locations, include) { var epsilon = 1e-12, min = Math.min, max = Math.max; if (max(v1[0], v1[2], v1[4], v1[6]) + epsilon > min(v2[0], v2[2], v2[4], v2[6]) && min(v1[0], v1[2], v1[4], v1[6]) - epsilon < max(v2[0], v2[2], v2[4], v2[6]) && max(v1[1], v1[3], v1[5], v1[7]) + epsilon > min(v2[1], v2[3], v2[5], v2[7]) && min(v1[1], v1[3], v1[5], v1[7]) - epsilon < max(v2[1], v2[3], v2[5], v2[7])) { var overlaps = getOverlaps(v1, v2); if (overlaps) { for (var i = 0; i < 2; i++) { var overlap = overlaps[i]; addLocation(locations, include, c1, overlap[0], c2, overlap[1], true) } } else { var straight1 = Curve.isStraight(v1), straight2 = Curve.isStraight(v2), straight = straight1 && straight2, flip = straight1 && !straight2, before = locations.length; (straight ? addLineIntersection : straight1 || straight2 ? addCurveLineIntersections : addCurveIntersections)(flip ? v2 : v1, flip ? v1 : v2, flip ? c2 : c1, flip ? c1 : c2, locations, include, flip, 0, 0, 0, 1, 0, 1); if (!straight || locations.length === before) { for (var i = 0; i < 4; i++) { var t1 = i >> 1, t2 = i & 1, i1 = t1 * 6, i2 = t2 * 6, p1 = new Point(v1[i1], v1[i1 + 1]), p2 = new Point(v2[i2], v2[i2 + 1]); if (p1.isClose(p2, epsilon)) { addLocation(locations, include, c1, t1, c2, t2) } } } } } return locations } function getLoopIntersection(v1, c1, locations, include) { var info = Curve.classify(v1); if (info.type === "loop") { var roots = info.roots; addLocation(locations, include, c1, roots[0], c1, roots[1]) } return locations } function getIntersections(curves1, curves2, include, matrix1, matrix2, _returnFirst) { var self = !curves2; if (self) curves2 = curves1; var length1 = curves1.length, length2 = curves2.length, values2 = [], arrays = [], locations, current; for (var i = 0; i < length2; i++) values2[i] = curves2[i].getValues(matrix2); for (var i = 0; i < length1; i++) { var curve1 = curves1[i], values1 = self ? values2[i] : curve1.getValues(matrix1), path1 = curve1.getPath(); if (path1 !== current) { current = path1; locations = []; arrays.push(locations) } if (self) { getLoopIntersection(values1, curve1, locations, include) } for (var j = self ? i + 1 : 0; j < length2; j++) { if (_returnFirst && locations.length) return locations; getCurveIntersections(values1, values2[j], curve1, curves2[j], locations, include) } } locations = []; for (var i = 0, l = arrays.length; i < l; i++) { Base.push(locations, arrays[i]) } return locations } function getOverlaps(v1, v2) { function getSquaredLineLength(v) { var x = v[6] - v[0], y = v[7] - v[1]; return x * x + y * y } var abs = Math.abs, getDistance = Line.getDistance, timeEpsilon = 1e-8, geomEpsilon = 1e-7, straight1 = Curve.isStraight(v1), straight2 = Curve.isStraight(v2), straightBoth = straight1 && straight2, flip = getSquaredLineLength(v1) < getSquaredLineLength(v2), l1 = flip ? v2 : v1, l2 = flip ? v1 : v2, px = l1[0], py = l1[1], vx = l1[6] - px, vy = l1[7] - py; if (getDistance(px, py, vx, vy, l2[0], l2[1], true) < geomEpsilon && getDistance(px, py, vx, vy, l2[6], l2[7], true) < geomEpsilon) { if (!straightBoth && getDistance(px, py, vx, vy, l1[2], l1[3], true) < geomEpsilon && getDistance(px, py, vx, vy, l1[4], l1[5], true) < geomEpsilon && getDistance(px, py, vx, vy, l2[2], l2[3], true) < geomEpsilon && getDistance(px, py, vx, vy, l2[4], l2[5], true) < geomEpsilon) { straight1 = straight2 = straightBoth = true } } else if (straightBoth) { return null } if (straight1 ^ straight2) { return null } var v = [v1, v2], pairs = []; for (var i = 0; i < 4 && pairs.length < 2; i++) { var i1 = i & 1, i2 = i1 ^ 1, t1 = i >> 1, t2 = Curve.getTimeOf(v[i1], new Point(v[i2][t1 ? 6 : 0], v[i2][t1 ? 7 : 1])); if (t2 != null) { var pair = i1 ? [t1, t2] : [t2, t1]; if (!pairs.length || abs(pair[0] - pairs[0][0]) > timeEpsilon && abs(pair[1] - pairs[0][1]) > timeEpsilon) { pairs.push(pair) } } if (i > 2 && !pairs.length) break } if (pairs.length !== 2) { pairs = null } else if (!straightBoth) { var o1 = Curve.getPart(v1, pairs[0][0], pairs[1][0]), o2 = Curve.getPart(v2, pairs[0][1], pairs[1][1]); if (abs(o2[2] - o1[2]) > geomEpsilon || abs(o2[3] - o1[3]) > geomEpsilon || abs(o2[4] - o1[4]) > geomEpsilon || abs(o2[5] - o1[5]) > geomEpsilon) pairs = null } return pairs } function getTimesWithTangent(v, tangent) { var x0 = v[0], y0 = v[1], x1 = v[2], y1 = v[3], x2 = v[4], y2 = v[5], x3 = v[6], y3 = v[7], normalized = tangent.normalize(), tx = normalized.x, ty = normalized.y, ax = 3 * x3 - 9 * x2 + 9 * x1 - 3 * x0, ay = 3 * y3 - 9 * y2 + 9 * y1 - 3 * y0, bx = 6 * x2 - 12 * x1 + 6 * x0, by = 6 * y2 - 12 * y1 + 6 * y0, cx = 3 * x1 - 3 * x0, cy = 3 * y1 - 3 * y0, den = 2 * ax * ty - 2 * ay * tx, times = []; if (Math.abs(den) < Numerical.CURVETIME_EPSILON) { var num = ax * cy - ay * cx, den = ax * by - ay * bx; if (den != 0) { var t = -num / den; if (t >= 0 && t <= 1) times.push(t) } } else { var delta = (bx * bx - 4 * ax * cx) * ty * ty + (-2 * bx * by + 4 * ay * cx + 4 * ax * cy) * tx * ty + (by * by - 4 * ay * cy) * tx * tx, k = bx * ty - by * tx; if (delta >= 0 && den != 0) { var d = Math.sqrt(delta), t0 = -(k + d) / den, t1 = (-k + d) / den; if (t0 >= 0 && t0 <= 1) times.push(t0); if (t1 >= 0 && t1 <= 1) times.push(t1) } } return times } return { getIntersections: function(curve) { var v1 = this.getValues(), v2 = curve && curve !== this && curve.getValues(); return v2 ? getCurveIntersections(v1, v2, this, curve, []) : getLoopIntersection(v1, this, []) }, statics: { getOverlaps: getOverlaps, getIntersections: getIntersections, getCurveLineIntersections: getCurveLineIntersections, getTimesWithTangent: getTimesWithTangent } } }); var CurveLocation = Base.extend({ _class: "CurveLocation", initialize: function CurveLocation(curve, time, point, _overlap, _distance) { if (time >= .99999999) { var next = curve.getNext(); if (next) { time = 0; curve = next } } this._setCurve(curve); this._time = time; this._point = point || curve.getPointAtTime(time); this._overlap = _overlap; this._distance = _distance; this._intersection = this._next = this._previous = null }, _setCurve: function(curve) { var path = curve._path; this._path = path; this._version = path ? path._version : 0; this._curve = curve; this._segment = null; this._segment1 = curve._segment1; this._segment2 = curve._segment2 }, _setSegment: function(segment) { this._setCurve(segment.getCurve()); this._segment = segment; this._time = segment === this._segment1 ? 0 : 1; this._point = segment._point.clone() }, getSegment: function() { var segment = this._segment; if (!segment) { var curve = this.getCurve(), time = this.getTime(); if (time === 0) { segment = curve._segment1 } else if (time === 1) { segment = curve._segment2 } else if (time != null) { segment = curve.getPartLength(0, time) < curve.getPartLength(time, 1) ? curve._segment1 : curve._segment2 } this._segment = segment } return segment }, getCurve: function() { var path = this._path, that = this; if (path && path._version !== this._version) { this._time = this._offset = this._curveOffset = this._curve = null } function trySegment(segment) { var curve = segment && segment.getCurve(); if (curve && (that._time = curve.getTimeOf(that._point)) != null) { that._setCurve(curve); return curve } } return this._curve || trySegment(this._segment) || trySegment(this._segment1) || trySegment(this._segment2.getPrevious()) }, getPath: function() { var curve = this.getCurve(); return curve && curve._path }, getIndex: function() { var curve = this.getCurve(); return curve && curve.getIndex() }, getTime: function() { var curve = this.getCurve(), time = this._time; return curve && time == null ? this._time = curve.getTimeOf(this._point) : time }, getParameter: "#getTime", getPoint: function() { return this._point }, getOffset: function() { var offset = this._offset; if (offset == null) { offset = 0; var path = this.getPath(), index = this.getIndex(); if (path && index != null) { var curves = path.getCurves(); for (var i = 0; i < index; i++) offset += curves[i].getLength() } this._offset = offset += this.getCurveOffset() } return offset }, getCurveOffset: function() { var offset = this._curveOffset; if (offset == null) { var curve = this.getCurve(), time = this.getTime(); this._curveOffset = offset = time != null && curve && curve.getPartLength(0, time) } return offset }, getIntersection: function() { return this._intersection }, getDistance: function() { return this._distance }, divide: function() { var curve = this.getCurve(), res = curve && curve.divideAtTime(this.getTime()); if (res) { this._setSegment(res._segment1) } return res }, split: function() { var curve = this.getCurve(), path = curve._path, res = curve && curve.splitAtTime(this.getTime()); if (res) { this._setSegment(path.getLastSegment()) } return res }, equals: function(loc, _ignoreOther) { var res = this === loc; if (!res && loc instanceof CurveLocation) { var c1 = this.getCurve(), c2 = loc.getCurve(), p1 = c1._path, p2 = c2._path; if (p1 === p2) { var abs = Math.abs, epsilon = 1e-7, diff = abs(this.getOffset() - loc.getOffset()), i1 = !_ignoreOther && this._intersection, i2 = !_ignoreOther && loc._intersection; res = (diff < epsilon || p1 && abs(p1.getLength() - diff) < epsilon) && (!i1 && !i2 || i1 && i2 && i1.equals(i2, true)) } } return res }, toString: function() { var parts = [], point = this.getPoint(), f = Formatter.instance; if (point) parts.push("point: " + point); var index = this.getIndex(); if (index != null) parts.push("index: " + index); var time = this.getTime(); if (time != null) parts.push("time: " + f.number(time)); if (this._distance != null) parts.push("distance: " + f.number(this._distance)); return "{ " + parts.join(", ") + " }" }, isTouching: function() { var inter = this._intersection; if (inter && this.getTangent().isCollinear(inter.getTangent())) { var curve1 = this.getCurve(), curve2 = inter.getCurve(); return !(curve1.isStraight() && curve2.isStraight() && curve1.getLine().intersect(curve2.getLine())) } return false }, isCrossing: function() { var inter = this._intersection; if (!inter) return false; var t1 = this.getTime(), t2 = inter.getTime(), tMin = 1e-8, tMax = 1 - tMin, t1Inside = t1 >= tMin && t1 <= tMax, t2Inside = t2 >= tMin && t2 <= tMax; if (t1Inside && t2Inside) return !this.isTouching(); var c2 = this.getCurve(), c1 = t1 < tMin ? c2.getPrevious() : c2, c4 = inter.getCurve(), c3 = t2 < tMin ? c4.getPrevious() : c4; if (t1 > tMax) c2 = c2.getNext(); if (t2 > tMax) c4 = c4.getNext(); if (!c1 || !c2 || !c3 || !c4) return false; var offsets = []; function addOffsets(curve, end) { var v = curve.getValues(), roots = Curve.classify(v).roots || Curve.getPeaks(v), count = roots.length, t = end && count > 1 ? roots[count - 1] : count > 0 ? roots[0] : .5; offsets.push(Curve.getLength(v, end ? t : 0, end ? 1 : t) / 2) } function isInRange(angle, min, max) { return min < max ? angle > min && angle < max : angle > min || angle < max } if (!t1Inside) { addOffsets(c1, true); addOffsets(c2, false) } if (!t2Inside) { addOffsets(c3, true); addOffsets(c4, false) } var pt = this.getPoint(), offset = Math.min.apply(Math, offsets), v2 = t1Inside ? c2.getTangentAtTime(t1) : c2.getPointAt(offset).subtract(pt), v1 = t1Inside ? v2.negate() : c1.getPointAt(-offset).subtract(pt), v4 = t2Inside ? c4.getTangentAtTime(t2) : c4.getPointAt(offset).subtract(pt), v3 = t2Inside ? v4.negate() : c3.getPointAt(-offset).subtract(pt), a1 = v1.getAngle(), a2 = v2.getAngle(), a3 = v3.getAngle(), a4 = v4.getAngle(); return !!(t1Inside ? isInRange(a1, a3, a4) ^ isInRange(a2, a3, a4) && isInRange(a1, a4, a3) ^ isInRange(a2, a4, a3) : isInRange(a3, a1, a2) ^ isInRange(a4, a1, a2) && isInRange(a3, a2, a1) ^ isInRange(a4, a2, a1)) }, hasOverlap: function() { return !!this._overlap } }, Base.each(Curve._evaluateMethods, function(name) { var get = name + "At"; this[name] = function() { var curve = this.getCurve(), time = this.getTime(); return time != null && curve && curve[get](time, true) } }, { preserve: true }), new function() { function insert(locations, loc, merge) { var length = locations.length, l = 0, r = length - 1; function search(index, dir) { for (var i = index + dir; i >= -1 && i <= length; i += dir) { var loc2 = locations[(i % length + length) % length]; if (!loc.getPoint().isClose(loc2.getPoint(), 1e-7)) break; if (loc.equals(loc2)) return loc2 } return null } while (l <= r) { var m = l + r >>> 1, loc2 = locations[m], found; if (merge && (found = loc.equals(loc2) ? loc2 : search(m, -1) || search(m, 1))) { if (loc._overlap) { found._overlap = found._intersection._overlap = true } return found } var path1 = loc.getPath(), path2 = loc2.getPath(), diff = path1 !== path2 ? path1._id - path2._id : loc.getIndex() + loc.getTime() - (loc2.getIndex() + loc2.getTime()); if (diff < 0) { r = m - 1 } else { l = m + 1 } } locations.splice(l, 0, loc); return loc } return { statics: { insert: insert, expand: function(locations) { var expanded = locations.slice(); for (var i = locations.length - 1; i >= 0; i--) { insert(expanded, locations[i]._intersection, false) } return expanded } } } }); var PathItem = Item.extend({ _class: "PathItem", _selectBounds: false, _canScaleStroke: true, beans: true, initialize: function PathItem() {}, statics: { create: function(arg) { var data, segments, compound; if (Base.isPlainObject(arg)) { segments = arg.segments; data = arg.pathData } else if (Array.isArray(arg)) { segments = arg } else if (typeof arg === "string") { data = arg } if (segments) { var first = segments[0]; compound = first && Array.isArray(first[0]) } else if (data) { compound = (data.match(/m/gi) || []).length > 1 || /z\s*\S+/i.test(data) } var ctor = compound ? CompoundPath : Path; return new ctor(arg) } }, _asPathItem: function() { return this }, isClockwise: function() { return this.getArea() >= 0 }, setClockwise: function(clockwise) { if (this.isClockwise() != (clockwise = !!clockwise)) this.reverse() }, setPathData: function(data) { var parts = data && data.match(/[mlhvcsqtaz][^mlhvcsqtaz]*/gi), coords, relative = false, previous, control, current = new Point, start = new Point; function getCoord(index, coord) { var val = +coords[index]; if (relative) val += current[coord]; return val } function getPoint(index) { return new Point(getCoord(index, "x"), getCoord(index + 1, "y")) } this.clear(); for (var i = 0, l = parts && parts.length; i < l; i++) { var part = parts[i], command = part[0], lower = command.toLowerCase(); coords = part.match(/[+-]?(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?/g); var length = coords && coords.length; relative = command === lower; if (previous === "z" && !/[mz]/.test(lower)) this.moveTo(current); switch (lower) { case "m": case "l": var move = lower === "m"; for (var j = 0; j < length; j += 2) { this[move ? "moveTo" : "lineTo"](current = getPoint(j)); if (move) { start = current; move = false } } control = current; break; case "h": case "v": var coord = lower === "h" ? "x" : "y"; current = current.clone(); for (var j = 0; j < length; j++) { current[coord] = getCoord(j, coord); this.lineTo(current) } control = current; break; case "c": for (var j = 0; j < length; j += 6) { this.cubicCurveTo(getPoint(j), control = getPoint(j + 2), current = getPoint(j + 4)) } break; case "s": for (var j = 0; j < length; j += 4) { this.cubicCurveTo(/[cs]/.test(previous) ? current.multiply(2).subtract(control) : current, control = getPoint(j), current = getPoint(j + 2)); previous = lower } break; case "q": for (var j = 0; j < length; j += 4) { this.quadraticCurveTo(control = getPoint(j), current = getPoint(j + 2)) } break; case "t": for (var j = 0; j < length; j += 2) { this.quadraticCurveTo(control = /[qt]/.test(previous) ? current.multiply(2).subtract(control) : current, current = getPoint(j)); previous = lower } break; case "a": for (var j = 0; j < length; j += 7) { this.arcTo(current = getPoint(j + 5), new Size(+coords[j], +coords[j + 1]), +coords[j + 2], +coords[j + 4], +coords[j + 3]) } break; case "z": this.closePath(1e-12); current = start; break } previous = lower } }, _canComposite: function() { return !(this.hasFill() && this.hasStroke()) }, _contains: function(point) { var winding = point.isInside(this.getBounds({ internal: true, handle: true })) ? this._getWinding(point) : {}; return winding.onPath || !!(this.getFillRule() === "evenodd" ? winding.windingL & 1 || winding.windingR & 1 : winding.winding) }, getIntersections: function(path, include, _matrix, _returnFirst) { var self = this === path || !path, matrix1 = this._matrix._orNullIfIdentity(), matrix2 = self ? matrix1 : (_matrix || path._matrix)._orNullIfIdentity(); return self || this.getBounds(matrix1).intersects(path.getBounds(matrix2), 1e-12) ? Curve.getIntersections(this.getCurves(), !self && path.getCurves(), include, matrix1, matrix2, _returnFirst) : [] }, getCrossings: function(path) { return this.getIntersections(path, function(inter) { return inter.hasOverlap() || inter.isCrossing() }) }, getNearestLocation: function() { var point = Point.read(arguments), curves = this.getCurves(), minDist = Infinity, minLoc = null; for (var i = 0, l = curves.length; i < l; i++) { var loc = curves[i].getNearestLocation(point); if (loc._distance < minDist) { minDist = loc._distance; minLoc = loc } } return minLoc }, getNearestPoint: function() { var loc = this.getNearestLocation.apply(this, arguments); return loc ? loc.getPoint() : loc }, interpolate: function(from, to, factor) { var isPath = !this._children, name = isPath ? "_segments" : "_children", itemsFrom = from[name], itemsTo = to[name], items = this[name]; if (!itemsFrom || !itemsTo || itemsFrom.length !== itemsTo.length) { throw new Error("Invalid operands in interpolate() call: " + from + ", " + to) } var current = items.length, length = itemsTo.length; if (current < length) { var ctor = isPath ? Segment : Path; for (var i = current; i < length; i++) { this.add(new ctor) } } else if (current > length) { this[isPath ? "removeSegments" : "removeChildren"](length, current) } for (var i = 0; i < length; i++) { items[i].interpolate(itemsFrom[i], itemsTo[i], factor) } if (isPath) { this.setClosed(from._closed); this._changed(9) } }, compare: function(path) { var ok = false; if (path) { var paths1 = this._children || [this], paths2 = path._children ? path._children.slice() : [path], length1 = paths1.length, length2 = paths2.length, matched = [], count = 0; ok = true; for (var i1 = length1 - 1; i1 >= 0 && ok; i1--) { var path1 = paths1[i1]; ok = false; for (var i2 = length2 - 1; i2 >= 0 && !ok; i2--) { if (path1.compare(paths2[i2])) { if (!matched[i2]) { matched[i2] = true; count++ } ok = true } } } ok = ok && count === length2 } return ok } }); var Path = PathItem.extend({ _class: "Path", _serializeFields: { segments: [], closed: false }, initialize: function Path(arg) { this._closed = false; this._segments = []; this._version = 0; var segments = Array.isArray(arg) ? typeof arg[0] === "object" ? arg : arguments : arg && (arg.size === undefined && (arg.x !== undefined || arg.point !== undefined)) ? arguments : null; if (segments && segments.length > 0) { this.setSegments(segments) } else { this._curves = undefined; this._segmentSelection = 0; if (!segments && typeof arg === "string") { this.setPathData(arg); arg = null } } this._initialize(!segments && arg) }, _equals: function(item) { return this._closed === item._closed && Base.equals(this._segments, item._segments) }, copyContent: function(source) { this.setSegments(source._segments); this._closed = source._closed }, _changed: function _changed(flags) { _changed.base.call(this, flags); if (flags & 8) { this._length = this._area = undefined; if (flags & 32) { this._version++ } else if (this._curves) { for (var i = 0, l = this._curves.length; i < l; i++) this._curves[i]._changed() } } else if (flags & 64) { this._bounds = undefined } }, getStyle: function() { var parent = this._parent; return (parent instanceof CompoundPath ? parent : this)._style }, getSegments: function() { return this._segments }, setSegments: function(segments) { var fullySelected = this.isFullySelected(), length = segments && segments.length; this._segments.length = 0; this._segmentSelection = 0; this._curves = undefined; if (length) { var last = segments[length - 1]; if (typeof last === "boolean") { this.setClosed(last); length-- } this._add(Segment.readList(segments, 0, {}, length)) } if (fullySelected) this.setFullySelected(true) }, getFirstSegment: function() { return this._segments[0] }, getLastSegment: function() { return this._segments[this._segments.length - 1] }, getCurves: function() { var curves = this._curves, segments = this._segments; if (!curves) { var length = this._countCurves(); curves = this._curves = new Array(length); for (var i = 0; i < length; i++) curves[i] = new Curve(this, segments[i], segments[i + 1] || segments[0]) } return curves }, getFirstCurve: function() { return this.getCurves()[0] }, getLastCurve: function() { var curves = this.getCurves(); return curves[curves.length - 1] }, isClosed: function() { return this._closed }, setClosed: function(closed) { if (this._closed != (closed = !!closed)) { this._closed = closed; if (this._curves) { var length = this._curves.length = this._countCurves(); if (closed) this._curves[length - 1] = new Curve(this, this._segments[length - 1], this._segments[0]) } this._changed(41) } } }, { beans: true, getPathData: function(_matrix, _precision) { var segments = this._segments, length = segments.length, f = new Formatter(_precision), coords = new Array(6), first = true, curX, curY, prevX, prevY, inX, inY, outX, outY, parts = []; function addSegment(segment, skipLine) { segment._transformCoordinates(_matrix, coords); curX = coords[0]; curY = coords[1]; if (first) { parts.push("M" + f.pair(curX, curY)); first = false } else { inX = coords[2]; inY = coords[3]; if (inX === curX && inY === curY && outX === prevX && outY === prevY) { if (!skipLine) { var dx = curX - prevX, dy = curY - prevY; parts.push(dx === 0 ? "v" + f.number(dy) : dy === 0 ? "h" + f.number(dx) : "l" + f.pair(dx, dy)) } } else { parts.push("c" + f.pair(outX - prevX, outY - prevY) + " " + f.pair(inX - prevX, inY - prevY) + " " + f.pair(curX - prevX, curY - prevY)) } } prevX = curX; prevY = curY; outX = coords[4]; outY = coords[5] } if (!length) return ""; for (var i = 0; i < length; i++) addSegment(segments[i]); if (this._closed && length > 0) { addSegment(segments[0], true); parts.push("z") } return parts.join("") }, isEmpty: function() { return !this._segments.length }, _transformContent: function(matrix) { var segments = this._segments, coords = new Array(6); for (var i = 0, l = segments.length; i < l; i++) segments[i]._transformCoordinates(matrix, coords, true); return true }, _add: function(segs, index) { var segments = this._segments, curves = this._curves, amount = segs.length, append = index == null, index = append ? segments.length : index; for (var i = 0; i < amount; i++) { var segment = segs[i]; if (segment._path) segment = segs[i] = segment.clone(); segment._path = this; segment._index = index + i; if (segment._selection) this._updateSelection(segment, 0, segment._selection) } if (append) { Base.push(segments, segs) } else { segments.splice.apply(segments, [index, 0].concat(segs)); for (var i = index + amount, l = segments.length; i < l; i++) segments[i]._index = i } if (curves) { var total = this._countCurves(), start = index > 0 && index + amount - 1 === total ? index - 1 : index, insert = start, end = Math.min(start + amount, total); if (segs._curves) { curves.splice.apply(curves, [start, 0].concat(segs._curves)); insert += segs._curves.length } for (var i = insert; i < end; i++) curves.splice(i, 0, new Curve(this, null, null)); this._adjustCurves(start, end) } this._changed(41); return segs }, _adjustCurves: function(start, end) { var segments = this._segments, curves = this._curves, curve; for (var i = start; i < end; i++) { curve = curves[i]; curve._path = this; curve._segment1 = segments[i]; curve._segment2 = segments[i + 1] || segments[0]; curve._changed() } if (curve = curves[this._closed && !start ? segments.length - 1 : start - 1]) { curve._segment2 = segments[start] || segments[0]; curve._changed() } if (curve = curves[end]) { curve._segment1 = segments[end]; curve._changed() } }, _countCurves: function() { var length = this._segments.length; return !this._closed && length > 0 ? length - 1 : length }, add: function(segment1) { return arguments.length > 1 && typeof segment1 !== "number" ? this._add(Segment.readList(arguments)) : this._add([Segment.read(arguments)])[0] }, insert: function(index, segment1) { return arguments.length > 2 && typeof segment1 !== "number" ? this._add(Segment.readList(arguments, 1), index) : this._add([Segment.read(arguments, 1)], index)[0] }, addSegment: function() { return this._add([Segment.read(arguments)])[0] }, insertSegment: function(index) { return this._add([Segment.read(arguments, 1)], index)[0] }, addSegments: function(segments) { return this._add(Segment.readList(segments)) }, insertSegments: function(index, segments) { return this._add(Segment.readList(segments), index) }, removeSegment: function(index) { return this.removeSegments(index, index + 1)[0] || null }, removeSegments: function(start, end, _includeCurves) { start = start || 0; end = Base.pick(end, this._segments.length); var segments = this._segments, curves = this._curves, count = segments.length, removed = segments.splice(start, end - start), amount = removed.length; if (!amount) return removed; for (var i = 0; i < amount; i++) { var segment = removed[i]; if (segment._selection) this._updateSelection(segment, segment._selection, 0); segment._index = segment._path = null } for (var i = start, l = segments.length; i < l; i++) segments[i]._index = i; if (curves) { var index = start > 0 && end === count + (this._closed ? 1 : 0) ? start - 1 : start, curves = curves.splice(index, amount); for (var i = curves.length - 1; i >= 0; i--) curves[i]._path = null; if (_includeCurves) removed._curves = curves.slice(1); this._adjustCurves(index, index) } this._changed(41); return removed }, clear: "#removeSegments", hasHandles: function() { var segments = this._segments; for (var i = 0, l = segments.length; i < l; i++) { if (segments[i].hasHandles()) return true } return false }, clearHandles: function() { var segments = this._segments; for (var i = 0, l = segments.length; i < l; i++) segments[i].clearHandles() }, getLength: function() { if (this._length == null) { var curves = this.getCurves(), length = 0; for (var i = 0, l = curves.length; i < l; i++) length += curves[i].getLength(); this._length = length } return this._length }, getArea: function() { var area = this._area; if (area == null) { var segments = this._segments, closed = this._closed; area = 0; for (var i = 0, l = segments.length; i < l; i++) { var last = i + 1 === l; area += Curve.getArea(Curve.getValues(segments[i], segments[last ? 0 : i + 1], null, last && !closed)) } this._area = area } return area }, isFullySelected: function() { var length = this._segments.length; return this.isSelected() && length > 0 && this._segmentSelection === length * 7 }, setFullySelected: function(selected) { if (selected) this._selectSegments(true); this.setSelected(selected) }, setSelection: function setSelection(selection) { if (!(selection & 1)) this._selectSegments(false); setSelection.base.call(this, selection) }, _selectSegments: function(selected) { var segments = this._segments, length = segments.length, selection = selected ? 7 : 0; this._segmentSelection = selection * length; for (var i = 0; i < length; i++) segments[i]._selection = selection }, _updateSelection: function(segment, oldSelection, newSelection) { segment._selection = newSelection; var selection = this._segmentSelection += newSelection - oldSelection; if (selection > 0) this.setSelected(true) }, divideAt: function(location) { var loc = this.getLocationAt(location), curve; return loc && (curve = loc.getCurve().divideAt(loc.getCurveOffset())) ? curve._segment1 : null }, splitAt: function(location) { var loc = this.getLocationAt(location), index = loc && loc.index, time = loc && loc.time, tMin = 1e-8, tMax = 1 - tMin; if (time > tMax) { index++; time = 0 } var curves = this.getCurves(); if (index >= 0 && index < curves.length) { if (time >= tMin) { curves[index++].divideAtTime(time) } var segs = this.removeSegments(index, this._segments.length, true), path; if (this._closed) { this.setClosed(false); path = this } else { path = new Path(Item.NO_INSERT); path.insertAbove(this); path.copyAttributes(this) } path._add(segs, 0); this.addSegment(segs[0]); return path } return null }, split: function(index, time) { var curve, location = time === undefined ? index : (curve = this.getCurves()[index]) && curve.getLocationAtTime(time); return location != null ? this.splitAt(location) : null }, join: function(path, tolerance) { var epsilon = tolerance || 0; if (path && path !== this) { var segments = path._segments, last1 = this.getLastSegment(), last2 = path.getLastSegment(); if (!last2) return this; if (last1 && last1._point.isClose(last2._point, epsilon)) path.reverse(); var first2 = path.getFirstSegment(); if (last1 && last1._point.isClose(first2._point, epsilon)) { last1.setHandleOut(first2._handleOut); this._add(segments.slice(1)) } else { var first1 = this.getFirstSegment(); if (first1 && first1._point.isClose(first2._point, epsilon)) path.reverse(); last2 = path.getLastSegment(); if (first1 && first1._point.isClose(last2._point, epsilon)) { first1.setHandleIn(last2._handleIn); this._add(segments.slice(0, segments.length - 1), 0) } else { this._add(segments.slice()) } } if (path._closed) this._add([segments[0]]); path.remove() } var first = this.getFirstSegment(), last = this.getLastSegment(); if (first !== last && first._point.isClose(last._point, epsilon)) { first.setHandleIn(last._handleIn); last.remove(); this.setClosed(true) } return this }, reduce: function(options) { var curves = this.getCurves(), simplify = options && options.simplify, tolerance = simplify ? 1e-7 : 0; for (var i = curves.length - 1; i >= 0; i--) { var curve = curves[i]; if (!curve.hasHandles() && (!curve.hasLength(tolerance) || simplify && curve.isCollinear(curve.getNext()))) curve.remove() } return this }, reverse: function() { this._segments.reverse(); for (var i = 0, l = this._segments.length; i < l; i++) { var segment = this._segments[i]; var handleIn = segment._handleIn; segment._handleIn = segment._handleOut; segment._handleOut = handleIn; segment._index = i } this._curves = null; this._changed(9) }, flatten: function(flatness) { var flattener = new PathFlattener(this, flatness || .25, 256, true), parts = flattener.parts, length = parts.length, segments = []; for (var i = 0; i < length; i++) { segments.push(new Segment(parts[i].curve.slice(0, 2))) } if (!this._closed && length > 0) { segments.push(new Segment(parts[length - 1].curve.slice(6))) } this.setSegments(segments) }, simplify: function(tolerance) { var segments = new PathFitter(this).fit(tolerance || 2.5); if (segments) this.setSegments(segments); return !!segments }, smooth: function(options) { var that = this, opts = options || {}, type = opts.type || "asymmetric", segments = this._segments, length = segments.length, closed = this._closed; function getIndex(value, _default) { var index = value && value.index; if (index != null) { var path = value.path; if (path && path !== that) throw new Error(value._class + " " + index + " of " + path + " is not part of " + that); if (_default && value instanceof Curve) index++ } else { index = typeof value === "number" ? value : _default } return Math.min(index < 0 && closed ? index % length : index < 0 ? index + length : index, length - 1) } var loop = closed && opts.from === undefined && opts.to === undefined, from = getIndex(opts.from, 0), to = getIndex(opts.to, length - 1); if (from > to) { if (closed) { from -= length } else { var tmp = from; from = to; to = tmp } } if (/^(?:asymmetric|continuous)$/.test(type)) { var asymmetric = type === "asymmetric", min = Math.min, amount = to - from + 1, n = amount - 1, padding = loop ? min(amount, 4) : 1, paddingLeft = padding, paddingRight = padding, knots = []; if (!closed) { paddingLeft = min(1, from); paddingRight = min(1, length - to - 1) } n += paddingLeft + paddingRight; if (n <= 1) return; for (var i = 0, j = from - paddingLeft; i <= n; i++, j++) { knots[i] = segments[(j < 0 ? j + length : j) % length]._point } var x = knots[0]._x + 2 * knots[1]._x, y = knots[0]._y + 2 * knots[1]._y, f = 2, n_1 = n - 1, rx = [x], ry = [y], rf = [f], px = [], py = []; for (var i = 1; i < n; i++) { var internal = i < n_1, a = internal ? 1 : asymmetric ? 1 : 2, b = internal ? 4 : asymmetric ? 2 : 7, u = internal ? 4 : asymmetric ? 3 : 8, v = internal ? 2 : asymmetric ? 0 : 1, m = a / f; f = rf[i] = b - m; x = rx[i] = u * knots[i]._x + v * knots[i + 1]._x - m * x; y = ry[i] = u * knots[i]._y + v * knots[i + 1]._y - m * y } px[n_1] = rx[n_1] / rf[n_1]; py[n_1] = ry[n_1] / rf[n_1]; for (var i = n - 2; i >= 0; i--) { px[i] = (rx[i] - px[i + 1]) / rf[i]; py[i] = (ry[i] - py[i + 1]) / rf[i] } px[n] = (3 * knots[n]._x - px[n_1]) / 2; py[n] = (3 * knots[n]._y - py[n_1]) / 2; for (var i = paddingLeft, max = n - paddingRight, j = from; i <= max; i++, j++) { var segment = segments[j < 0 ? j + length : j], pt = segment._point, hx = px[i] - pt._x, hy = py[i] - pt._y; if (loop || i < max) segment.setHandleOut(hx, hy); if (loop || i > paddingLeft) segment.setHandleIn(-hx, -hy) } } else { for (var i = from; i <= to; i++) { segments[i < 0 ? i + length : i].smooth(opts, !loop && i === from, !loop && i === to) } } }, toShape: function(insert) { if (!this._closed) return null; var segments = this._segments, type, size, radius, topCenter; function isCollinear(i, j) { var seg1 = segments[i], seg2 = seg1.getNext(), seg3 = segments[j], seg4 = seg3.getNext(); return seg1._handleOut.isZero() && seg2._handleIn.isZero() && seg3._handleOut.isZero() && seg4._handleIn.isZero() && seg2._point.subtract(seg1._point).isCollinear(seg4._point.subtract(seg3._point)) } function isOrthogonal(i) { var seg2 = segments[i], seg1 = seg2.getPrevious(), seg3 = seg2.getNext(); return seg1._handleOut.isZero() && seg2._handleIn.isZero() && seg2._handleOut.isZero() && seg3._handleIn.isZero() && seg2._point.subtract(seg1._point).isOrthogonal(seg3._point.subtract(seg2._point)) } function isArc(i) { var seg1 = segments[i], seg2 = seg1.getNext(), handle1 = seg1._handleOut, handle2 = seg2._handleIn, kappa = .5522847498307936; if (handle1.isOrthogonal(handle2)) { var pt1 = seg1._point, pt2 = seg2._point, corner = new Line(pt1, handle1, true).intersect(new Line(pt2, handle2, true), true); return corner && Numerical.isZero(handle1.getLength() / corner.subtract(pt1).getLength() - kappa) && Numerical.isZero(handle2.getLength() / corner.subtract(pt2).getLength() - kappa) } return false } function getDistance(i, j) { return segments[i]._point.getDistance(segments[j]._point) } if (!this.hasHandles() && segments.length === 4 && isCollinear(0, 2) && isCollinear(1, 3) && isOrthogonal(1)) { type = Shape.Rectangle; size = new Size(getDistance(0, 3), getDistance(0, 1)); topCenter = segments[1]._point.add(segments[2]._point).divide(2) } else if (segments.length === 8 && isArc(0) && isArc(2) && isArc(4) && isArc(6) && isCollinear(1, 5) && isCollinear(3, 7)) { type = Shape.Rectangle; size = new Size(getDistance(1, 6), getDistance(0, 3)); radius = size.subtract(new Size(getDistance(0, 7), getDistance(1, 2))).divide(2); topCenter = segments[3]._point.add(segments[4]._point).divide(2) } else if (segments.length === 4 && isArc(0) && isArc(1) && isArc(2) && isArc(3)) { if (Numerical.isZero(getDistance(0, 2) - getDistance(1, 3))) { type = Shape.Circle; radius = getDistance(0, 2) / 2 } else { type = Shape.Ellipse; radius = new Size(getDistance(2, 0) / 2, getDistance(3, 1) / 2) } topCenter = segments[1]._point } if (type) { var center = this.getPosition(true), shape = new type({ center: center, size: size, radius: radius, insert: false }); shape.copyAttributes(this, true); shape._matrix.prepend(this._matrix); shape.rotate(topCenter.subtract(center).getAngle() + 90); if (insert === undefined || insert) shape.insertAbove(this); return shape } return null }, toPath: "#clone", compare: function compare(path) { if (!path || path instanceof CompoundPath) return compare.base.call(this, path); var curves1 = this.getCurves(), curves2 = path.getCurves(), length1 = curves1.length, length2 = curves2.length; if (!length1 || !length2) { return length1 == length2 } var v1 = curves1[0].getValues(), values2 = [], pos1 = 0, pos2, end1 = 0, end2; for (var i = 0; i < length2; i++) { var v2 = curves2[i].getValues(); values2.push(v2); var overlaps = Curve.getOverlaps(v1, v2); if (overlaps) { pos2 = !i && overlaps[0][0] > 0 ? length2 - 1 : i; end2 = overlaps[0][1]; break } } var abs = Math.abs, epsilon = 1e-8, v2 = values2[pos2], start2; while (v1 && v2) { var overlaps = Curve.getOverlaps(v1, v2); if (overlaps) { var t1 = overlaps[0][0]; if (abs(t1 - end1) < epsilon) { end1 = overlaps[1][0]; if (end1 === 1) { v1 = ++pos1 < length1 ? curves1[pos1].getValues() : null; end1 = 0 } var t2 = overlaps[0][1]; if (abs(t2 - end2) < epsilon) { if (!start2) start2 = [pos2, t2]; end2 = overlaps[1][1]; if (end2 === 1) { if (++pos2 >= length2) pos2 = 0; v2 = values2[pos2] || curves2[pos2].getValues(); end2 = 0 } if (!v1) { return start2[0] === pos2 && start2[1] === end2 } continue } } } break } return false }, _hitTestSelf: function(point, options, viewMatrix, strokeMatrix) { var that = this, style = this.getStyle(), segments = this._segments, numSegments = segments.length, closed = this._closed, tolerancePadding = options._tolerancePadding, strokePadding = tolerancePadding, join, cap, miterLimit, area, loc, res, hitStroke = options.stroke && style.hasStroke(), hitFill = options.fill && style.hasFill(), hitCurves = options.curves, strokeRadius = hitStroke ? style.getStrokeWidth() / 2 : hitFill && options.tolerance > 0 || hitCurves ? 0 : null; if (strokeRadius !== null) { if (strokeRadius > 0) { join = style.getStrokeJoin(); cap = style.getStrokeCap(); miterLimit = style.getMiterLimit(); strokePadding = strokePadding.add(Path._getStrokePadding(strokeRadius, strokeMatrix)) } else { join = cap = "round" } } function isCloseEnough(pt, padding) { return point.subtract(pt).divide(padding).length <= 1 } function checkSegmentPoint(seg, pt, name) { if (!options.selected || pt.isSelected()) { var anchor = seg._point; if (pt !== anchor) pt = pt.add(anchor); if (isCloseEnough(pt, strokePadding)) { return new HitResult(name, that, { segment: seg, point: pt }) } } } function checkSegmentPoints(seg, ends) { return (ends || options.segments) && checkSegmentPoint(seg, seg._point, "segment") || !ends && options.handles && (checkSegmentPoint(seg, seg._handleIn, "handle-in") || checkSegmentPoint(seg, seg._handleOut, "handle-out")) } function addToArea(point) { area.add(point) } function checkSegmentStroke(segment) { var isJoin = closed || segment._index > 0 && segment._index < numSegments - 1; if ((isJoin ? join : cap) === "round") { return isCloseEnough(segment._point, strokePadding) } else { area = new Path({ internal: true, closed: true }); if (isJoin) { if (!segment.isSmooth()) { Path._addBevelJoin(segment, join, strokeRadius, miterLimit, null, strokeMatrix, addToArea, true) } } else if (cap === "square") { Path._addSquareCap(segment, cap, strokeRadius, null, strokeMatrix, addToArea, true) } if (!area.isEmpty()) { var loc; return area.contains(point) || (loc = area.getNearestLocation(point)) && isCloseEnough(loc.getPoint(), tolerancePadding) } } } if (options.ends && !options.segments && !closed) { if (res = checkSegmentPoints(segments[0], true) || checkSegmentPoints(segments[numSegments - 1], true)) return res } else if (options.segments || options.handles) { for (var i = 0; i < numSegments; i++) if (res = checkSegmentPoints(segments[i])) return res } if (strokeRadius !== null) { loc = this.getNearestLocation(point); if (loc) { var time = loc.getTime(); if (time === 0 || time === 1 && numSegments > 1) { if (!checkSegmentStroke(loc.getSegment())) loc = null } else if (!isCloseEnough(loc.getPoint(), strokePadding)) { loc = null } } if (!loc && join === "miter" && numSegments > 1) { for (var i = 0; i < numSegments; i++) { var segment = segments[i]; if (point.getDistance(segment._point) <= miterLimit * strokeRadius && checkSegmentStroke(segment)) { loc = segment.getLocation(); break } } } } return !loc && hitFill && this._contains(point) || loc && !hitStroke && !hitCurves ? new HitResult("fill", this) : loc ? new HitResult(hitStroke ? "stroke" : "curve", this, { location: loc, point: loc.getPoint() }) : null } }, Base.each(Curve._evaluateMethods, function(name) { this[name + "At"] = function(offset) { var loc = this.getLocationAt(offset); return loc && loc[name]() } }, { beans: false, getLocationOf: function() { var point = Point.read(arguments), curves = this.getCurves(); for (var i = 0, l = curves.length; i < l; i++) { var loc = curves[i].getLocationOf(point); if (loc) return loc } return null }, getOffsetOf: function() { var loc = this.getLocationOf.apply(this, arguments); return loc ? loc.getOffset() : null }, getLocationAt: function(offset) { if (typeof offset === "number") { var curves = this.getCurves(), length = 0; for (var i = 0, l = curves.length; i < l; i++) { var start = length, curve = curves[i]; length += curve.getLength(); if (length > offset) { return curve.getLocationAt(offset - start) } } if (curves.length > 0 && offset <= this.getLength()) { return new CurveLocation(curves[curves.length - 1], 1) } } else if (offset && offset.getPath && offset.getPath() === this) { return offset } return null }, getOffsetsWithTangent: function() { var tangent = Point.read(arguments); if (tangent.isZero()) { return [] } var offsets = []; var curveStart = 0; var curves = this.getCurves(); for (var i = 0, l = curves.length; i < l; i++) { var curve = curves[i]; var curveTimes = curve.getTimesWithTangent(tangent); for (var j = 0, m = curveTimes.length; j < m; j++) { var offset = curveStart + curve.getOffsetAtTime(curveTimes[j]); if (offsets.indexOf(offset) < 0) { offsets.push(offset) } } curveStart += curve.length } return offsets } }), new function() { function drawHandles(ctx, segments, matrix, size) { var half = size / 2, coords = new Array(6), pX, pY; function drawHandle(index) { var hX = coords[index], hY = coords[index + 1]; if (pX != hX || pY != hY) { ctx.beginPath(); ctx.moveTo(pX, pY); ctx.lineTo(hX, hY); ctx.stroke(); ctx.beginPath(); ctx.arc(hX, hY, half, 0, Math.PI * 2, true); ctx.fill() } } for (var i = 0, l = segments.length; i < l; i++) { var segment = segments[i], selection = segment._selection; segment._transformCoordinates(matrix, coords); pX = coords[0]; pY = coords[1]; if (selection & 2) drawHandle(2); if (selection & 4) drawHandle(4); ctx.fillRect(pX - half, pY - half, size, size); if (!(selection & 1)) { var fillStyle = ctx.fillStyle; ctx.fillStyle = "#ffffff"; ctx.fillRect(pX - half + 1, pY - half + 1, size - 2, size - 2); ctx.fillStyle = fillStyle } } } function drawSegments(ctx, path, matrix) { var segments = path._segments, length = segments.length, coords = new Array(6), first = true, curX, curY, prevX, prevY, inX, inY, outX, outY; function drawSegment(segment) { if (matrix) { segment._transformCoordinates(matrix, coords); curX = coords[0]; curY = coords[1] } else { var point = segment._point; curX = point._x; curY = point._y } if (first) { ctx.moveTo(curX, curY); first = false } else { if (matrix) { inX = coords[2]; inY = coords[3] } else { var handle = segment._handleIn; inX = curX + handle._x; inY = curY + handle._y } if (inX === curX && inY === curY && outX === prevX && outY === prevY) { ctx.lineTo(curX, curY) } else { ctx.bezierCurveTo(outX, outY, inX, inY, curX, curY) } } prevX = curX; prevY = curY; if (matrix) { outX = coords[4]; outY = coords[5] } else { var handle = segment._handleOut; outX = prevX + handle._x; outY = prevY + handle._y } } for (var i = 0; i < length; i++) drawSegment(segments[i]); if (path._closed && length > 0) drawSegment(segments[0]) } return { _draw: function(ctx, param, viewMatrix, strokeMatrix) { var dontStart = param.dontStart, dontPaint = param.dontFinish || param.clip, style = this.getStyle(), hasFill = style.hasFill(), hasStroke = style.hasStroke(), dashArray = style.getDashArray(), dashLength = !paper.support.nativeDash && hasStroke && dashArray && dashArray.length; if (!dontStart) ctx.beginPath(); if (hasFill || hasStroke && !dashLength || dontPaint) { drawSegments(ctx, this, strokeMatrix); if (this._closed) ctx.closePath() } function getOffset(i) { return dashArray[(i % dashLength + dashLength) % dashLength] } if (!dontPaint && (hasFill || hasStroke)) { this._setStyles(ctx, param, viewMatrix); if (hasFill) { ctx.fill(style.getFillRule()); ctx.shadowColor = "rgba(0,0,0,0)" } if (hasStroke) { if (dashLength) { if (!dontStart) ctx.beginPath(); var flattener = new PathFlattener(this, .25, 32, false, strokeMatrix), length = flattener.length, from = -style.getDashOffset(), to, i = 0; from = from % length; while (from > 0) { from -= getOffset(i--) + getOffset(i--) } while (from < length) { to = from + getOffset(i++); if (from > 0 || to > 0) flattener.drawPart(ctx, Math.max(from, 0), Math.max(to, 0)); from = to + getOffset(i++) } } ctx.stroke() } } }, _drawSelected: function(ctx, matrix) { ctx.beginPath(); drawSegments(ctx, this, matrix); ctx.stroke(); drawHandles(ctx, this._segments, matrix, paper.settings.handleSize) } } }, new function() { function getCurrentSegment(that) { var segments = that._segments; if (!segments.length) throw new Error("Use a moveTo() command first"); return segments[segments.length - 1] } return { moveTo: function() { var segments = this._segments; if (segments.length === 1) this.removeSegment(0); if (!segments.length) this._add([new Segment(Point.read(arguments))]) }, moveBy: function() { throw new Error("moveBy() is unsupported on Path items.") }, lineTo: function() { this._add([new Segment(Point.read(arguments))]) }, cubicCurveTo: function() { var handle1 = Point.read(arguments), handle2 = Point.read(arguments), to = Point.read(arguments), current = getCurrentSegment(this); current.setHandleOut(handle1.subtract(current._point)); this._add([new Segment(to, handle2.subtract(to))]) }, quadraticCurveTo: function() { var handle = Point.read(arguments), to = Point.read(arguments), current = getCurrentSegment(this)._point; this.cubicCurveTo(handle.add(current.subtract(handle).multiply(1 / 3)), handle.add(to.subtract(handle).multiply(1 / 3)), to) }, curveTo: function() { var through = Point.read(arguments), to = Point.read(arguments), t = Base.pick(Base.read(arguments), .5), t1 = 1 - t, current = getCurrentSegment(this)._point, handle = through.subtract(current.multiply(t1 * t1)).subtract(to.multiply(t * t)).divide(2 * t * t1); if (handle.isNaN()) throw new Error("Cannot put a curve through points with parameter = " + t); this.quadraticCurveTo(handle, to) }, arcTo: function() { var abs = Math.abs, sqrt = Math.sqrt, current = getCurrentSegment(this), from = current._point, to = Point.read(arguments), through, peek = Base.peek(arguments), clockwise = Base.pick(peek, true), center, extent, vector, matrix; if (typeof clockwise === "boolean") { var middle = from.add(to).divide(2), through = middle.add(middle.subtract(from).rotate(clockwise ? -90 : 90)) } else if (Base.remain(arguments) <= 2) { through = to; to = Point.read(arguments) } else { var radius = Size.read(arguments), isZero = Numerical.isZero; if (isZero(radius.width) || isZero(radius.height)) return this.lineTo(to); var rotation = Base.read(arguments), clockwise = !!Base.read(arguments), large = !!Base.read(arguments), middle = from.add(to).divide(2), pt = from.subtract(middle).rotate(-rotation), x = pt.x, y = pt.y, rx = abs(radius.width), ry = abs(radius.height), rxSq = rx * rx, rySq = ry * ry, xSq = x * x, ySq = y * y; var factor = sqrt(xSq / rxSq + ySq / rySq); if (factor > 1) { rx *= factor; ry *= factor; rxSq = rx * rx; rySq = ry * ry } factor = (rxSq * rySq - rxSq * ySq - rySq * xSq) / (rxSq * ySq + rySq * xSq); if (abs(factor) < 1e-12) factor = 0; if (factor < 0) throw new Error("Cannot create an arc with the given arguments"); center = new Point(rx * y / ry, -ry * x / rx).multiply((large === clockwise ? -1 : 1) * sqrt(factor)).rotate(rotation).add(middle); matrix = (new Matrix).translate(center).rotate(rotation).scale(rx, ry); vector = matrix._inverseTransform(from); extent = vector.getDirectedAngle(matrix._inverseTransform(to)); if (!clockwise && extent > 0) extent -= 360; else if (clockwise && extent < 0) extent += 360 } if (through) { var l1 = new Line(from.add(through).divide(2), through.subtract(from).rotate(90), true), l2 = new Line(through.add(to).divide(2), to.subtract(through).rotate(90), true), line = new Line(from, to), throughSide = line.getSide(through); center = l1.intersect(l2, true); if (!center) { if (!throughSide) return this.lineTo(to); throw new Error("Cannot create an arc with the given arguments") } vector = from.subtract(center); extent = vector.getDirectedAngle(to.subtract(center)); var centerSide = line.getSide(center, true); if (centerSide === 0) { extent = throughSide * abs(extent) } else if (throughSide === centerSide) { extent += extent < 0 ? 360 : -360 } } var epsilon = 1e-7, ext = abs(extent), count = ext >= 360 ? 4 : Math.ceil((ext - epsilon) / 90), inc = extent / count, half = inc * Math.PI / 360, z = 4 / 3 * Math.sin(half) / (1 + Math.cos(half)), segments = []; for (var i = 0; i <= count; i++) { var pt = to, out = null; if (i < count) { out = vector.rotate(90).multiply(z); if (matrix) { pt = matrix._transformPoint(vector); out = matrix._transformPoint(vector.add(out)).subtract(pt) } else { pt = center.add(vector) } } if (!i) { current.setHandleOut(out) } else { var _in = vector.rotate(-90).multiply(z); if (matrix) { _in = matrix._transformPoint(vector.add(_in)).subtract(pt) } segments.push(new Segment(pt, _in, out)) } vector = vector.rotate(inc) } this._add(segments) }, lineBy: function() { var to = Point.read(arguments), current = getCurrentSegment(this)._point; this.lineTo(current.add(to)) }, curveBy: function() { var through = Point.read(arguments), to = Point.read(arguments), parameter = Base.read(arguments), current = getCurrentSegment(this)._point; this.curveTo(current.add(through), current.add(to), parameter) }, cubicCurveBy: function() { var handle1 = Point.read(arguments), handle2 = Point.read(arguments), to = Point.read(arguments), current = getCurrentSegment(this)._point; this.cubicCurveTo(current.add(handle1), current.add(handle2), current.add(to)) }, quadraticCurveBy: function() { var handle = Point.read(arguments), to = Point.read(arguments), current = getCurrentSegment(this)._point; this.quadraticCurveTo(current.add(handle), current.add(to)) }, arcBy: function() { var current = getCurrentSegment(this)._point, point = current.add(Point.read(arguments)), clockwise = Base.pick(Base.peek(arguments), true); if (typeof clockwise === "boolean") { this.arcTo(point, clockwise) } else { this.arcTo(point, current.add(Point.read(arguments))) } }, closePath: function(tolerance) { this.setClosed(true); this.join(this, tolerance) } } }, { _getBounds: function(matrix, options) { var method = options.handle ? "getHandleBounds" : options.stroke ? "getStrokeBounds" : "getBounds"; return Path[method](this._segments, this._closed, this, matrix, options) }, statics: { getBounds: function(segments, closed, path, matrix, options, strokePadding) { var first = segments[0]; if (!first) return new Rectangle; var coords = new Array(6), prevCoords = first._transformCoordinates(matrix, new Array(6)), min = prevCoords.slice(0, 2), max = min.slice(), roots = new Array(2); function processSegment(segment) { segment._transformCoordinates(matrix, coords); for (var i = 0; i < 2; i++) { Curve._addBounds(prevCoords[i], prevCoords[i + 4], coords[i + 2], coords[i], i, strokePadding ? strokePadding[i] : 0, min, max, roots) } var tmp = prevCoords; prevCoords = coords; coords = tmp } for (var i = 1, l = segments.length; i < l; i++) processSegment(segments[i]); if (closed) processSegment(first); return new Rectangle(min[0], min[1], max[0] - min[0], max[1] - min[1]) }, getStrokeBounds: function(segments, closed, path, matrix, options) { var style = path.getStyle(), stroke = style.hasStroke(), strokeWidth = style.getStrokeWidth(), strokeMatrix = stroke && path._getStrokeMatrix(matrix, options), strokePadding = stroke && Path._getStrokePadding(strokeWidth, strokeMatrix), bounds = Path.getBounds(segments, closed, path, matrix, options, strokePadding); if (!stroke) return bounds; var strokeRadius = strokeWidth / 2, join = style.getStrokeJoin(), cap = style.getStrokeCap(), miterLimit = style.getMiterLimit(), joinBounds = new Rectangle(new Size(strokePadding)); function addPoint(point) { bounds = bounds.include(point) } function addRound(segment) { bounds = bounds.unite(joinBounds.setCenter(segment._point.transform(matrix))) } function addJoin(segment, join) { if (join === "round" || segment.isSmooth()) { addRound(segment) } else { Path._addBevelJoin(segment, join, strokeRadius, miterLimit, matrix, strokeMatrix, addPoint) } } function addCap(segment, cap) { if (cap === "round") { addRound(segment) } else { Path._addSquareCap(segment, cap, strokeRadius, matrix, strokeMatrix, addPoint) } } var length = segments.length - (closed ? 0 : 1); for (var i = 1; i < length; i++) addJoin(segments[i], join); if (closed) { addJoin(segments[0], join) } else if (length > 0) { addCap(segments[0], cap); addCap(segments[segments.length - 1], cap) } return bounds }, _getStrokePadding: function(radius, matrix) { if (!matrix) return [radius, radius]; var hor = new Point(radius, 0).transform(matrix), ver = new Point(0, radius).transform(matrix), phi = hor.getAngleInRadians(), a = hor.getLength(), b = ver.getLength(); var sin = Math.sin(phi), cos = Math.cos(phi), tan = Math.tan(phi), tx = Math.atan2(b * tan, a), ty = Math.atan2(b, tan * a); return [Math.abs(a * Math.cos(tx) * cos + b * Math.sin(tx) * sin), Math.abs(b * Math.sin(ty) * cos + a * Math.cos(ty) * sin)] }, _addBevelJoin: function(segment, join, radius, miterLimit, matrix, strokeMatrix, addPoint, isArea) { var curve2 = segment.getCurve(), curve1 = curve2.getPrevious(), point = curve2.getPoint1().transform(matrix), normal1 = curve1.getNormalAtTime(1).multiply(radius).transform(strokeMatrix), normal2 = curve2.getNormalAtTime(0).multiply(radius).transform(strokeMatrix); if (normal1.getDirectedAngle(normal2) < 0) { normal1 = normal1.negate(); normal2 = normal2.negate() } if (isArea) addPoint(point); addPoint(point.add(normal1)); if (join === "miter") { var corner = new Line(point.add(normal1), new Point(-normal1.y, normal1.x), true).intersect(new Line(point.add(normal2), new Point(-normal2.y, normal2.x), true), true); if (corner && point.getDistance(corner) <= miterLimit * radius) { addPoint(corner) } } addPoint(point.add(normal2)) }, _addSquareCap: function(segment, cap, radius, matrix, strokeMatrix, addPoint, isArea) { var point = segment._point.transform(matrix), loc = segment.getLocation(), normal = loc.getNormal().multiply(loc.getTime() === 0 ? radius : -radius).transform(strokeMatrix); if (cap === "square") { if (isArea) { addPoint(point.subtract(normal)); addPoint(point.add(normal)) } point = point.add(normal.rotate(-90)) } addPoint(point.add(normal)); addPoint(point.subtract(normal)) }, getHandleBounds: function(segments, closed, path, matrix, options) { var style = path.getStyle(), stroke = options.stroke && style.hasStroke(), strokePadding, joinPadding; if (stroke) { var strokeMatrix = path._getStrokeMatrix(matrix, options), strokeRadius = style.getStrokeWidth() / 2, joinRadius = strokeRadius; if (style.getStrokeJoin() === "miter") joinRadius = strokeRadius * style.getMiterLimit(); if (style.getStrokeCap() === "square") joinRadius = Math.max(joinRadius, strokeRadius * Math.SQRT2); strokePadding = Path._getStrokePadding(strokeRadius, strokeMatrix); joinPadding = Path._getStrokePadding(joinRadius, strokeMatrix) } var coords = new Array(6), x1 = Infinity, x2 = -x1, y1 = x1, y2 = x2; for (var i = 0, l = segments.length; i < l; i++) { var segment = segments[i]; segment._transformCoordinates(matrix, coords); for (var j = 0; j < 6; j += 2) { var padding = !j ? joinPadding : strokePadding, paddingX = padding ? padding[0] : 0, paddingY = padding ? padding[1] : 0, x = coords[j], y = coords[j + 1], xn = x - paddingX, xx = x + paddingX, yn = y - paddingY, yx = y + paddingY; if (xn < x1) x1 = xn; if (xx > x2) x2 = xx; if (yn < y1) y1 = yn; if (yx > y2) y2 = yx } } return new Rectangle(x1, y1, x2 - x1, y2 - y1) } } }); Path.inject({ statics: new function() { var kappa = .5522847498307936, ellipseSegments = [new Segment([-1, 0], [0, kappa], [0, -kappa]), new Segment([0, -1], [-kappa, 0], [kappa, 0]), new Segment([1, 0], [0, -kappa], [0, kappa]), new Segment([0, 1], [kappa, 0], [-kappa, 0])]; function createPath(segments, closed, args) { var props = Base.getNamed(args), path = new Path(props && props.insert == false && Item.NO_INSERT); path._add(segments); path._closed = closed; return path.set(props, { insert: true }) } function createEllipse(center, radius, args) { var segments = new Array(4); for (var i = 0; i < 4; i++) { var segment = ellipseSegments[i]; segments[i] = new Segment(segment._point.multiply(radius).add(center), segment._handleIn.multiply(radius), segment._handleOut.multiply(radius)) } return createPath(segments, true, args) } return { Line: function() { return createPath([new Segment(Point.readNamed(arguments, "from")), new Segment(Point.readNamed(arguments, "to"))], false, arguments) }, Circle: function() { var center = Point.readNamed(arguments, "center"), radius = Base.readNamed(arguments, "radius"); return createEllipse(center, new Size(radius), arguments) }, Rectangle: function() { var rect = Rectangle.readNamed(arguments, "rectangle"), radius = Size.readNamed(arguments, "radius", 0, { readNull: true }), bl = rect.getBottomLeft(true), tl = rect.getTopLeft(true), tr = rect.getTopRight(true), br = rect.getBottomRight(true), segments; if (!radius || radius.isZero()) { segments = [new Segment(bl), new Segment(tl), new Segment(tr), new Segment(br)] } else { radius = Size.min(radius, rect.getSize(true).divide(2)); var rx = radius.width, ry = radius.height, hx = rx * kappa, hy = ry * kappa; segments = [new Segment(bl.add(rx, 0), null, [-hx, 0]), new Segment(bl.subtract(0, ry), [0, hy]), new Segment(tl.add(0, ry), null, [0, -hy]), new Segment(tl.add(rx, 0), [-hx, 0], null), new Segment(tr.subtract(rx, 0), null, [hx, 0]), new Segment(tr.add(0, ry), [0, -hy], null), new Segment(br.subtract(0, ry), null, [0, hy]), new Segment(br.subtract(rx, 0), [hx, 0])] } return createPath(segments, true, arguments) }, RoundRectangle: "#Rectangle", Ellipse: function() { var ellipse = Shape._readEllipse(arguments); return createEllipse(ellipse.center, ellipse.radius, arguments) }, Oval: "#Ellipse", Arc: function() { var from = Point.readNamed(arguments, "from"), through = Point.readNamed(arguments, "through"), to = Point.readNamed(arguments, "to"), props = Base.getNamed(arguments), path = new Path(props && props.insert == false && Item.NO_INSERT); path.moveTo(from); path.arcTo(through, to); return path.set(props) }, RegularPolygon: function() { var center = Point.readNamed(arguments, "center"), sides = Base.readNamed(arguments, "sides"), radius = Base.readNamed(arguments, "radius"), step = 360 / sides, three = sides % 3 === 0, vector = new Point(0, three ? -radius : radius), offset = three ? -1 : .5, segments = new Array(sides); for (var i = 0; i < sides; i++) segments[i] = new Segment(center.add(vector.rotate((i + offset) * step))); return createPath(segments, true, arguments) }, Star: function() { var center = Point.readNamed(arguments, "center"), points = Base.readNamed(arguments, "points") * 2, radius1 = Base.readNamed(arguments, "radius1"), radius2 = Base.readNamed(arguments, "radius2"), step = 360 / points, vector = new Point(0, -1), segments = new Array(points); for (var i = 0; i < points; i++) segments[i] = new Segment(center.add(vector.rotate(step * i).multiply(i % 2 ? radius2 : radius1))); return createPath(segments, true, arguments) } } } }); var CompoundPath = PathItem.extend({ _class: "CompoundPath", _serializeFields: { children: [] }, beans: true, initialize: function CompoundPath(arg) { this._children = []; this._namedChildren = {}; if (!this._initialize(arg)) { if (typeof arg === "string") { this.setPathData(arg) } else { this.addChildren(Array.isArray(arg) ? arg : arguments) } } }, insertChildren: function insertChildren(index, items) { var list = items, first = list[0]; if (first && typeof first[0] === "number") list = [list]; for (var i = items.length - 1; i >= 0; i--) { var item = list[i]; if (list === items && !(item instanceof Path)) list = Base.slice(list); if (Array.isArray(item)) { list[i] = new Path({ segments: item, insert: false }) } else if (item instanceof CompoundPath) { list.splice.apply(list, [i, 1].concat(item.removeChildren())); item.remove() } } return insertChildren.base.call(this, index, list) }, reduce: function reduce(options) { var children = this._children; for (var i = children.length - 1; i >= 0; i--) { var path = children[i].reduce(options); if (path.isEmpty()) path.remove() } if (!children.length) { var path = new Path(Item.NO_INSERT); path.copyAttributes(this); path.insertAbove(this); this.remove(); return path } return reduce.base.call(this) }, isClosed: function() { var children = this._children; for (var i = 0, l = children.length; i < l; i++) { if (!children[i]._closed) return false } return true }, setClosed: function(closed) { var children = this._children; for (var i = 0, l = children.length; i < l; i++) { children[i].setClosed(closed) } }, getFirstSegment: function() { var first = this.getFirstChild(); return first && first.getFirstSegment() }, getLastSegment: function() { var last = this.getLastChild(); return last && last.getLastSegment() }, getCurves: function() { var children = this._children, curves = []; for (var i = 0, l = children.length; i < l; i++) { Base.push(curves, children[i].getCurves()) } return curves }, getFirstCurve: function() { var first = this.getFirstChild(); return first && first.getFirstCurve() }, getLastCurve: function() { var last = this.getLastChild(); return last && last.getLastCurve() }, getArea: function() { var children = this._children, area = 0; for (var i = 0, l = children.length; i < l; i++) area += children[i].getArea(); return area }, getLength: function() { var children = this._children, length = 0; for (var i = 0, l = children.length; i < l; i++) length += children[i].getLength(); return length }, getPathData: function(_matrix, _precision) { var children = this._children, paths = []; for (var i = 0, l = children.length; i < l; i++) { var child = children[i], mx = child._matrix; paths.push(child.getPathData(_matrix && !mx.isIdentity() ? _matrix.appended(mx) : _matrix, _precision)) } return paths.join("") }, _hitTestChildren: function _hitTestChildren(point, options, viewMatrix) { return _hitTestChildren.base.call(this, point, options.class === Path || options.type === "path" ? options : Base.set({}, options, { fill: false }), viewMatrix) }, _draw: function(ctx, param, viewMatrix, strokeMatrix) { var children = this._children; if (!children.length) return; param = param.extend({ dontStart: true, dontFinish: true }); ctx.beginPath(); for (var i = 0, l = children.length; i < l; i++) children[i].draw(ctx, param, strokeMatrix); if (!param.clip) { this._setStyles(ctx, param, viewMatrix); var style = this._style; if (style.hasFill()) { ctx.fill(style.getFillRule()); ctx.shadowColor = "rgba(0,0,0,0)" } if (style.hasStroke()) ctx.stroke() } }, _drawSelected: function(ctx, matrix, selectionItems) { var children = this._children; for (var i = 0, l = children.length; i < l; i++) { var child = children[i], mx = child._matrix; if (!selectionItems[child._id]) { child._drawSelected(ctx, mx.isIdentity() ? matrix : matrix.appended(mx)) } } } }, new function() { function getCurrentPath(that, check) { var children = that._children; if (check && !children.length) throw new Error("Use a moveTo() command first"); return children[children.length - 1] } return Base.each(["lineTo", "cubicCurveTo", "quadraticCurveTo", "curveTo", "arcTo", "lineBy", "cubicCurveBy", "quadraticCurveBy", "curveBy", "arcBy"], function(key) { this[key] = function() { var path = getCurrentPath(this, true); path[key].apply(path, arguments) } }, { moveTo: function() { var current = getCurrentPath(this), path = current && current.isEmpty() ? current : new Path(Item.NO_INSERT); if (path !== current) this.addChild(path); path.moveTo.apply(path, arguments) }, moveBy: function() { var current = getCurrentPath(this, true), last = current && current.getLastSegment(), point = Point.read(arguments); this.moveTo(last ? point.add(last._point) : point) }, closePath: function(tolerance) { getCurrentPath(this, true).closePath(tolerance) } }) }, Base.each(["reverse", "flatten", "simplify", "smooth"], function(key) { this[key] = function(param) { var children = this._children, res; for (var i = 0, l = children.length; i < l; i++) { res = children[i][key](param) || res } return res } }, {})); PathItem.inject(new function() { var min = Math.min, max = Math.max, abs = Math.abs, operators = { unite: { 1: true, 2: true }, intersect: { 2: true }, subtract: { 1: true }, exclude: { 1: true, "-1": true } }; function preparePath(path, resolve) { var res = path.clone(false).reduce({ simplify: true }).transform(null, true, true); return resolve ? res.resolveCrossings().reorient(res.getFillRule() === "nonzero", true) : res } function createResult(paths, simplify, path1, path2, options) { var result = new CompoundPath(Item.NO_INSERT); result.addChildren(paths, true); result = result.reduce({ simplify: simplify }); if (!(options && options.insert == false)) { result.insertAbove(path2 && path1.isSibling(path2) && path1.getIndex() < path2.getIndex() ? path2 : path1) } result.copyAttributes(path1, true); return result } function traceBoolean(path1, path2, operation, options) { if (options && (options.trace == false || options.stroke) && /^(subtract|intersect)$/.test(operation)) return splitBoolean(path1, path2, operation); var _path1 = preparePath(path1, true), _path2 = path2 && path1 !== path2 && preparePath(path2, true), operator = operators[operation]; operator[operation] = true; if (_path2 && (operator.subtract || operator.exclude) ^ (_path2.isClockwise() ^ _path1.isClockwise())) _path2.reverse(); var crossings = divideLocations(CurveLocation.expand(_path1.getCrossings(_path2))), paths1 = _path1._children || [_path1], paths2 = _path2 && (_path2._children || [_path2]), segments = [], curves = [], paths; function collect(paths) { for (var i = 0, l = paths.length; i < l; i++) { var path = paths[i]; Base.push(segments, path._segments); Base.push(curves, path.getCurves()); path._overlapsOnly = true } } if (crossings.length) { collect(paths1); if (paths2) collect(paths2); for (var i = 0, l = crossings.length; i < l; i++) { propagateWinding(crossings[i]._segment, _path1, _path2, curves, operator) } for (var i = 0, l = segments.length; i < l; i++) { var segment = segments[i], inter = segment._intersection; if (!segment._winding) { propagateWinding(segment, _path1, _path2, curves, operator) } if (!(inter && inter._overlap)) segment._path._overlapsOnly = false } paths = tracePaths(segments, operator) } else { paths = reorientPaths(paths2 ? paths1.concat(paths2) : paths1.slice(), function(w) { return !!operator[w] }) } return createResult(paths, true, path1, path2, options) } function splitBoolean(path1, path2, operation) { var _path1 = preparePath(path1), _path2 = preparePath(path2), crossings = _path1.getCrossings(_path2), subtract = operation === "subtract", divide = operation === "divide", added = {}, paths = []; function addPath(path) { if (!added[path._id] && (divide || _path2.contains(path.getPointAt(path.getLength() / 2)) ^ subtract)) { paths.unshift(path); return added[path._id] = true } } for (var i = crossings.length - 1; i >= 0; i--) { var path = crossings[i].split(); if (path) { if (addPath(path)) path.getFirstSegment().setHandleIn(0, 0); _path1.getLastSegment().setHandleOut(0, 0) } } addPath(_path1); return createResult(paths, false, path1, path2) } function linkIntersections(from, to) { var prev = from; while (prev) { if (prev === to) return; prev = prev._previous } while (from._next && from._next !== to) from = from._next; if (!from._next) { while (to._previous) to = to._previous; from._next = to; to._previous = from } } function clearCurveHandles(curves) { for (var i = curves.length - 1; i >= 0; i--) curves[i].clearHandles() } function reorientPaths(paths, isInside, clockwise) { var length = paths && paths.length; if (length) { var lookup = Base.each(paths, function(path, i) { this[path._id] = { container: null, winding: path.isClockwise() ? 1 : -1, index: i } }, {}), sorted = paths.slice().sort(function(a, b) { return abs(b.getArea()) - abs(a.getArea()) }), first = sorted[0]; if (clockwise == null) clockwise = first.isClockwise(); for (var i = 0; i < length; i++) { var path1 = sorted[i], entry1 = lookup[path1._id], point = path1.getInteriorPoint(), containerWinding = 0; for (var j = i - 1; j >= 0; j--) { var path2 = sorted[j]; if (path2.contains(point)) { var entry2 = lookup[path2._id]; containerWinding = entry2.winding; entry1.winding += containerWinding; entry1.container = entry2.exclude ? entry2.container : path2; break } } if (isInside(entry1.winding) === isInside(containerWinding)) { entry1.exclude = true; paths[entry1.index] = null } else { var container = entry1.container; path1.setClockwise(container ? !container.isClockwise() : clockwise) } } } return paths } function divideLocations(locations, include, clearLater) { var results = include && [], tMin = 1e-8, tMax = 1 - tMin, clearHandles = false, clearCurves = clearLater || [], clearLookup = clearLater && {}, renormalizeLocs, prevCurve, prevTime; function getId(curve) { return curve._path._id + "." + curve._segment1._index } for (var i = (clearLater && clearLater.length) - 1; i >= 0; i--) { var curve = clearLater[i]; if (curve._path) clearLookup[getId(curve)] = true } for (var i = locations.length - 1; i >= 0; i--) { var loc = locations[i], time = loc._time, origTime = time, exclude = include && !include(loc), curve = loc._curve, segment; if (curve) { if (curve !== prevCurve) { clearHandles = !curve.hasHandles() || clearLookup && clearLookup[getId(curve)]; renormalizeLocs = []; prevTime = null; prevCurve = curve } else if (prevTime >= tMin) { time /= prevTime } } if (exclude) { if (renormalizeLocs) renormalizeLocs.push(loc); continue } else if (include) { results.unshift(loc) } prevTime = origTime; if (time < tMin) { segment = curve._segment1 } else if (time > tMax) { segment = curve._segment2 } else { var newCurve = curve.divideAtTime(time, true); if (clearHandles) clearCurves.push(curve, newCurve); segment = newCurve._segment1; for (var j = renormalizeLocs.length - 1; j >= 0; j--) { var l = renormalizeLocs[j]; l._time = (l._time - time) / (1 - time) } } loc._setSegment(segment); var inter = segment._intersection, dest = loc._intersection; if (inter) { linkIntersections(inter, dest); var other = inter; while (other) { linkIntersections(other._intersection, inter); other = other._next } } else { segment._intersection = dest } } if (!clearLater) clearCurveHandles(clearCurves); return results || locations } function getWinding(point, curves, dir, closed, dontFlip) { var ia = dir ? 1 : 0, io = ia ^ 1, pv = [point.x, point.y], pa = pv[ia], po = pv[io], windingEpsilon = 1e-9, qualityEpsilon = 1e-6, paL = pa - windingEpsilon, paR = pa + windingEpsilon, windingL = 0, windingR = 0, pathWindingL = 0, pathWindingR = 0, onPath = false, onAnyPath = false, quality = 1, roots = [], vPrev, vClose; function addWinding(v) { var o0 = v[io + 0], o3 = v[io + 6]; if (po < min(o0, o3) || po > max(o0, o3)) { return } var a0 = v[ia + 0], a1 = v[ia + 2], a2 = v[ia + 4], a3 = v[ia + 6]; if (o0 === o3) { if (a0 < paR && a3 > paL || a3 < paR && a0 > paL) { onPath = true } return } var t = po === o0 ? 0 : po === o3 ? 1 : paL > max(a0, a1, a2, a3) || paR < min(a0, a1, a2, a3) ? 1 : Curve.solveCubic(v, io, po, roots, 0, 1) > 0 ? roots[0] : 1, a = t === 0 ? a0 : t === 1 ? a3 : Curve.getPoint(v, t)[dir ? "y" : "x"], winding = o0 > o3 ? 1 : -1, windingPrev = vPrev[io] > vPrev[io + 6] ? 1 : -1, a3Prev = vPrev[ia + 6]; if (po !== o0) { if (a < paL) { pathWindingL += winding } else if (a > paR) { pathWindingR += winding } else { onPath = true } if (a > pa - qualityEpsilon && a < pa + qualityEpsilon) quality /= 2 } else { if (winding !== windingPrev) { if (a0 < paL) { pathWindingL += winding } else if (a0 > paR) { pathWindingR += winding } } else if (a0 != a3Prev) { if (a3Prev < paR && a > paR) { pathWindingR += winding; onPath = true } else if (a3Prev > paL && a < paL) { pathWindingL += winding; onPath = true } } quality = 0 } vPrev = v; return !dontFlip && a > paL && a < paR && Curve.getTangent(v, t)[dir ? "x" : "y"] === 0 && getWinding(point, curves, !dir, closed, true) } function handleCurve(v) { var o0 = v[io + 0], o1 = v[io + 2], o2 = v[io + 4], o3 = v[io + 6]; if (po <= max(o0, o1, o2, o3) && po >= min(o0, o1, o2, o3)) { var a0 = v[ia + 0], a1 = v[ia + 2], a2 = v[ia + 4], a3 = v[ia + 6], monoCurves = paL > max(a0, a1, a2, a3) || paR < min(a0, a1, a2, a3) ? [v] : Curve.getMonoCurves(v, dir), res; for (var i = 0, l = monoCurves.length; i < l; i++) { if (res = addWinding(monoCurves[i])) return res } } } for (var i = 0, l = curves.length; i < l; i++) { var curve = curves[i], path = curve._path, v = curve.getValues(), res; if (!i || curves[i - 1]._path !== path) { vPrev = null; if (!path._closed) { vClose = Curve.getValues(path.getLastCurve().getSegment2(), curve.getSegment1(), null, !closed); if (vClose[io] !== vClose[io + 6]) { vPrev = vClose } } if (!vPrev) { vPrev = v; var prev = path.getLastCurve(); while (prev && prev !== curve) { var v2 = prev.getValues(); if (v2[io] !== v2[io + 6]) { vPrev = v2; break } prev = prev.getPrevious() } } } if (res = handleCurve(v)) return res; if (i + 1 === l || curves[i + 1]._path !== path) { if (vClose && (res = handleCurve(vClose))) return res; if (onPath && !pathWindingL && !pathWindingR) { pathWindingL = pathWindingR = path.isClockwise(closed) ^ dir ? 1 : -1 } windingL += pathWindingL; windingR += pathWindingR; pathWindingL = pathWindingR = 0; if (onPath) { onAnyPath = true; onPath = false } vClose = null } } windingL = abs(windingL); windingR = abs(windingR); return { winding: max(windingL, windingR), windingL: windingL, windingR: windingR, quality: quality, onPath: onAnyPath } } function propagateWinding(segment, path1, path2, curves, operator) { var chain = [], start = segment, totalLength = 0, winding; do { var curve = segment.getCurve(), length = curve.getLength(); chain.push({ segment: segment, curve: curve, length: length }); totalLength += length; segment = segment.getNext() } while (segment && !segment._intersection && segment !== start); var offsets = [.5, .25, .75], winding = { winding: 0, quality: -1 }, tMin = 1e-8, tMax = 1 - tMin; for (var i = 0; i < offsets.length && winding.quality < .5; i++) { var length = totalLength * offsets[i]; for (var j = 0, l = chain.length; j < l; j++) { var entry = chain[j], curveLength = entry.length; if (length <= curveLength) { var curve = entry.curve, path = curve._path, parent = path._parent, operand = parent instanceof CompoundPath ? parent : path, t = Numerical.clamp(curve.getTimeAt(length), tMin, tMax), pt = curve.getPointAtTime(t), dir = abs(curve.getTangentAtTime(t).y) < Math.SQRT1_2; var wind = null; if (operator.subtract && path2) { var pathWinding = operand === path1 ? path2._getWinding(pt, dir, true) : path1._getWinding(pt, dir, true); if (operand === path1 && pathWinding.winding || operand === path2 && !pathWinding.winding) { if (pathWinding.quality < 1) { continue } else { wind = { winding: 0, quality: 1 } } } } wind = wind || getWinding(pt, curves, dir, true); if (wind.quality > winding.quality) winding = wind; break } length -= curveLength } } for (var j = chain.length - 1; j >= 0; j--) { chain[j].segment._winding = winding } } function tracePaths(segments, operator) { var paths = [], starts; function isValid(seg) { var winding; return !!(seg && !seg._visited && (!operator || operator[(winding = seg._winding || {}).winding] && !(operator.unite && winding.winding === 2 && winding.windingL && winding.windingR))) } function isStart(seg) { if (seg) { for (var i = 0, l = starts.length; i < l; i++) { if (seg === starts[i]) return true } } return false } function visitPath(path) { var segments = path._segments; for (var i = 0, l = segments.length; i < l; i++) { segments[i]._visited = true } } function getCrossingSegments(segment, collectStarts) { var inter = segment._intersection, start = inter, crossings = []; if (collectStarts) starts = [segment]; function collect(inter, end) { while (inter && inter !== end) { var other = inter._segment, path = other && other._path; if (path) { var next = other.getNext() || path.getFirstSegment(), nextInter = next._intersection; if (other !== segment && (isStart(other) || isStart(next) || next && (isValid(other) && (isValid(next) || nextInter && isValid(nextInter._segment))))) { crossings.push(other) } if (collectStarts) starts.push(other) } inter = inter._next } } if (inter) { collect(inter); while (inter && inter._prev) inter = inter._prev; collect(inter, start) } return crossings } segments.sort(function(seg1, seg2) { var inter1 = seg1._intersection, inter2 = seg2._intersection, over1 = !!(inter1 && inter1._overlap), over2 = !!(inter2 && inter2._overlap), path1 = seg1._path, path2 = seg2._path; return over1 ^ over2 ? over1 ? 1 : -1 : !inter1 ^ !inter2 ? inter1 ? 1 : -1 : path1 !== path2 ? path1._id - path2._id : seg1._index - seg2._index }); for (var i = 0, l = segments.length; i < l; i++) { var seg = segments[i], valid = isValid(seg), path = null, finished = false, closed = true, branches = [], branch, visited, handleIn; if (valid && seg._path._overlapsOnly) { var path1 = seg._path, path2 = seg._intersection._segment._path; if (path1.compare(path2)) { if (path1.getArea()) paths.push(path1.clone(false)); visitPath(path1); visitPath(path2); valid = false } } while (valid) { var first = !path, crossings = getCrossingSegments(seg, first), other = crossings.shift(), finished = !first && (isStart(seg) || isStart(other)), cross = !finished && other; if (first) { path = new Path(Item.NO_INSERT); branch = null } if (finished) { if (seg.isFirst() || seg.isLast()) closed = seg._path._closed; seg._visited = true; break } if (cross && branch) { branches.push(branch); branch = null } if (!branch) { if (cross) crossings.push(seg); branch = { start: path._segments.length, crossings: crossings, visited: visited = [], handleIn: handleIn } } if (cross) seg = other; if (!isValid(seg)) { path.removeSegments(branch.start); for (var j = 0, k = visited.length; j < k; j++) { visited[j]._visited = false } visited.length = 0; do { seg = branch && branch.crossings.shift(); if (!seg || !seg._path) { seg = null; branch = branches.pop(); if (branch) { visited = branch.visited; handleIn = branch.handleIn } } } while (branch && !isValid(seg)); if (!seg) break } var next = seg.getNext(); path.add(new Segment(seg._point, handleIn, next && seg._handleOut)); seg._visited = true; visited.push(seg); seg = next || seg._path.getFirstSegment(); handleIn = next && next._handleIn } if (finished) { if (closed) { path.getFirstSegment().setHandleIn(handleIn); path.setClosed(closed) } if (path.getArea() !== 0) { paths.push(path) } } } return paths } return { _getWinding: function(point, dir, closed) { return getWinding(point, this.getCurves(), dir, closed) }, unite: function(path, options) { return traceBoolean(this, path, "unite", options) }, intersect: function(path, options) { return traceBoolean(this, path, "intersect", options) }, subtract: function(path, options) { return traceBoolean(this, path, "subtract", options) }, exclude: function(path, options) { return traceBoolean(this, path, "exclude", options) }, divide: function(path, options) { return options && (options.trace == false || options.stroke) ? splitBoolean(this, path, "divide") : createResult([this.subtract(path, options), this.intersect(path, options)], true, this, path, options) }, resolveCrossings: function() { var children = this._children, paths = children || [this]; function hasOverlap(seg, path) { var inter = seg && seg._intersection; return inter && inter._overlap && inter._path === path } var hasOverlaps = false, hasCrossings = false, intersections = this.getIntersections(null, function(inter) { return inter.hasOverlap() && (hasOverlaps = true) || inter.isCrossing() && (hasCrossings = true) }), clearCurves = hasOverlaps && hasCrossings && []; intersections = CurveLocation.expand(intersections); if (hasOverlaps) { var overlaps = divideLocations(intersections, function(inter) { return inter.hasOverlap() }, clearCurves); for (var i = overlaps.length - 1; i >= 0; i--) { var overlap = overlaps[i], path = overlap._path, seg = overlap._segment, prev = seg.getPrevious(), next = seg.getNext(); if (hasOverlap(prev, path) && hasOverlap(next, path)) { seg.remove(); prev._handleOut._set(0, 0); next._handleIn._set(0, 0); if (prev !== seg && !prev.getCurve().hasLength()) { next._handleIn.set(prev._handleIn); prev.remove() } } } } if (hasCrossings) { divideLocations(intersections, hasOverlaps && function(inter) { var curve1 = inter.getCurve(), seg1 = inter.getSegment(), other = inter._intersection, curve2 = other._curve, seg2 = other._segment; if (curve1 && curve2 && curve1._path && curve2._path) return true; if (seg1) seg1._intersection = null; if (seg2) seg2._intersection = null }, clearCurves); if (clearCurves) clearCurveHandles(clearCurves); paths = tracePaths(Base.each(paths, function(path) { Base.push(this, path._segments) }, [])) } var length = paths.length, item; if (length > 1 && children) { if (paths !== children) this.setChildren(paths); item = this } else if (length === 1 && !children) { if (paths[0] !== this) this.setSegments(paths[0].removeSegments()); item = this } if (!item) { item = new CompoundPath(Item.NO_INSERT); item.addChildren(paths); item = item.reduce(); item.copyAttributes(this); this.replaceWith(item) } return item }, reorient: function(nonZero, clockwise) { var children = this._children; if (children && children.length) { this.setChildren(reorientPaths(this.removeChildren(), function(w) { return !!(nonZero ? w : w & 1) }, clockwise)) } else if (clockwise !== undefined) { this.setClockwise(clockwise) } return this }, getInteriorPoint: function() { var bounds = this.getBounds(), point = bounds.getCenter(true); if (!this.contains(point)) { var curves = this.getCurves(), y = point.y, intercepts = [], roots = []; for (var i = 0, l = curves.length; i < l; i++) { var v = curves[i].getValues(), o0 = v[1], o1 = v[3], o2 = v[5], o3 = v[7]; if (y >= min(o0, o1, o2, o3) && y <= max(o0, o1, o2, o3)) { var monoCurves = Curve.getMonoCurves(v); for (var j = 0, m = monoCurves.length; j < m; j++) { var mv = monoCurves[j], mo0 = mv[1], mo3 = mv[7]; if (mo0 !== mo3 && (y >= mo0 && y <= mo3 || y >= mo3 && y <= mo0)) { var x = y === mo0 ? mv[0] : y === mo3 ? mv[6] : Curve.solveCubic(mv, 1, y, roots, 0, 1) === 1 ? Curve.getPoint(mv, roots[0]).x : (mv[0] + mv[6]) / 2; intercepts.push(x) } } } } if (intercepts.length > 1) { intercepts.sort(function(a, b) { return a - b }); point.x = (intercepts[0] + intercepts[1]) / 2 } } return point } } }); var PathFlattener = Base.extend({ _class: "PathFlattener", initialize: function(path, flatness, maxRecursion, ignoreStraight, matrix) { var curves = [], parts = [], length = 0, minSpan = 1 / (maxRecursion || 32), segments = path._segments, segment1 = segments[0], segment2; function addCurve(segment1, segment2) { var curve = Curve.getValues(segment1, segment2, matrix); curves.push(curve); computeParts(curve, segment1._index, 0, 1) } function computeParts(curve, index, t1, t2) { if (t2 - t1 > minSpan && !(ignoreStraight && Curve.isStraight(curve)) && !Curve.isFlatEnough(curve, flatness || .25)) { var halves = Curve.subdivide(curve, .5), tMid = (t1 + t2) / 2; computeParts(halves[0], index, t1, tMid); computeParts(halves[1], index, tMid, t2) } else { var dx = curve[6] - curve[0], dy = curve[7] - curve[1], dist = Math.sqrt(dx * dx + dy * dy); if (dist > 0) { length += dist; parts.push({ offset: length, curve: curve, index: index, time: t2 }) } } } for (var i = 1, l = segments.length; i < l; i++) { segment2 = segments[i]; addCurve(segment1, segment2); segment1 = segment2 } if (path._closed) addCurve(segment2 || segment1, segments[0]); this.curves = curves; this.parts = parts; this.length = length; this.index = 0 }, _get: function(offset) { var parts = this.parts, length = parts.length, start, i, j = this.index; for (;;) { i = j; if (!j || parts[--j].offset < offset) break } for (; i < length; i++) { var part = parts[i]; if (part.offset >= offset) { this.index = i; var prev = parts[i - 1], prevTime = prev && prev.index === part.index ? prev.time : 0, prevOffset = prev ? prev.offset : 0; return { index: part.index, time: prevTime + (part.time - prevTime) * (offset - prevOffset) / (part.offset - prevOffset) } } } return { index: parts[length - 1].index, time: 1 } }, drawPart: function(ctx, from, to) { var start = this._get(from), end = this._get(to); for (var i = start.index, l = end.index; i <= l; i++) { var curve = Curve.getPart(this.curves[i], i === start.index ? start.time : 0, i === end.index ? end.time : 1); if (i === start.index) ctx.moveTo(curve[0], curve[1]); ctx.bezierCurveTo.apply(ctx, curve.slice(2)) } } }, Base.each(Curve._evaluateMethods, function(name) { this[name + "At"] = function(offset) { var param = this._get(offset); return Curve[name](this.curves[param.index], param.time) } }, {})); var PathFitter = Base.extend({ initialize: function(path) { var points = this.points = [], segments = path._segments, closed = path._closed; for (var i = 0, prev, l = segments.length; i < l; i++) { var point = segments[i].point; if (!prev || !prev.equals(point)) { points.push(prev = point.clone()) } } if (closed) { points.unshift(points[points.length - 1]); points.push(points[1]) } this.closed = closed }, fit: function(error) { var points = this.points, length = points.length, segments = null; if (length > 0) { segments = [new Segment(points[0])]; if (length > 1) { this.fitCubic(segments, error, 0, length - 1, points[1].subtract(points[0]), points[length - 2].subtract(points[length - 1])); if (this.closed) { segments.shift(); segments.pop() } } } return segments }, fitCubic: function(segments, error, first, last, tan1, tan2) { var points = this.points; if (last - first === 1) { var pt1 = points[first], pt2 = points[last], dist = pt1.getDistance(pt2) / 3; this.addCurve(segments, [pt1, pt1.add(tan1.normalize(dist)), pt2.add(tan2.normalize(dist)), pt2]); return } var uPrime = this.chordLengthParameterize(first, last), maxError = Math.max(error, error * error), split, parametersInOrder = true; for (var i = 0; i <= 4; i++) { var curve = this.generateBezier(first, last, uPrime, tan1, tan2); var max = this.findMaxError(first, last, curve, uPrime); if (max.error < error && parametersInOrder) { this.addCurve(segments, curve); return } split = max.index; if (max.error >= maxError) break; parametersInOrder = this.reparameterize(first, last, uPrime, curve); maxError = max.error } var tanCenter = points[split - 1].subtract(points[split + 1]); this.fitCubic(segments, error, first, split, tan1, tanCenter); this.fitCubic(segments, error, split, last, tanCenter.negate(), tan2) }, addCurve: function(segments, curve) { var prev = segments[segments.length - 1]; prev.setHandleOut(curve[1].subtract(curve[0])); segments.push(new Segment(curve[3], curve[2].subtract(curve[3]))) }, generateBezier: function(first, last, uPrime, tan1, tan2) { var epsilon = 1e-12, abs = Math.abs, points = this.points, pt1 = points[first], pt2 = points[last], C = [ [0, 0], [0, 0] ], X = [0, 0]; for (var i = 0, l = last - first + 1; i < l; i++) { var u = uPrime[i], t = 1 - u, b = 3 * u * t, b0 = t * t * t, b1 = b * t, b2 = b * u, b3 = u * u * u, a1 = tan1.normalize(b1), a2 = tan2.normalize(b2), tmp = points[first + i].subtract(pt1.multiply(b0 + b1)).subtract(pt2.multiply(b2 + b3)); C[0][0] += a1.dot(a1); C[0][1] += a1.dot(a2); C[1][0] = C[0][1]; C[1][1] += a2.dot(a2); X[0] += a1.dot(tmp); X[1] += a2.dot(tmp) } var detC0C1 = C[0][0] * C[1][1] - C[1][0] * C[0][1], alpha1, alpha2; if (abs(detC0C1) > epsilon) { var detC0X = C[0][0] * X[1] - C[1][0] * X[0], detXC1 = X[0] * C[1][1] - X[1] * C[0][1]; alpha1 = detXC1 / detC0C1; alpha2 = detC0X / detC0C1 } else { var c0 = C[0][0] + C[0][1], c1 = C[1][0] + C[1][1]; alpha1 = alpha2 = abs(c0) > epsilon ? X[0] / c0 : abs(c1) > epsilon ? X[1] / c1 : 0 } var segLength = pt2.getDistance(pt1), eps = epsilon * segLength, handle1, handle2; if (alpha1 < eps || alpha2 < eps) { alpha1 = alpha2 = segLength / 3 } else { var line = pt2.subtract(pt1); handle1 = tan1.normalize(alpha1); handle2 = tan2.normalize(alpha2); if (handle1.dot(line) - handle2.dot(line) > segLength * segLength) { alpha1 = alpha2 = segLength / 3; handle1 = handle2 = null } } return [pt1, pt1.add(handle1 || tan1.normalize(alpha1)), pt2.add(handle2 || tan2.normalize(alpha2)), pt2] }, reparameterize: function(first, last, u, curve) { for (var i = first; i <= last; i++) { u[i - first] = this.findRoot(curve, this.points[i], u[i - first]) } for (var i = 1, l = u.length; i < l; i++) { if (u[i] <= u[i - 1]) return false } return true }, findRoot: function(curve, point, u) { var curve1 = [], curve2 = []; for (var i = 0; i <= 2; i++) { curve1[i] = curve[i + 1].subtract(curve[i]).multiply(3) } for (var i = 0; i <= 1; i++) { curve2[i] = curve1[i + 1].subtract(curve1[i]).multiply(2) } var pt = this.evaluate(3, curve, u), pt1 = this.evaluate(2, curve1, u), pt2 = this.evaluate(1, curve2, u), diff = pt.subtract(point), df = pt1.dot(pt1) + diff.dot(pt2); return Numerical.isZero(df) ? u : u - diff.dot(pt1) / df }, evaluate: function(degree, curve, t) { var tmp = curve.slice(); for (var i = 1; i <= degree; i++) { for (var j = 0; j <= degree - i; j++) { tmp[j] = tmp[j].multiply(1 - t).add(tmp[j + 1].multiply(t)) } } return tmp[0] }, chordLengthParameterize: function(first, last) { var u = [0]; for (var i = first + 1; i <= last; i++) { u[i - first] = u[i - first - 1] + this.points[i].getDistance(this.points[i - 1]) } for (var i = 1, m = last - first; i <= m; i++) { u[i] /= u[m] } return u }, findMaxError: function(first, last, curve, u) { var index = Math.floor((last - first + 1) / 2), maxDist = 0; for (var i = first + 1; i < last; i++) { var P = this.evaluate(3, curve, u[i - first]); var v = P.subtract(this.points[i]); var dist = v.x * v.x + v.y * v.y; if (dist >= maxDist) { maxDist = dist; index = i } } return { error: maxDist, index: index } } }); var TextItem = Item.extend({ _class: "TextItem", _applyMatrix: false, _canApplyMatrix: false, _serializeFields: { content: null }, _boundsOptions: { stroke: false, handle: false }, initialize: function TextItem(arg) { this._content = ""; this._lines = []; var hasProps = arg && Base.isPlainObject(arg) && arg.x === undefined && arg.y === undefined; this._initialize(hasProps && arg, !hasProps && Point.read(arguments)) }, _equals: function(item) { return this._content === item._content }, copyContent: function(source) { this.setContent(source._content) }, getContent: function() { return this._content }, setContent: function(content) { this._content = "" + content; this._lines = this._content.split(/\r\n|\n|\r/gm); this._changed(521) }, isEmpty: function() { return !this._content }, getCharacterStyle: "#getStyle", setCharacterStyle: "#setStyle", getParagraphStyle: "#getStyle", setParagraphStyle: "#setStyle" }); var PointText = TextItem.extend({ _class: "PointText", initialize: function PointText() { TextItem.apply(this, arguments) }, getPoint: function() { var point = this._matrix.getTranslation(); return new LinkedPoint(point.x, point.y, this, "setPoint") }, setPoint: function() { var point = Point.read(arguments); this.translate(point.subtract(this._matrix.getTranslation())) }, _draw: function(ctx, param, viewMatrix) { if (!this._content) return; this._setStyles(ctx, param, viewMatrix); var lines = this._lines, style = this._style, hasFill = style.hasFill(), hasStroke = style.hasStroke(), leading = style.getLeading(), shadowColor = ctx.shadowColor; ctx.font = style.getFontStyle(); ctx.textAlign = style.getJustification(); for (var i = 0, l = lines.length; i < l; i++) { ctx.shadowColor = shadowColor; var line = lines[i]; if (hasFill) { ctx.fillText(line, 0, 0); ctx.shadowColor = "rgba(0,0,0,0)" } if (hasStroke) ctx.strokeText(line, 0, 0); ctx.translate(0, leading) } }, _getBounds: function(matrix, options) { var style = this._style, lines = this._lines, numLines = lines.length, justification = style.getJustification(), leading = style.getLeading(), width = this.getView().getTextWidth(style.getFontStyle(), lines), x = 0; if (justification !== "left") x -= width / (justification === "center" ? 2 : 1); var rect = new Rectangle(x, numLines ? -.75 * leading : 0, width, numLines * leading); return matrix ? matrix._transformBounds(rect, rect) : rect } }); var Color = Base.extend(new function() { var types = { gray: ["gray"], rgb: ["red", "green", "blue"], hsb: ["hue", "saturation", "brightness"], hsl: ["hue", "saturation", "lightness"], gradient: ["gradient", "origin", "destination", "highlight"] }; var componentParsers = {}, namedColors = { transparent: [0, 0, 0, 0] }, colorCtx; function fromCSS(string) { var match = string.match(/^#([\da-f]{2})([\da-f]{2})([\da-f]{2})([\da-f]{2})?$/i) || string.match(/^#([\da-f])([\da-f])([\da-f])([\da-f])?$/i), type = "rgb", components; if (match) { var amount = match[4] ? 4 : 3; components = new Array(amount); for (var i = 0; i < amount; i++) { var value = match[i + 1]; components[i] = parseInt(value.length == 1 ? value + value : value, 16) / 255 } } else if (match = string.match(/^(rgb|hsl)a?\((.*)\)$/)) { type = match[1]; components = match[2].split(/[,\s]+/g); var isHSL = type === "hsl"; for (var i = 0, l = Math.min(components.length, 4); i < l; i++) { var component = components[i]; var value = parseFloat(component); if (isHSL) { if (i === 0) { var unit = component.match(/([a-z]*)$/)[1]; value *= { turn: 360, rad: 180 / Math.PI, grad: .9 }[unit] || 1 } else if (i < 3) { value /= 100 } } else if (i < 3) { value /= 255 } components[i] = value } } else { var color = namedColors[string]; if (!color) { if (window) { if (!colorCtx) { colorCtx = CanvasProvider.getContext(1, 1); colorCtx.globalCompositeOperation = "copy" } colorCtx.fillStyle = "rgba(0,0,0,0)"; colorCtx.fillStyle = string; colorCtx.fillRect(0, 0, 1, 1); var data = colorCtx.getImageData(0, 0, 1, 1).data; color = namedColors[string] = [data[0] / 255, data[1] / 255, data[2] / 255] } else { color = [0, 0, 0] } } components = color.slice() } return [type, components] } var hsbIndices = [ [0, 3, 1], [2, 0, 1], [1, 0, 3], [1, 2, 0], [3, 1, 0], [0, 1, 2] ]; var converters = { "rgb-hsb": function(r, g, b) { var max = Math.max(r, g, b), min = Math.min(r, g, b), delta = max - min, h = delta === 0 ? 0 : (max == r ? (g - b) / delta + (g < b ? 6 : 0) : max == g ? (b - r) / delta + 2 : (r - g) / delta + 4) * 60; return [h, max === 0 ? 0 : delta / max, max] }, "hsb-rgb": function(h, s, b) { h = (h / 60 % 6 + 6) % 6; var i = Math.floor(h), f = h - i, i = hsbIndices[i], v = [b, b * (1 - s), b * (1 - s * f), b * (1 - s * (1 - f))]; return [v[i[0]], v[i[1]], v[i[2]]] }, "rgb-hsl": function(r, g, b) { var max = Math.max(r, g, b), min = Math.min(r, g, b), delta = max - min, achromatic = delta === 0, h = achromatic ? 0 : (max == r ? (g - b) / delta + (g < b ? 6 : 0) : max == g ? (b - r) / delta + 2 : (r - g) / delta + 4) * 60, l = (max + min) / 2, s = achromatic ? 0 : l < .5 ? delta / (max + min) : delta / (2 - max - min); return [h, s, l] }, "hsl-rgb": function(h, s, l) { h = (h / 360 % 1 + 1) % 1; if (s === 0) return [l, l, l]; var t3s = [h + 1 / 3, h, h - 1 / 3], t2 = l < .5 ? l * (1 + s) : l + s - l * s, t1 = 2 * l - t2, c = []; for (var i = 0; i < 3; i++) { var t3 = t3s[i]; if (t3 < 0) t3 += 1; if (t3 > 1) t3 -= 1; c[i] = 6 * t3 < 1 ? t1 + (t2 - t1) * 6 * t3 : 2 * t3 < 1 ? t2 : 3 * t3 < 2 ? t1 + (t2 - t1) * (2 / 3 - t3) * 6 : t1 } return c }, "rgb-gray": function(r, g, b) { return [r * .2989 + g * .587 + b * .114] }, "gray-rgb": function(g) { return [g, g, g] }, "gray-hsb": function(g) { return [0, 0, g] }, "gray-hsl": function(g) { return [0, 0, g] }, "gradient-rgb": function() { return [] }, "rgb-gradient": function() { return [] } }; return Base.each(types, function(properties, type) { componentParsers[type] = []; Base.each(properties, function(name, index) { var part = Base.capitalize(name), hasOverlap = /^(hue|saturation)$/.test(name), parser = componentParsers[type][index] = type === "gradient" ? name === "gradient" ? function(value) { var current = this._components[0]; value = Gradient.read(Array.isArray(value) ? value : arguments, 0, { readNull: true }); if (current !== value) { if (current) current._removeOwner(this); if (value) value._addOwner(this) } return value } : function() { return Point.read(arguments, 0, { readNull: name === "highlight", clone: true }) } : function(value) { return value == null || isNaN(value) ? 0 : +value }; this["get" + part] = function() { return this._type === type || hasOverlap && /^hs[bl]$/.test(this._type) ? this._components[index] : this._convert(type)[index] }; this["set" + part] = function(value) { if (this._type !== type && !(hasOverlap && /^hs[bl]$/.test(this._type))) { this._components = this._convert(type); this._properties = types[type]; this._type = type } this._components[index] = parser.call(this, value); this._changed() } }, this) }, { _class: "Color", _readIndex: true, initialize: function Color(arg) { var args = arguments, reading = this.__read, read = 0, type, components, alpha, values; if (Array.isArray(arg)) { args = arg; arg = args[0] } var argType = arg != null && typeof arg; if (argType === "string" && arg in types) { type = arg; arg = args[1]; if (Array.isArray(arg)) { components = arg; alpha = args[2] } else { if (reading) read = 1; args = Base.slice(args, 1); argType = typeof arg } } if (!components) { values = argType === "number" ? args : argType === "object" && arg.length != null ? arg : null; if (values) { if (!type) type = values.length >= 3 ? "rgb" : "gray"; var length = types[type].length; alpha = values[length]; if (reading) { read += values === arguments ? length + (alpha != null ? 1 : 0) : 1 } if (values.length > length) values = Base.slice(values, 0, length) } else if (argType === "string") { var converted = fromCSS(arg); type = converted[0]; components = converted[1]; if (components.length === 4) { alpha = components[3]; components.length-- } } else if (argType === "object") { if (arg.constructor === Color) { type = arg._type; components = arg._components.slice(); alpha = arg._alpha; if (type === "gradient") { for (var i = 1, l = components.length; i < l; i++) { var point = components[i]; if (point) components[i] = point.clone() } } } else if (arg.constructor === Gradient) { type = "gradient"; values = args } else { type = "hue" in arg ? "lightness" in arg ? "hsl" : "hsb" : "gradient" in arg || "stops" in arg || "radial" in arg ? "gradient" : "gray" in arg ? "gray" : "rgb"; var properties = types[type], parsers = componentParsers[type]; this._components = components = []; for (var i = 0, l = properties.length; i < l; i++) { var value = arg[properties[i]]; if (value == null && !i && type === "gradient" && "stops" in arg) { value = { stops: arg.stops, radial: arg.radial } } value = parsers[i].call(this, value); if (value != null) components[i] = value } alpha = arg.alpha } } if (reading && type) read = 1 } this._type = type || "rgb"; if (!components) { this._components = components = []; var parsers = componentParsers[this._type]; for (var i = 0, l = parsers.length; i < l; i++) { var value = parsers[i].call(this, values && values[i]); if (value != null) components[i] = value } } this._components = components; this._properties = types[this._type]; this._alpha = alpha; if (reading) this.__read = read; return this }, set: "#initialize", _serialize: function(options, dictionary) { var components = this.getComponents(); return Base.serialize(/^(gray|rgb)$/.test(this._type) ? components : [this._type].concat(components), options, true, dictionary) }, _changed: function() { this._canvasStyle = null; if (this._owner) this._owner._changed(129) }, _convert: function(type) { var converter; return this._type === type ? this._components.slice() : (converter = converters[this._type + "-" + type]) ? converter.apply(this, this._components) : converters["rgb-" + type].apply(this, converters[this._type + "-rgb"].apply(this, this._components)) }, convert: function(type) { return new Color(type, this._convert(type), this._alpha) }, getType: function() { return this._type }, setType: function(type) { this._components = this._convert(type); this._properties = types[type]; this._type = type }, getComponents: function() { var components = this._components.slice(); if (this._alpha != null) components.push(this._alpha); return components }, getAlpha: function() { return this._alpha != null ? this._alpha : 1 }, setAlpha: function(alpha) { this._alpha = alpha == null ? null : Math.min(Math.max(alpha, 0), 1); this._changed() }, hasAlpha: function() { return this._alpha != null }, equals: function(color) { var col = Base.isPlainValue(color, true) ? Color.read(arguments) : color; return col === this || col && this._class === col._class && this._type === col._type && this.getAlpha() === col.getAlpha() && Base.equals(this._components, col._components) || false }, toString: function() { var properties = this._properties, parts = [], isGradient = this._type === "gradient", f = Formatter.instance; for (var i = 0, l = properties.length; i < l; i++) { var value = this._components[i]; if (value != null) parts.push(properties[i] + ": " + (isGradient ? value : f.number(value))) } if (this._alpha != null) parts.push("alpha: " + f.number(this._alpha)); return "{ " + parts.join(", ") + " }" }, toCSS: function(hex) { var components = this._convert("rgb"), alpha = hex || this._alpha == null ? 1 : this._alpha; function convert(val) { return Math.round((val < 0 ? 0 : val > 1 ? 1 : val) * 255) } components = [convert(components[0]), convert(components[1]), convert(components[2])]; if (alpha < 1) components.push(alpha < 0 ? 0 : alpha); return hex ? "#" + ((1 << 24) + (components[0] << 16) + (components[1] << 8) + components[2]).toString(16).slice(1) : (components.length == 4 ? "rgba(" : "rgb(") + components.join(",") + ")" }, toCanvasStyle: function(ctx, matrix) { if (this._canvasStyle) return this._canvasStyle; if (this._type !== "gradient") return this._canvasStyle = this.toCSS(); var components = this._components, gradient = components[0], stops = gradient._stops, origin = components[1], destination = components[2], highlight = components[3], inverse = matrix && matrix.inverted(), canvasGradient; if (inverse) { origin = inverse._transformPoint(origin); destination = inverse._transformPoint(destination); if (highlight) highlight = inverse._transformPoint(highlight) } if (gradient._radial) { var radius = destination.getDistance(origin); if (highlight) { var vector = highlight.subtract(origin); if (vector.getLength() > radius) highlight = origin.add(vector.normalize(radius - .1)) } var start = highlight || origin; canvasGradient = ctx.createRadialGradient(start.x, start.y, 0, origin.x, origin.y, radius) } else { canvasGradient = ctx.createLinearGradient(origin.x, origin.y, destination.x, destination.y) } for (var i = 0, l = stops.length; i < l; i++) { var stop = stops[i], offset = stop._offset; canvasGradient.addColorStop(offset == null ? i / (l - 1) : offset, stop._color.toCanvasStyle()) } return this._canvasStyle = canvasGradient }, transform: function(matrix) { if (this._type === "gradient") { var components = this._components; for (var i = 1, l = components.length; i < l; i++) { var point = components[i]; matrix._transformPoint(point, point, true) } this._changed() } }, statics: { _types: types, random: function() { var random = Math.random; return new Color(random(), random(), random()) } } }) }, new function() { var operators = { add: function(a, b) { return a + b }, subtract: function(a, b) { return a - b }, multiply: function(a, b) { return a * b }, divide: function(a, b) { return a / b } }; return Base.each(operators, function(operator, name) { this[name] = function(color) { color = Color.read(arguments); var type = this._type, components1 = this._components, components2 = color._convert(type); for (var i = 0, l = components1.length; i < l; i++) components2[i] = operator(components1[i], components2[i]); return new Color(type, components2, this._alpha != null ? operator(this._alpha, color.getAlpha()) : null) } }, {}) }); var Gradient = Base.extend({ _class: "Gradient", initialize: function Gradient(stops, radial) { this._id = UID.get(); if (stops && Base.isPlainObject(stops)) { this.set(stops); stops = radial = null } if (this._stops == null) { this.setStops(stops || ["white", "black"]) } if (this._radial == null) { this.setRadial(typeof radial === "string" && radial === "radial" || radial || false) } }, _serialize: function(options, dictionary) { return dictionary.add(this, function() { return Base.serialize([this._stops, this._radial], options, true, dictionary) }) }, _changed: function() { for (var i = 0, l = this._owners && this._owners.length; i < l; i++) { this._owners[i]._changed() } }, _addOwner: function(color) { if (!this._owners) this._owners = []; this._owners.push(color) }, _removeOwner: function(color) { var index = this._owners ? this._owners.indexOf(color) : -1; if (index != -1) { this._owners.splice(index, 1); if (!this._owners.length) this._owners = undefined } }, clone: function() { var stops = []; for (var i = 0, l = this._stops.length; i < l; i++) { stops[i] = this._stops[i].clone() } return new Gradient(stops, this._radial) }, getStops: function() { return this._stops }, setStops: function(stops) { if (stops.length < 2) { throw new Error("Gradient stop list needs to contain at least two stops.") } var _stops = this._stops; if (_stops) { for (var i = 0, l = _stops.length; i < l; i++) _stops[i]._owner = undefined } _stops = this._stops = GradientStop.readList(stops, 0, { clone: true }); for (var i = 0, l = _stops.length; i < l; i++) _stops[i]._owner = this; this._changed() }, getRadial: function() { return this._radial }, setRadial: function(radial) { this._radial = radial; this._changed() }, equals: function(gradient) { if (gradient === this) return true; if (gradient && this._class === gradient._class) { var stops1 = this._stops, stops2 = gradient._stops, length = stops1.length; if (length === stops2.length) { for (var i = 0; i < length; i++) { if (!stops1[i].equals(stops2[i])) return false } return true } } return false } }); var GradientStop = Base.extend({ _class: "GradientStop", initialize: function GradientStop(arg0, arg1) { var color = arg0, offset = arg1; if (typeof arg0 === "object" && arg1 === undefined) { if (Array.isArray(arg0) && typeof arg0[0] !== "number") { color = arg0[0]; offset = arg0[1] } else if ("color" in arg0 || "offset" in arg0 || "rampPoint" in arg0) { color = arg0.color; offset = arg0.offset || arg0.rampPoint || 0 } } this.setColor(color); this.setOffset(offset) }, clone: function() { return new GradientStop(this._color.clone(), this._offset) }, _serialize: function(options, dictionary) { var color = this._color, offset = this._offset; return Base.serialize(offset == null ? [color] : [color, offset], options, true, dictionary) }, _changed: function() { if (this._owner) this._owner._changed(129) }, getOffset: function() { return this._offset }, setOffset: function(offset) { this._offset = offset; this._changed() }, getRampPoint: "#getOffset", setRampPoint: "#setOffset", getColor: function() { return this._color }, setColor: function() { var color = Color.read(arguments, 0, { clone: true }); if (color) color._owner = this; this._color = color; this._changed() }, equals: function(stop) { return stop === this || stop && this._class === stop._class && this._color.equals(stop._color) && this._offset == stop._offset || false } }); var Style = Base.extend(new function() { var itemDefaults = { fillColor: null, fillRule: "nonzero", strokeColor: null, strokeWidth: 1, strokeCap: "butt", strokeJoin: "miter", strokeScaling: true, miterLimit: 10, dashOffset: 0, dashArray: [], shadowColor: null, shadowBlur: 0, shadowOffset: new Point, selectedColor: null }, groupDefaults = Base.set({}, itemDefaults, { fontFamily: "sans-serif", fontWeight: "normal", fontSize: 12, leading: null, justification: "left" }), textDefaults = Base.set({}, groupDefaults, { fillColor: new Color }), flags = { strokeWidth: 193, strokeCap: 193, strokeJoin: 193, strokeScaling: 201, miterLimit: 193, fontFamily: 9, fontWeight: 9, fontSize: 9, font: 9, leading: 9, justification: 9 }, item = { beans: true }, fields = { _class: "Style", beans: true, initialize: function Style(style, _owner, _project) { this._values = {}; this._owner = _owner; this._project = _owner && _owner._project || _project || paper.project; this._defaults = !_owner || _owner instanceof Group ? groupDefaults : _owner instanceof TextItem ? textDefaults : itemDefaults; if (style) this.set(style) } }; Base.each(groupDefaults, function(value, key) { var isColor = /Color$/.test(key), isPoint = key === "shadowOffset", part = Base.capitalize(key), flag = flags[key], set = "set" + part, get = "get" + part; fields[set] = function(value) { var owner = this._owner, children = owner && owner._children; if (children && children.length > 0 && !(owner instanceof CompoundPath)) { for (var i = 0, l = children.length; i < l; i++) children[i]._style[set](value) } else if (key in this._defaults) { var old = this._values[key]; if (old !== value) { if (isColor) { if (old && old._owner !== undefined) { old._owner = undefined; old._canvasStyle = null } if (value && value.constructor === Color) { if (value._owner) value = value.clone(); value._owner = owner } } this._values[key] = value; if (owner) owner._changed(flag || 129) } } }; fields[get] = function(_dontMerge) { var owner = this._owner, children = owner && owner._children, value; if (key in this._defaults && (!children || !children.length || _dontMerge || owner instanceof CompoundPath)) { var value = this._values[key]; if (value === undefined) { value = this._defaults[key]; if (value && value.clone) value = value.clone() } else { var ctor = isColor ? Color : isPoint ? Point : null; if (ctor && !(value && value.constructor === ctor)) { this._values[key] = value = ctor.read([value], 0, { readNull: true, clone: true }); if (value && isColor) value._owner = owner } } } else if (children) { for (var i = 0, l = children.length; i < l; i++) { var childValue = children[i]._style[get](); if (!i) { value = childValue } else if (!Base.equals(value, childValue)) { return undefined } } } return value }; item[get] = function(_dontMerge) { return this._style[get](_dontMerge) }; item[set] = function(value) { this._style[set](value) } }); Base.each({ Font: "FontFamily", WindingRule: "FillRule" }, function(value, key) { var get = "get" + key, set = "set" + key; fields[get] = item[get] = "#get" + value; fields[set] = item[set] = "#set" + value }); Item.inject(item); return fields }, { set: function(style) { var isStyle = style instanceof Style, values = isStyle ? style._values : style; if (values) { for (var key in values) { if (key in this._defaults) { var value = values[key]; this[key] = value && isStyle && value.clone ? value.clone() : value } } } }, equals: function(style) { function compare(style1, style2, secondary) { var values1 = style1._values, values2 = style2._values, defaults2 = style2._defaults; for (var key in values1) { var value1 = values1[key], value2 = values2[key]; if (!(secondary && key in values2) && !Base.equals(value1, value2 === undefined ? defaults2[key] : value2)) return false } return true } return style === this || style && this._class === style._class && compare(this, style) && compare(style, this, true) || false }, _dispose: function() { var color; color = this.getFillColor(); if (color) color._canvasStyle = null; color = this.getStrokeColor(); if (color) color._canvasStyle = null; color = this.getShadowColor(); if (color) color._canvasStyle = null }, hasFill: function() { var color = this.getFillColor(); return !!color && color.alpha > 0 }, hasStroke: function() { var color = this.getStrokeColor(); return !!color && color.alpha > 0 && this.getStrokeWidth() > 0 }, hasShadow: function() { var color = this.getShadowColor(); return !!color && color.alpha > 0 && (this.getShadowBlur() > 0 || !this.getShadowOffset().isZero()) }, getView: function() { return this._project._view }, getFontStyle: function() { var fontSize = this.getFontSize(); return this.getFontWeight() + " " + fontSize + (/[a-z]/i.test(fontSize + "") ? " " : "px ") + this.getFontFamily() }, getFont: "#getFontFamily", setFont: "#setFontFamily", getLeading: function getLeading() { var leading = getLeading.base.call(this), fontSize = this.getFontSize(); if (/pt|em|%|px/.test(fontSize)) fontSize = this.getView().getPixelSize(fontSize); return leading != null ? leading : fontSize * 1.2 } }); var DomElement = new function() { function handlePrefix(el, name, set, value) { var prefixes = ["", "webkit", "moz", "Moz", "ms", "o"], suffix = name[0].toUpperCase() + name.substring(1); for (var i = 0; i < 6; i++) { var prefix = prefixes[i], key = prefix ? prefix + suffix : name; if (key in el) { if (set) { el[key] = value } else { return el[key] } break } } } return { getStyles: function(el) { var doc = el && el.nodeType !== 9 ? el.ownerDocument : el, view = doc && doc.defaultView; return view && view.getComputedStyle(el, "") }, getBounds: function(el, viewport) { var doc = el.ownerDocument, body = doc.body, html = doc.documentElement, rect; try { rect = el.getBoundingClientRect() } catch (e) { rect = { left: 0, top: 0, width: 0, height: 0 } } var x = rect.left - (html.clientLeft || body.clientLeft || 0), y = rect.top - (html.clientTop || body.clientTop || 0); if (!viewport) { var view = doc.defaultView; x += view.pageXOffset || html.scrollLeft || body.scrollLeft; y += view.pageYOffset || html.scrollTop || body.scrollTop } return new Rectangle(x, y, rect.width, rect.height) }, getViewportBounds: function(el) { var doc = el.ownerDocument, view = doc.defaultView, html = doc.documentElement; return new Rectangle(0, 0, view.innerWidth || html.clientWidth, view.innerHeight || html.clientHeight) }, getOffset: function(el, viewport) { return DomElement.getBounds(el, viewport).getPoint() }, getSize: function(el) { return DomElement.getBounds(el, true).getSize() }, isInvisible: function(el) { return DomElement.getSize(el).equals(new Size(0, 0)) }, isInView: function(el) { return !DomElement.isInvisible(el) && DomElement.getViewportBounds(el).intersects(DomElement.getBounds(el, true)) }, isInserted: function(el) { return document.body.contains(el) }, getPrefixed: function(el, name) { return el && handlePrefix(el, name) }, setPrefixed: function(el, name, value) { if (typeof name === "object") { for (var key in name) handlePrefix(el, key, true, name[key]) } else { handlePrefix(el, name, true, value) } } } }; var DomEvent = { add: function(el, events) { if (el) { for (var type in events) { var func = events[type], parts = type.split(/[\s,]+/g); for (var i = 0, l = parts.length; i < l; i++) { var name = parts[i]; var options = el === document && (name === "touchstart" || name === "touchmove") ? { passive: false } : false; el.addEventListener(name, func, options) } } } }, remove: function(el, events) { if (el) { for (var type in events) { var func = events[type], parts = type.split(/[\s,]+/g); for (var i = 0, l = parts.length; i < l; i++) el.removeEventListener(parts[i], func, false) } } }, getPoint: function(event) { var pos = event.targetTouches ? event.targetTouches.length ? event.targetTouches[0] : event.changedTouches[0] : event; return new Point(pos.pageX || pos.clientX + document.documentElement.scrollLeft, pos.pageY || pos.clientY + document.documentElement.scrollTop) }, getTarget: function(event) { return event.target || event.srcElement }, getRelatedTarget: function(event) { return event.relatedTarget || event.toElement }, getOffset: function(event, target) { return DomEvent.getPoint(event).subtract(DomElement.getOffset(target || DomEvent.getTarget(event))) } }; DomEvent.requestAnimationFrame = new function() { var nativeRequest = DomElement.getPrefixed(window, "requestAnimationFrame"), requested = false, callbacks = [], timer; function handleCallbacks() { var functions = callbacks; callbacks = []; for (var i = 0, l = functions.length; i < l; i++) functions[i](); requested = nativeRequest && callbacks.length; if (requested) nativeRequest(handleCallbacks) } return function(callback) { callbacks.push(callback); if (nativeRequest) { if (!requested) { nativeRequest(handleCallbacks); requested = true } } else if (!timer) { timer = setInterval(handleCallbacks, 1e3 / 60) } } }; var View = Base.extend(Emitter, { _class: "View", initialize: function View(project, element) { function getSize(name) { return element[name] || parseInt(element.getAttribute(name), 10) } function getCanvasSize() { var size = DomElement.getSize(element); return size.isNaN() || size.isZero() ? new Size(getSize("width"), getSize("height")) : size } var size; if (window && element) { this._id = element.getAttribute("id"); if (this._id == null) element.setAttribute("id", this._id = "view-" + View._id++); DomEvent.add(element, this._viewEvents); var none = "none"; DomElement.setPrefixed(element.style, { userDrag: none, userSelect: none, touchCallout: none, contentZooming: none, tapHighlightColor: "rgba(0,0,0,0)" }); if (PaperScope.hasAttribute(element, "resize")) { var that = this; DomEvent.add(window, this._windowEvents = { resize: function() { that.setViewSize(getCanvasSize()) } }) } size = getCanvasSize(); if (PaperScope.hasAttribute(element, "stats") && typeof Stats !== "undefined") { this._stats = new Stats; var stats = this._stats.domElement, style = stats.style, offset = DomElement.getOffset(element); style.position = "absolute"; style.left = offset.x + "px"; style.top = offset.y + "px"; document.body.appendChild(stats) } } else { size = new Size(element); element = null } this._project = project; this._scope = project._scope; this._element = element; if (!this._pixelRatio) this._pixelRatio = window && window.devicePixelRatio || 1; this._setElementSize(size.width, size.height); this._viewSize = size; View._views.push(this); View._viewsById[this._id] = this; (this._matrix = new Matrix)._owner = this; if (!View._focused) View._focused = this; this._frameItems = {}; this._frameItemCount = 0; this._itemEvents = { native: {}, virtual: {} }; this._autoUpdate = !paper.agent.node; this._needsUpdate = false }, remove: function() { if (!this._project) return false; if (View._focused === this) View._focused = null; View._views.splice(View._views.indexOf(this), 1); delete View._viewsById[this._id]; var project = this._project; if (project._view === this) project._view = null; DomEvent.remove(this._element, this._viewEvents); DomEvent.remove(window, this._windowEvents); this._element = this._project = null; this.off("frame"); this._animate = false; this._frameItems = {}; return true }, _events: Base.each(Item._itemHandlers.concat(["onResize", "onKeyDown", "onKeyUp"]), function(name) { this[name] = {} }, { onFrame: { install: function() { this.play() }, uninstall: function() { this.pause() } } }), _animate: false, _time: 0, _count: 0, getAutoUpdate: function() { return this._autoUpdate }, setAutoUpdate: function(autoUpdate) { this._autoUpdate = autoUpdate; if (autoUpdate) this.requestUpdate() }, update: function() {}, draw: function() { this.update() }, requestUpdate: function() { if (!this._requested) { var that = this; DomEvent.requestAnimationFrame(function() { that._requested = false; if (that._animate) { that.requestUpdate(); var element = that._element; if ((!DomElement.getPrefixed(document, "hidden") || PaperScope.getAttribute(element, "keepalive") === "true") && DomElement.isInView(element)) { that._handleFrame() } } if (that._autoUpdate) that.update() }); this._requested = true } }, play: function() { this._animate = true; this.requestUpdate() }, pause: function() { this._animate = false }, _handleFrame: function() { paper = this._scope; var now = Date.now() / 1e3, delta = this._last ? now - this._last : 0; this._last = now; this.emit("frame", new Base({ delta: delta, time: this._time += delta, count: this._count++ })); if (this._stats) this._stats.update() }, _animateItem: function(item, animate) { var items = this._frameItems; if (animate) { items[item._id] = { item: item, time: 0, count: 0 }; if (++this._frameItemCount === 1) this.on("frame", this._handleFrameItems) } else { delete items[item._id]; if (--this._frameItemCount === 0) { this.off("frame", this._handleFrameItems) } } }, _handleFrameItems: function(event) { for (var i in this._frameItems) { var entry = this._frameItems[i]; entry.item.emit("frame", new Base(event, { time: entry.time += event.delta, count: entry.count++ })) } }, _changed: function() { this._project._changed(4097); this._bounds = this._decomposed = undefined }, getElement: function() { return this._element }, getPixelRatio: function() { return this._pixelRatio }, getResolution: function() { return this._pixelRatio * 72 }, getViewSize: function() { var size = this._viewSize; return new LinkedSize(size.width, size.height, this, "setViewSize") }, setViewSize: function() { var size = Size.read(arguments), delta = size.subtract(this._viewSize); if (delta.isZero()) return; this._setElementSize(size.width, size.height); this._viewSize.set(size); this._changed(); this.emit("resize", { size: size, delta: delta }); if (this._autoUpdate) { this.update() } }, _setElementSize: function(width, height) { var element = this._element; if (element) { if (element.width !== width) element.width = width; if (element.height !== height) element.height = height } }, getBounds: function() { if (!this._bounds) this._bounds = this._matrix.inverted()._transformBounds(new Rectangle(new Point, this._viewSize)); return this._bounds }, getSize: function() { return this.getBounds().getSize() }, isVisible: function() { return DomElement.isInView(this._element) }, isInserted: function() { return DomElement.isInserted(this._element) }, getPixelSize: function(size) { var element = this._element, pixels; if (element) { var parent = element.parentNode, temp = document.createElement("div"); temp.style.fontSize = size; parent.appendChild(temp); pixels = parseFloat(DomElement.getStyles(temp).fontSize); parent.removeChild(temp) } else { pixels = parseFloat(pixels) } return pixels }, getTextWidth: function(font, lines) { return 0 } }, Base.each(["rotate", "scale", "shear", "skew"], function(key) { var rotate = key === "rotate"; this[key] = function() { var value = (rotate ? Base : Point).read(arguments), center = Point.read(arguments, 0, { readNull: true }); return this.transform((new Matrix)[key](value, center || this.getCenter(true))) } }, { _decompose: function() { return this._decomposed || (this._decomposed = this._matrix.decompose()) }, translate: function() { var mx = new Matrix; return this.transform(mx.translate.apply(mx, arguments)) }, getCenter: function() { return this.getBounds().getCenter() }, setCenter: function() { var center = Point.read(arguments); this.translate(this.getCenter().subtract(center)) }, getZoom: function() { var decomposed = this._decompose(), scaling = decomposed && decomposed.scaling; return scaling ? (scaling.x + scaling.y) / 2 : 0 }, setZoom: function(zoom) { this.transform((new Matrix).scale(zoom / this.getZoom(), this.getCenter())) }, getRotation: function() { var decomposed = this._decompose(); return decomposed && decomposed.rotation }, setRotation: function(rotation) { var current = this.getRotation(); if (current != null && rotation != null) { this.rotate(rotation - current) } }, getScaling: function() { var decomposed = this._decompose(), scaling = decomposed && decomposed.scaling; return scaling ? new LinkedPoint(scaling.x, scaling.y, this, "setScaling") : undefined }, setScaling: function() { var current = this.getScaling(), scaling = Point.read(arguments, 0, { clone: true, readNull: true }); if (current && scaling) { this.scale(scaling.x / current.x, scaling.y / current.y) } }, getMatrix: function() { return this._matrix }, setMatrix: function() { var matrix = this._matrix; matrix.initialize.apply(matrix, arguments) }, transform: function(matrix) { this._matrix.append(matrix) }, scrollBy: function() { this.translate(Point.read(arguments).negate()) } }), { projectToView: function() { return this._matrix._transformPoint(Point.read(arguments)) }, viewToProject: function() { return this._matrix._inverseTransform(Point.read(arguments)) }, getEventPoint: function(event) { return this.viewToProject(DomEvent.getOffset(event, this._element)) } }, { statics: { _views: [], _viewsById: {}, _id: 0, create: function(project, element) { if (document && typeof element === "string") element = document.getElementById(element); var ctor = window ? CanvasView : View; return new ctor(project, element) } } }, new function() { if (!window) return; var prevFocus, tempFocus, dragging = false, mouseDown = false; function getView(event) { var target = DomEvent.getTarget(event); return target.getAttribute && View._viewsById[target.getAttribute("id")] } function updateFocus() { var view = View._focused; if (!view || !view.isVisible()) { for (var i = 0, l = View._views.length; i < l; i++) { if ((view = View._views[i]).isVisible()) { View._focused = tempFocus = view; break } } } } function handleMouseMove(view, event, point) { view._handleMouseEvent("mousemove", event, point) } var navigator = window.navigator, mousedown, mousemove, mouseup; if (navigator.pointerEnabled || navigator.msPointerEnabled) { mousedown = "pointerdown MSPointerDown"; mousemove = "pointermove MSPointerMove"; mouseup = "pointerup pointercancel MSPointerUp MSPointerCancel" } else { mousedown = "touchstart"; mousemove = "touchmove"; mouseup = "touchend touchcancel"; if (!("ontouchstart" in window && navigator.userAgent.match(/mobile|tablet|ip(ad|hone|od)|android|silk/i))) { mousedown += " mousedown"; mousemove += " mousemove"; mouseup += " mouseup" } } var viewEvents = {}, docEvents = { mouseout: function(event) { var view = View._focused, target = DomEvent.getRelatedTarget(event); if (view && (!target || target.nodeName === "HTML")) { var offset = DomEvent.getOffset(event, view._element), x = offset.x, abs = Math.abs, ax = abs(x), max = 1 << 25, diff = ax - max; offset.x = abs(diff) < ax ? diff * (x < 0 ? -1 : 1) : x; handleMouseMove(view, event, view.viewToProject(offset)) } }, scroll: updateFocus }; viewEvents[mousedown] = function(event) { var view = View._focused = getView(event); if (!dragging) { dragging = true; view._handleMouseEvent("mousedown", event) } }; docEvents[mousemove] = function(event) { var view = View._focused; if (!mouseDown) { var target = getView(event); if (target) { if (view !== target) { if (view) handleMouseMove(view, event); if (!prevFocus) prevFocus = view; view = View._focused = tempFocus = target } } else if (tempFocus && tempFocus === view) { if (prevFocus && !prevFocus.isInserted()) prevFocus = null; view = View._focused = prevFocus; prevFocus = null; updateFocus() } } if (view) handleMouseMove(view, event) }; docEvents[mousedown] = function() { mouseDown = true }; docEvents[mouseup] = function(event) { var view = View._focused; if (view && dragging) view._handleMouseEvent("mouseup", event); mouseDown = dragging = false }; DomEvent.add(document, docEvents); DomEvent.add(window, { load: updateFocus }); var called = false, prevented = false, fallbacks = { doubleclick: "click", mousedrag: "mousemove" }, wasInView = false, overView, downPoint, lastPoint, downItem, overItem, dragItem, clickItem, clickTime, dblClick; function emitMouseEvent(obj, target, type, event, point, prevPoint, stopItem) { var stopped = false, mouseEvent; function emit(obj, type) { if (obj.responds(type)) { if (!mouseEvent) { mouseEvent = new MouseEvent(type, event, point, target || obj, prevPoint ? point.subtract(prevPoint) : null) } if (obj.emit(type, mouseEvent)) { called = true; if (mouseEvent.prevented) prevented = true; if (mouseEvent.stopped) return stopped = true } } else { var fallback = fallbacks[type]; if (fallback) return emit(obj, fallback) } } while (obj && obj !== stopItem) { if (emit(obj, type)) break; obj = obj._parent } return stopped } function emitMouseEvents(view, hitItem, type, event, point, prevPoint) { view._project.removeOn(type); prevented = called = false; return dragItem && emitMouseEvent(dragItem, null, type, event, point, prevPoint) || hitItem && hitItem !== dragItem && !hitItem.isDescendant(dragItem) && emitMouseEvent(hitItem, null, type, event, point, prevPoint, dragItem) || emitMouseEvent(view, dragItem || hitItem || view, type, event, point, prevPoint) } var itemEventsMap = { mousedown: { mousedown: 1, mousedrag: 1, click: 1, doubleclick: 1 }, mouseup: { mouseup: 1, mousedrag: 1, click: 1, doubleclick: 1 }, mousemove: { mousedrag: 1, mousemove: 1, mouseenter: 1, mouseleave: 1 } }; return { _viewEvents: viewEvents, _handleMouseEvent: function(type, event, point) { var itemEvents = this._itemEvents, hitItems = itemEvents.native[type], nativeMove = type === "mousemove", tool = this._scope.tool, view = this; function responds(type) { return itemEvents.virtual[type] || view.responds(type) || tool && tool.responds(type) } if (nativeMove && dragging && responds("mousedrag")) type = "mousedrag"; if (!point) point = this.getEventPoint(event); var inView = this.getBounds().contains(point), hit = hitItems && inView && view._project.hitTest(point, { tolerance: 0, fill: true, stroke: true }), hitItem = hit && hit.item || null, handle = false, mouse = {}; mouse[type.substr(5)] = true; if (hitItems && hitItem !== overItem) { if (overItem) { emitMouseEvent(overItem, null, "mouseleave", event, point) } if (hitItem) { emitMouseEvent(hitItem, null, "mouseenter", event, point) } overItem = hitItem } if (wasInView ^ inView) { emitMouseEvent(this, null, inView ? "mouseenter" : "mouseleave", event, point); overView = inView ? this : null; handle = true } if ((inView || mouse.drag) && !point.equals(lastPoint)) { emitMouseEvents(this, hitItem, nativeMove ? type : "mousemove", event, point, lastPoint); handle = true } wasInView = inView; if (mouse.down && inView || mouse.up && downPoint) { emitMouseEvents(this, hitItem, type, event, point, downPoint); if (mouse.down) { dblClick = hitItem === clickItem && Date.now() - clickTime < 300; downItem = clickItem = hitItem; if (!prevented && hitItem) { var item = hitItem; while (item && !item.responds("mousedrag")) item = item._parent; if (item) dragItem = hitItem } downPoint = point } else if (mouse.up) { if (!prevented && hitItem === downItem) { clickTime = Date.now(); emitMouseEvents(this, hitItem, dblClick ? "doubleclick" : "click", event, point, downPoint); dblClick = false } downItem = dragItem = null } wasInView = false; handle = true } lastPoint = point; if (handle && tool) { called = tool._handleMouseEvent(type, event, point, mouse) || called } if (event.cancelable !== false && (called && !mouse.move || mouse.down && responds("mouseup"))) { event.preventDefault() } }, _handleKeyEvent: function(type, event, key, character) { var scope = this._scope, tool = scope.tool, keyEvent; function emit(obj) { if (obj.responds(type)) { paper = scope; obj.emit(type, keyEvent = keyEvent || new KeyEvent(type, event, key, character)) } } if (this.isVisible()) { emit(this); if (tool && tool.responds(type)) emit(tool) } }, _countItemEvent: function(type, sign) { var itemEvents = this._itemEvents, native = itemEvents.native, virtual = itemEvents.virtual; for (var key in itemEventsMap) { native[key] = (native[key] || 0) + (itemEventsMap[key][type] || 0) * sign } virtual[type] = (virtual[type] || 0) + sign }, statics: { updateFocus: updateFocus, _resetState: function() { dragging = mouseDown = called = wasInView = false; prevFocus = tempFocus = overView = downPoint = lastPoint = downItem = overItem = dragItem = clickItem = clickTime = dblClick = null } } } }); var CanvasView = View.extend({ _class: "CanvasView", initialize: function CanvasView(project, canvas) { if (!(canvas instanceof window.HTMLCanvasElement)) { var size = Size.read(arguments, 1); if (size.isZero()) throw new Error("Cannot create CanvasView with the provided argument: " + Base.slice(arguments, 1)); canvas = CanvasProvider.getCanvas(size) } var ctx = this._context = canvas.getContext("2d"); ctx.save(); this._pixelRatio = 1; if (!/^off|false$/.test(PaperScope.getAttribute(canvas, "hidpi"))) { var deviceRatio = window.devicePixelRatio || 1, backingStoreRatio = DomElement.getPrefixed(ctx, "backingStorePixelRatio") || 1; this._pixelRatio = deviceRatio / backingStoreRatio } View.call(this, project, canvas); this._needsUpdate = true }, remove: function remove() { this._context.restore(); return remove.base.call(this) }, _setElementSize: function _setElementSize(width, height) { var pixelRatio = this._pixelRatio; _setElementSize.base.call(this, width * pixelRatio, height * pixelRatio); if (pixelRatio !== 1) { var element = this._element, ctx = this._context; if (!PaperScope.hasAttribute(element, "resize")) { var style = element.style; style.width = width + "px"; style.height = height + "px" } ctx.restore(); ctx.save(); ctx.scale(pixelRatio, pixelRatio) } }, getPixelSize: function getPixelSize(size) { var agent = paper.agent, pixels; if (agent && agent.firefox) { pixels = getPixelSize.base.call(this, size) } else { var ctx = this._context, prevFont = ctx.font; ctx.font = size + " serif"; pixels = parseFloat(ctx.font); ctx.font = prevFont } return pixels }, getTextWidth: function(font, lines) { var ctx = this._context, prevFont = ctx.font, width = 0; ctx.font = font; for (var i = 0, l = lines.length; i < l; i++) width = Math.max(width, ctx.measureText(lines[i]).width); ctx.font = prevFont; return width }, update: function() { if (!this._needsUpdate) return false; var project = this._project, ctx = this._context, size = this._viewSize; ctx.clearRect(0, 0, size.width + 1, size.height + 1); if (project) project.draw(ctx, this._matrix, this._pixelRatio); this._needsUpdate = false; return true } }); var Event = Base.extend({ _class: "Event", initialize: function Event(event) { this.event = event; this.type = event && event.type }, prevented: false, stopped: false, preventDefault: function() { this.prevented = true; this.event.preventDefault() }, stopPropagation: function() { this.stopped = true; this.event.stopPropagation() }, stop: function() { this.stopPropagation(); this.preventDefault() }, getTimeStamp: function() { return this.event.timeStamp }, getModifiers: function() { return Key.modifiers } }); var KeyEvent = Event.extend({ _class: "KeyEvent", initialize: function KeyEvent(type, event, key, character) { this.type = type; this.event = event; this.key = key; this.character = character }, toString: function() { return "{ type: '" + this.type + "', key: '" + this.key + "', character: '" + this.character + "', modifiers: " + this.getModifiers() + " }" } }); var Key = new function() { var keyLookup = { "\t": "tab", " ": "space", "\b": "backspace", "": "delete", Spacebar: "space", Del: "delete", Win: "meta", Esc: "escape" }, charLookup = { tab: "\t", space: " ", enter: "\r" }, keyMap = {}, charMap = {}, metaFixMap, downKey, modifiers = new Base({ shift: false, control: false, alt: false, meta: false, capsLock: false, space: false }).inject({ option: { get: function() { return this.alt } }, command: { get: function() { var agent = paper && paper.agent; return agent && agent.mac ? this.meta : this.control } } }); function getKey(event) { var key = event.key || event.keyIdentifier; key = /^U\+/.test(key) ? String.fromCharCode(parseInt(key.substr(2), 16)) : /^Arrow[A-Z]/.test(key) ? key.substr(5) : key === "Unidentified" || key === undefined ? String.fromCharCode(event.keyCode) : key; return keyLookup[key] || (key.length > 1 ? Base.hyphenate(key) : key.toLowerCase()) } function handleKey(down, key, character, event) { var type = down ? "keydown" : "keyup", view = View._focused, name; keyMap[key] = down; if (down) { charMap[key] = character } else { delete charMap[key] } if (key.length > 1 && (name = Base.camelize(key)) in modifiers) { modifiers[name] = down; var agent = paper && paper.agent; if (name === "meta" && agent && agent.mac) { if (down) { metaFixMap = {} } else { for (var k in metaFixMap) { if (k in charMap) handleKey(false, k, metaFixMap[k], event) } metaFixMap = null } } } else if (down && metaFixMap) { metaFixMap[key] = character } if (view) { view._handleKeyEvent(down ? "keydown" : "keyup", event, key, character) } } DomEvent.add(document, { keydown: function(event) { var key = getKey(event), agent = paper && paper.agent; if (key.length > 1 || agent && (agent.chrome && (event.altKey || agent.mac && event.metaKey || !agent.mac && event.ctrlKey))) { handleKey(true, key, charLookup[key] || (key.length > 1 ? "" : key), event) } else { downKey = key } }, keypress: function(event) { if (downKey) { var key = getKey(event), code = event.charCode, character = code >= 32 ? String.fromCharCode(code) : key.length > 1 ? "" : key; if (key !== downKey) { key = character.toLowerCase() } handleKey(true, key, character, event); downKey = null } }, keyup: function(event) { var key = getKey(event); if (key in charMap) handleKey(false, key, charMap[key], event) } }); DomEvent.add(window, { blur: function(event) { for (var key in charMap) handleKey(false, key, charMap[key], event) } }); return { modifiers: modifiers, isDown: function(key) { return !!keyMap[key] } } }; var MouseEvent = Event.extend({ _class: "MouseEvent", initialize: function MouseEvent(type, event, point, target, delta) { this.type = type; this.event = event; this.point = point; this.target = target; this.delta = delta }, toString: function() { return "{ type: '" + this.type + "', point: " + this.point + ", target: " + this.target + (this.delta ? ", delta: " + this.delta : "") + ", modifiers: " + this.getModifiers() + " }" } }); var ToolEvent = Event.extend({ _class: "ToolEvent", _item: null, initialize: function ToolEvent(tool, type, event) { this.tool = tool; this.type = type; this.event = event }, _choosePoint: function(point, toolPoint) { return point ? point : toolPoint ? toolPoint.clone() : null }, getPoint: function() { return this._choosePoint(this._point, this.tool._point) }, setPoint: function(point) { this._point = point }, getLastPoint: function() { return this._choosePoint(this._lastPoint, this.tool._lastPoint) }, setLastPoint: function(lastPoint) { this._lastPoint = lastPoint }, getDownPoint: function() { return this._choosePoint(this._downPoint, this.tool._downPoint) }, setDownPoint: function(downPoint) { this._downPoint = downPoint }, getMiddlePoint: function() { if (!this._middlePoint && this.tool._lastPoint) { return this.tool._point.add(this.tool._lastPoint).divide(2) } return this._middlePoint }, setMiddlePoint: function(middlePoint) { this._middlePoint = middlePoint }, getDelta: function() { return !this._delta && this.tool._lastPoint ? this.tool._point.subtract(this.tool._lastPoint) : this._delta }, setDelta: function(delta) { this._delta = delta }, getCount: function() { return this.tool[/^mouse(down|up)$/.test(this.type) ? "_downCount" : "_moveCount"] }, setCount: function(count) { this.tool[/^mouse(down|up)$/.test(this.type) ? "downCount" : "count"] = count }, getItem: function() { if (!this._item) { var result = this.tool._scope.project.hitTest(this.getPoint()); if (result) { var item = result.item, parent = item._parent; while (/^(Group|CompoundPath)$/.test(parent._class)) { item = parent; parent = parent._parent } this._item = item } } return this._item }, setItem: function(item) { this._item = item }, toString: function() { return "{ type: " + this.type + ", point: " + this.getPoint() + ", count: " + this.getCount() + ", modifiers: " + this.getModifiers() + " }" } }); var Tool = PaperScopeItem.extend({ _class: "Tool", _list: "tools", _reference: "tool", _events: ["onMouseDown", "onMouseUp", "onMouseDrag", "onMouseMove", "onActivate", "onDeactivate", "onEditOptions", "onKeyDown", "onKeyUp"], initialize: function Tool(props) { PaperScopeItem.call(this); this._moveCount = -1; this._downCount = -1; this.set(props) }, getMinDistance: function() { return this._minDistance }, setMinDistance: function(minDistance) { this._minDistance = minDistance; if (minDistance != null && this._maxDistance != null && minDistance > this._maxDistance) { this._maxDistance = minDistance } }, getMaxDistance: function() { return this._maxDistance }, setMaxDistance: function(maxDistance) { this._maxDistance = maxDistance; if (this._minDistance != null && maxDistance != null && maxDistance < this._minDistance) { this._minDistance = maxDistance } }, getFixedDistance: function() { return this._minDistance == this._maxDistance ? this._minDistance : null }, setFixedDistance: function(distance) { this._minDistance = this._maxDistance = distance }, _handleMouseEvent: function(type, event, point, mouse) { paper = this._scope; if (mouse.drag && !this.responds(type)) type = "mousemove"; var move = mouse.move || mouse.drag, responds = this.responds(type), minDistance = this.minDistance, maxDistance = this.maxDistance, called = false, tool = this; function update(minDistance, maxDistance) { var pt = point, toolPoint = move ? tool._point : tool._downPoint || pt; if (move) { if (tool._moveCount >= 0 && pt.equals(toolPoint)) { return false } if (toolPoint && (minDistance != null || maxDistance != null)) { var vector = pt.subtract(toolPoint), distance = vector.getLength(); if (distance < (minDistance || 0)) return false; if (maxDistance) { pt = toolPoint.add(vector.normalize(Math.min(distance, maxDistance))) } } tool._moveCount++ } tool._point = pt; tool._lastPoint = toolPoint || pt; if (mouse.down) { tool._moveCount = -1; tool._downPoint = pt; tool._downCount++ } return true } function emit() { if (responds) { called = tool.emit(type, new ToolEvent(tool, type, event)) || called } } if (mouse.down) { update(); emit() } else if (mouse.up) { update(null, maxDistance); emit() } else if (responds) { while (update(minDistance, maxDistance)) emit() } return called } }); var Http = { request: function(options) { var xhr = new self.XMLHttpRequest; xhr.open((options.method || "get").toUpperCase(), options.url, Base.pick(options.async, true)); if (options.mimeType) xhr.overrideMimeType(options.mimeType); xhr.onload = function() { var status = xhr.status; if (status === 0 || status === 200) { if (options.onLoad) { options.onLoad.call(xhr, xhr.responseText) } } else { xhr.onerror() } }; xhr.onerror = function() { var status = xhr.status, message = 'Could not load "' + options.url + '" (Status: ' + status + ")"; if (options.onError) { options.onError(message, status) } else { throw new Error(message) } }; return xhr.send(null) } }; var CanvasProvider = { canvases: [], getCanvas: function(width, height) { if (!window) return null; var canvas, clear = true; if (typeof width === "object") { height = width.height; width = width.width } if (this.canvases.length) { canvas = this.canvases.pop() } else { canvas = document.createElement("canvas"); clear = false } var ctx = canvas.getContext("2d"); if (!ctx) { throw new Error("Canvas " + canvas + " is unable to provide a 2D context.") } if (canvas.width === width && canvas.height === height) { if (clear) ctx.clearRect(0, 0, width + 1, height + 1) } else { canvas.width = width; canvas.height = height } ctx.save(); return canvas }, getContext: function(width, height) { var canvas = this.getCanvas(width, height); return canvas ? canvas.getContext("2d") : null }, release: function(obj) { var canvas = obj && obj.canvas ? obj.canvas : obj; if (canvas && canvas.getContext) { canvas.getContext("2d").restore(); this.canvases.push(canvas) } } }; var BlendMode = new function() { var min = Math.min, max = Math.max, abs = Math.abs, sr, sg, sb, sa, br, bg, bb, ba, dr, dg, db; function getLum(r, g, b) { return .2989 * r + .587 * g + .114 * b } function setLum(r, g, b, l) { var d = l - getLum(r, g, b); dr = r + d; dg = g + d; db = b + d; var l = getLum(dr, dg, db), mn = min(dr, dg, db), mx = max(dr, dg, db); if (mn < 0) { var lmn = l - mn; dr = l + (dr - l) * l / lmn; dg = l + (dg - l) * l / lmn; db = l + (db - l) * l / lmn } if (mx > 255) { var ln = 255 - l, mxl = mx - l; dr = l + (dr - l) * ln / mxl; dg = l + (dg - l) * ln / mxl; db = l + (db - l) * ln / mxl } } function getSat(r, g, b) { return max(r, g, b) - min(r, g, b) } function setSat(r, g, b, s) { var col = [r, g, b], mx = max(r, g, b), mn = min(r, g, b), md; mn = mn === r ? 0 : mn === g ? 1 : 2; mx = mx === r ? 0 : mx === g ? 1 : 2; md = min(mn, mx) === 0 ? max(mn, mx) === 1 ? 2 : 1 : 0; if (col[mx] > col[mn]) { col[md] = (col[md] - col[mn]) * s / (col[mx] - col[mn]); col[mx] = s } else { col[md] = col[mx] = 0 } col[mn] = 0; dr = col[0]; dg = col[1]; db = col[2] } var modes = { multiply: function() { dr = br * sr / 255; dg = bg * sg / 255; db = bb * sb / 255 }, screen: function() { dr = br + sr - br * sr / 255; dg = bg + sg - bg * sg / 255; db = bb + sb - bb * sb / 255 }, overlay: function() { dr = br < 128 ? 2 * br * sr / 255 : 255 - 2 * (255 - br) * (255 - sr) / 255; dg = bg < 128 ? 2 * bg * sg / 255 : 255 - 2 * (255 - bg) * (255 - sg) / 255; db = bb < 128 ? 2 * bb * sb / 255 : 255 - 2 * (255 - bb) * (255 - sb) / 255 }, "soft-light": function() { var t = sr * br / 255; dr = t + br * (255 - (255 - br) * (255 - sr) / 255 - t) / 255; t = sg * bg / 255; dg = t + bg * (255 - (255 - bg) * (255 - sg) / 255 - t) / 255; t = sb * bb / 255; db = t + bb * (255 - (255 - bb) * (255 - sb) / 255 - t) / 255 }, "hard-light": function() { dr = sr < 128 ? 2 * sr * br / 255 : 255 - 2 * (255 - sr) * (255 - br) / 255; dg = sg < 128 ? 2 * sg * bg / 255 : 255 - 2 * (255 - sg) * (255 - bg) / 255; db = sb < 128 ? 2 * sb * bb / 255 : 255 - 2 * (255 - sb) * (255 - bb) / 255 }, "color-dodge": function() { dr = br === 0 ? 0 : sr === 255 ? 255 : min(255, 255 * br / (255 - sr)); dg = bg === 0 ? 0 : sg === 255 ? 255 : min(255, 255 * bg / (255 - sg)); db = bb === 0 ? 0 : sb === 255 ? 255 : min(255, 255 * bb / (255 - sb)) }, "color-burn": function() { dr = br === 255 ? 255 : sr === 0 ? 0 : max(0, 255 - (255 - br) * 255 / sr); dg = bg === 255 ? 255 : sg === 0 ? 0 : max(0, 255 - (255 - bg) * 255 / sg); db = bb === 255 ? 255 : sb === 0 ? 0 : max(0, 255 - (255 - bb) * 255 / sb) }, darken: function() { dr = br < sr ? br : sr; dg = bg < sg ? bg : sg; db = bb < sb ? bb : sb }, lighten: function() { dr = br > sr ? br : sr; dg = bg > sg ? bg : sg; db = bb > sb ? bb : sb }, difference: function() { dr = br - sr; if (dr < 0) dr = -dr; dg = bg - sg; if (dg < 0) dg = -dg; db = bb - sb; if (db < 0) db = -db }, exclusion: function() { dr = br + sr * (255 - br - br) / 255; dg = bg + sg * (255 - bg - bg) / 255; db = bb + sb * (255 - bb - bb) / 255 }, hue: function() { setSat(sr, sg, sb, getSat(br, bg, bb)); setLum(dr, dg, db, getLum(br, bg, bb)) }, saturation: function() { setSat(br, bg, bb, getSat(sr, sg, sb)); setLum(dr, dg, db, getLum(br, bg, bb)) }, luminosity: function() { setLum(br, bg, bb, getLum(sr, sg, sb)) }, color: function() { setLum(sr, sg, sb, getLum(br, bg, bb)) }, add: function() { dr = min(br + sr, 255); dg = min(bg + sg, 255); db = min(bb + sb, 255) }, subtract: function() { dr = max(br - sr, 0); dg = max(bg - sg, 0); db = max(bb - sb, 0) }, average: function() { dr = (br + sr) / 2; dg = (bg + sg) / 2; db = (bb + sb) / 2 }, negation: function() { dr = 255 - abs(255 - sr - br); dg = 255 - abs(255 - sg - bg); db = 255 - abs(255 - sb - bb) } }; var nativeModes = this.nativeModes = Base.each(["source-over", "source-in", "source-out", "source-atop", "destination-over", "destination-in", "destination-out", "destination-atop", "lighter", "darker", "copy", "xor"], function(mode) { this[mode] = true }, {}); var ctx = CanvasProvider.getContext(1, 1); if (ctx) { Base.each(modes, function(func, mode) { var darken = mode === "darken", ok = false; ctx.save(); try { ctx.fillStyle = darken ? "#300" : "#a00"; ctx.fillRect(0, 0, 1, 1); ctx.globalCompositeOperation = mode; if (ctx.globalCompositeOperation === mode) { ctx.fillStyle = darken ? "#a00" : "#300"; ctx.fillRect(0, 0, 1, 1); ok = ctx.getImageData(0, 0, 1, 1).data[0] !== darken ? 170 : 51 } } catch (e) {} ctx.restore(); nativeModes[mode] = ok }); CanvasProvider.release(ctx) } this.process = function(mode, srcContext, dstContext, alpha, offset) { var srcCanvas = srcContext.canvas, normal = mode === "normal"; if (normal || nativeModes[mode]) { dstContext.save(); dstContext.setTransform(1, 0, 0, 1, 0, 0); dstContext.globalAlpha = alpha; if (!normal) dstContext.globalCompositeOperation = mode; dstContext.drawImage(srcCanvas, offset.x, offset.y); dstContext.restore() } else { var process = modes[mode]; if (!process) return; var dstData = dstContext.getImageData(offset.x, offset.y, srcCanvas.width, srcCanvas.height), dst = dstData.data, src = srcContext.getImageData(0, 0, srcCanvas.width, srcCanvas.height).data; for (var i = 0, l = dst.length; i < l; i += 4) { sr = src[i]; br = dst[i]; sg = src[i + 1]; bg = dst[i + 1]; sb = src[i + 2]; bb = dst[i + 2]; sa = src[i + 3]; ba = dst[i + 3]; process(); var a1 = sa * alpha / 255, a2 = 1 - a1; dst[i] = a1 * dr + a2 * br; dst[i + 1] = a1 * dg + a2 * bg; dst[i + 2] = a1 * db + a2 * bb; dst[i + 3] = sa * alpha + a2 * ba } dstContext.putImageData(dstData, offset.x, offset.y) } } }; var SvgElement = new function() { var svg = "http://www.w3.org/2000/svg", xmlns = "http://www.w3.org/2000/xmlns", xlink = "http://www.w3.org/1999/xlink", attributeNamespace = { href: xlink, xlink: xmlns, xmlns: xmlns + "/", "xmlns:xlink": xmlns + "/" }; function create(tag, attributes, formatter) { return set(document.createElementNS(svg, tag), attributes, formatter) } function get(node, name) { var namespace = attributeNamespace[name], value = namespace ? node.getAttributeNS(namespace, name) : node.getAttribute(name); return value === "null" ? null : value } function set(node, attributes, formatter) { for (var name in attributes) { var value = attributes[name], namespace = attributeNamespace[name]; if (typeof value === "number" && formatter) value = formatter.number(value); if (namespace) { node.setAttributeNS(namespace, name, value) } else { node.setAttribute(name, value) } } return node } return { svg: svg, xmlns: xmlns, xlink: xlink, create: create, get: get, set: set } }; var SvgStyles = Base.each({ fillColor: ["fill", "color"], fillRule: ["fill-rule", "string"], strokeColor: ["stroke", "color"], strokeWidth: ["stroke-width", "number"], strokeCap: ["stroke-linecap", "string"], strokeJoin: ["stroke-linejoin", "string"], strokeScaling: ["vector-effect", "lookup", { true: "none", false: "non-scaling-stroke" }, function(item, value) { return !value && (item instanceof PathItem || item instanceof Shape || item instanceof TextItem) }], miterLimit: ["stroke-miterlimit", "number"], dashArray: ["stroke-dasharray", "array"], dashOffset: ["stroke-dashoffset", "number"], fontFamily: ["font-family", "string"], fontWeight: ["font-weight", "string"], fontSize: ["font-size", "number"], justification: ["text-anchor", "lookup", { left: "start", center: "middle", right: "end" }], opacity: ["opacity", "number"], blendMode: ["mix-blend-mode", "style"] }, function(entry, key) { var part = Base.capitalize(key), lookup = entry[2]; this[key] = { type: entry[1], property: key, attribute: entry[0], toSVG: lookup, fromSVG: lookup && Base.each(lookup, function(value, name) { this[value] = name }, {}), exportFilter: entry[3], get: "get" + part, set: "set" + part } }, {}); new function() { var formatter; function getTransform(matrix, coordinates, center) { var attrs = new Base, trans = matrix.getTranslation(); if (coordinates) { matrix = matrix._shiftless(); var point = matrix._inverseTransform(trans); attrs[center ? "cx" : "x"] = point.x; attrs[center ? "cy" : "y"] = point.y; trans = null } if (!matrix.isIdentity()) { var decomposed = matrix.decompose(); if (decomposed) { var parts = [], angle = decomposed.rotation, scale = decomposed.scaling, skew = decomposed.skewing; if (trans && !trans.isZero()) parts.push("translate(" + formatter.point(trans) + ")"); if (angle) parts.push("rotate(" + formatter.number(angle) + ")"); if (!Numerical.isZero(scale.x - 1) || !Numerical.isZero(scale.y - 1)) parts.push("scale(" + formatter.point(scale) + ")"); if (skew.x) parts.push("skewX(" + formatter.number(skew.x) + ")"); if (skew.y) parts.push("skewY(" + formatter.number(skew.y) + ")"); attrs.transform = parts.join(" ") } else { attrs.transform = "matrix(" + matrix.getValues().join(",") + ")" } } return attrs } function exportGroup(item, options) { var attrs = getTransform(item._matrix), children = item._children; var node = SvgElement.create("g", attrs, formatter); for (var i = 0, l = children.length; i < l; i++) { var child = children[i]; var childNode = exportSVG(child, options); if (childNode) { if (child.isClipMask()) { var clip = SvgElement.create("clipPath"); clip.appendChild(childNode); setDefinition(child, clip, "clip"); SvgElement.set(node, { "clip-path": "url(#" + clip.id + ")" }) } else { node.appendChild(childNode) } } } return node } function exportRaster(item, options) { var attrs = getTransform(item._matrix, true), size = item.getSize(), image = item.getImage(); attrs.x -= size.width / 2; attrs.y -= size.height / 2; attrs.width = size.width; attrs.height = size.height; attrs.href = options.embedImages == false && image && image.src || item.toDataURL(); return SvgElement.create("image", attrs, formatter) } function exportPath(item, options) { var matchShapes = options.matchShapes; if (matchShapes) { var shape = item.toShape(false); if (shape) return exportShape(shape, options) } var segments = item._segments, length = segments.length, type, attrs = getTransform(item._matrix); if (matchShapes && length >= 2 && !item.hasHandles()) { if (length > 2) { type = item._closed ? "polygon" : "polyline"; var parts = []; for (var i = 0; i < length; i++) { parts.push(formatter.point(segments[i]._point)) } attrs.points = parts.join(" ") } else { type = "line"; var start = segments[0]._point, end = segments[1]._point; attrs.set({ x1: start.x, y1: start.y, x2: end.x, y2: end.y }) } } else { type = "path"; attrs.d = item.getPathData(null, options.precision) } return SvgElement.create(type, attrs, formatter) } function exportShape(item) { var type = item._type, radius = item._radius, attrs = getTransform(item._matrix, true, type !== "rectangle"); if (type === "rectangle") { type = "rect"; var size = item._size, width = size.width, height = size.height; attrs.x -= width / 2; attrs.y -= height / 2; attrs.width = width; attrs.height = height; if (radius.isZero()) radius = null } if (radius) { if (type === "circle") { attrs.r = radius } else { attrs.rx = radius.width; attrs.ry = radius.height } } return SvgElement.create(type, attrs, formatter) } function exportCompoundPath(item, options) { var attrs = getTransform(item._matrix); var data = item.getPathData(null, options.precision); if (data) attrs.d = data; return SvgElement.create("path", attrs, formatter) } function exportSymbolItem(item, options) { var attrs = getTransform(item._matrix, true), definition = item._definition, node = getDefinition(definition, "symbol"), definitionItem = definition._item, bounds = definitionItem.getBounds(); if (!node) { node = SvgElement.create("symbol", { viewBox: formatter.rectangle(bounds) }); node.appendChild(exportSVG(definitionItem, options)); setDefinition(definition, node, "symbol") } attrs.href = "#" + node.id; attrs.x += bounds.x; attrs.y += bounds.y; attrs.width = bounds.width; attrs.height = bounds.height; attrs.overflow = "visible"; return SvgElement.create("use", attrs, formatter) } function exportGradient(color) { var gradientNode = getDefinition(color, "color"); if (!gradientNode) { var gradient = color.getGradient(), radial = gradient._radial, origin = color.getOrigin(), destination = color.getDestination(), attrs; if (radial) { attrs = { cx: origin.x, cy: origin.y, r: origin.getDistance(destination) }; var highlight = color.getHighlight(); if (highlight) { attrs.fx = highlight.x; attrs.fy = highlight.y } } else { attrs = { x1: origin.x, y1: origin.y, x2: destination.x, y2: destination.y } } attrs.gradientUnits = "userSpaceOnUse"; gradientNode = SvgElement.create((radial ? "radial" : "linear") + "Gradient", attrs, formatter); var stops = gradient._stops; for (var i = 0, l = stops.length; i < l; i++) { var stop = stops[i], stopColor = stop._color, alpha = stopColor.getAlpha(), offset = stop._offset; attrs = { offset: offset == null ? i / (l - 1) : offset }; if (stopColor) attrs["stop-color"] = stopColor.toCSS(true); if (alpha < 1) attrs["stop-opacity"] = alpha; gradientNode.appendChild(SvgElement.create("stop", attrs, formatter)) } setDefinition(color, gradientNode, "color") } return "url(#" + gradientNode.id + ")" } function exportText(item) { var node = SvgElement.create("text", getTransform(item._matrix, true), formatter); node.textContent = item._content; return node } var exporters = { Group: exportGroup, Layer: exportGroup, Raster: exportRaster, Path: exportPath, Shape: exportShape, CompoundPath: exportCompoundPath, SymbolItem: exportSymbolItem, PointText: exportText }; function applyStyle(item, node, isRoot) { var attrs = {}, parent = !isRoot && item.getParent(), style = []; if (item._name != null) attrs.id = item._name; Base.each(SvgStyles, function(entry) { var get = entry.get, type = entry.type, value = item[get](); if (entry.exportFilter ? entry.exportFilter(item, value) : !parent || !Base.equals(parent[get](), value)) { if (type === "color" && value != null) { var alpha = value.getAlpha(); if (alpha < 1) attrs[entry.attribute + "-opacity"] = alpha } if (type === "style") { style.push(entry.attribute + ": " + value) } else { attrs[entry.attribute] = value == null ? "none" : type === "color" ? value.gradient ? exportGradient(value, item) : value.toCSS(true) : type === "array" ? value.join(",") : type === "lookup" ? entry.toSVG[value] : value } } }); if (style.length) attrs.style = style.join(";"); if (attrs.opacity === 1) delete attrs.opacity; if (!item._visible) attrs.visibility = "hidden"; return SvgElement.set(node, attrs, formatter) } var definitions; function getDefinition(item, type) { if (!definitions) definitions = { ids: {}, svgs: {} }; return item && definitions.svgs[type + "-" + (item._id || item.__id || (item.__id = UID.get("svg")))] } function setDefinition(item, node, type) { if (!definitions) getDefinition(); var typeId = definitions.ids[type] = (definitions.ids[type] || 0) + 1; node.id = type + "-" + typeId; definitions.svgs[type + "-" + (item._id || item.__id)] = node } function exportDefinitions(node, options) { var svg = node, defs = null; if (definitions) { svg = node.nodeName.toLowerCase() === "svg" && node; for (var i in definitions.svgs) { if (!defs) { if (!svg) { svg = SvgElement.create("svg"); svg.appendChild(node) } defs = svg.insertBefore(SvgElement.create("defs"), svg.firstChild) } defs.appendChild(definitions.svgs[i]) } definitions = null } return options.asString ? (new self.XMLSerializer).serializeToString(svg) : svg } function exportSVG(item, options, isRoot) { var exporter = exporters[item._class], node = exporter && exporter(item, options); if (node) { var onExport = options.onExport; if (onExport) node = onExport(item, node, options) || node; var data = JSON.stringify(item._data); if (data && data !== "{}" && data !== "null") node.setAttribute("data-paper-data", data) } return node && applyStyle(item, node, isRoot) } function setOptions(options) { if (!options) options = {}; formatter = new Formatter(options.precision); return options } Item.inject({ exportSVG: function(options) { options = setOptions(options); return exportDefinitions(exportSVG(this, options, true), options) } }); Project.inject({ exportSVG: function(options) { options = setOptions(options); var children = this._children, view = this.getView(), bounds = Base.pick(options.bounds, "view"), mx = options.matrix || bounds === "view" && view._matrix, matrix = mx && Matrix.read([mx]), rect = bounds === "view" ? new Rectangle([0, 0], view.getViewSize()) : bounds === "content" ? Item._getBounds(children, matrix, { stroke: true }).rect : Rectangle.read([bounds], 0, { readNull: true }), attrs = { version: "1.1", xmlns: SvgElement.svg, "xmlns:xlink": SvgElement.xlink }; if (rect) { attrs.width = rect.width; attrs.height = rect.height; if (rect.x || rect.y) attrs.viewBox = formatter.rectangle(rect) } var node = SvgElement.create("svg", attrs, formatter), parent = node; if (matrix && !matrix.isIdentity()) { parent = node.appendChild(SvgElement.create("g", getTransform(matrix), formatter)) } for (var i = 0, l = children.length; i < l; i++) { parent.appendChild(exportSVG(children[i], options, true)) } return exportDefinitions(node, options) } }) }; new function() { var definitions = {}, rootSize; function getValue(node, name, isString, allowNull, allowPercent) { var value = SvgElement.get(node, name), res = value == null ? allowNull ? null : isString ? "" : 0 : isString ? value : parseFloat(value); return /%\s*$/.test(value) ? res / 100 * (allowPercent ? 1 : rootSize[/x|^width/.test(name) ? "width" : "height"]) : res } function getPoint(node, x, y, allowNull, allowPercent) { x = getValue(node, x || "x", false, allowNull, allowPercent); y = getValue(node, y || "y", false, allowNull, allowPercent); return allowNull && (x == null || y == null) ? null : new Point(x, y) } function getSize(node, w, h, allowNull, allowPercent) { w = getValue(node, w || "width", false, allowNull, allowPercent); h = getValue(node, h || "height", false, allowNull, allowPercent); return allowNull && (w == null || h == null) ? null : new Size(w, h) } function convertValue(value, type, lookup) { return value === "none" ? null : type === "number" ? parseFloat(value) : type === "array" ? value ? value.split(/[\s,]+/g).map(parseFloat) : [] : type === "color" ? getDefinition(value) || value : type === "lookup" ? lookup[value] : value } function importGroup(node, type, options, isRoot) { var nodes = node.childNodes, isClip = type === "clippath", isDefs = type === "defs", item = new Group, project = item._project, currentStyle = project._currentStyle, children = []; if (!isClip && !isDefs) { item = applyAttributes(item, node, isRoot); project._currentStyle = item._style.clone() } if (isRoot) { var defs = node.querySelectorAll("defs"); for (var i = 0, l = defs.length; i < l; i++) { importNode(defs[i], options, false) } } for (var i = 0, l = nodes.length; i < l; i++) { var childNode = nodes[i], child; if (childNode.nodeType === 1 && !/^defs$/i.test(childNode.nodeName) && (child = importNode(childNode, options, false)) && !(child instanceof SymbolDefinition)) children.push(child) } item.addChildren(children); if (isClip) item = applyAttributes(item.reduce(), node, isRoot); project._currentStyle = currentStyle; if (isClip || isDefs) { item.remove(); item = null } return item } function importPoly(node, type) { var coords = node.getAttribute("points").match(/[+-]?(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?/g), points = []; for (var i = 0, l = coords.length; i < l; i += 2) points.push(new Point(parseFloat(coords[i]), parseFloat(coords[i + 1]))); var path = new Path(points); if (type === "polygon") path.closePath(); return path } function importPath(node) { return PathItem.create(node.getAttribute("d")) } function importGradient(node, type) { var id = (getValue(node, "href", true) || "").substring(1), radial = type === "radialgradient", gradient; if (id) { gradient = definitions[id].getGradient(); if (gradient._radial ^ radial) { gradient = gradient.clone(); gradient._radial = radial } } else { var nodes = node.childNodes, stops = []; for (var i = 0, l = nodes.length; i < l; i++) { var child = nodes[i]; if (child.nodeType === 1) stops.push(applyAttributes(new GradientStop, child)) } gradient = new Gradient(stops, radial) } var origin, destination, highlight, scaleToBounds = getValue(node, "gradientUnits", true) !== "userSpaceOnUse"; if (radial) { origin = getPoint(node, "cx", "cy", false, scaleToBounds); destination = origin.add(getValue(node, "r", false, false, scaleToBounds), 0); highlight = getPoint(node, "fx", "fy", true, scaleToBounds) } else { origin = getPoint(node, "x1", "y1", false, scaleToBounds); destination = getPoint(node, "x2", "y2", false, scaleToBounds) } var color = applyAttributes(new Color(gradient, origin, destination, highlight), node); color._scaleToBounds = scaleToBounds; return null } var importers = { "#document": function(node, type, options, isRoot) { var nodes = node.childNodes; for (var i = 0, l = nodes.length; i < l; i++) { var child = nodes[i]; if (child.nodeType === 1) return importNode(child, options, isRoot) } }, g: importGroup, svg: importGroup, clippath: importGroup, polygon: importPoly, polyline: importPoly, path: importPath, lineargradient: importGradient, radialgradient: importGradient, image: function(node) { var raster = new Raster(getValue(node, "href", true)); raster.on("load", function() { var size = getSize(node); this.setSize(size); var center = getPoint(node).add(size.divide(2)); this._matrix.append((new Matrix).translate(center)) }); return raster }, symbol: function(node, type, options, isRoot) { return new SymbolDefinition(importGroup(node, type, options, isRoot), true) }, defs: importGroup, use: function(node) { var id = (getValue(node, "href", true) || "").substring(1), definition = definitions[id], point = getPoint(node); return definition ? definition instanceof SymbolDefinition ? definition.place(point) : definition.clone().translate(point) : null }, circle: function(node) { return new Shape.Circle(getPoint(node, "cx", "cy"), getValue(node, "r")) }, ellipse: function(node) { return new Shape.Ellipse({ center: getPoint(node, "cx", "cy"), radius: getSize(node, "rx", "ry") }) }, rect: function(node) { return new Shape.Rectangle(new Rectangle(getPoint(node), getSize(node)), getSize(node, "rx", "ry")) }, line: function(node) { return new Path.Line(getPoint(node, "x1", "y1"), getPoint(node, "x2", "y2")) }, text: function(node) { var text = new PointText(getPoint(node).add(getPoint(node, "dx", "dy"))); text.setContent(node.textContent.trim() || ""); return text } }; function applyTransform(item, value, name, node) { if (item.transform) { var transforms = (node.getAttribute(name) || "").split(/\)\s*/g), matrix = new Matrix; for (var i = 0, l = transforms.length; i < l; i++) { var transform = transforms[i]; if (!transform) break; var parts = transform.split(/\(\s*/), command = parts[0], v = parts[1].split(/[\s,]+/g); for (var j = 0, m = v.length; j < m; j++) v[j] = parseFloat(v[j]); switch (command) { case "matrix": matrix.append(new Matrix(v[0], v[1], v[2], v[3], v[4], v[5])); break; case "rotate": matrix.rotate(v[0], v[1] || 0, v[2] || 0); break; case "translate": matrix.translate(v[0], v[1] || 0); break; case "scale": matrix.scale(v); break; case "skewX": matrix.skew(v[0], 0); break; case "skewY": matrix.skew(0, v[0]); break } } item.transform(matrix) } } function applyOpacity(item, value, name) { var key = name === "fill-opacity" ? "getFillColor" : "getStrokeColor", color = item[key] && item[key](); if (color) color.setAlpha(parseFloat(value)) } var attributes = Base.set(Base.each(SvgStyles, function(entry) { this[entry.attribute] = function(item, value) { if (item[entry.set]) { item[entry.set](convertValue(value, entry.type, entry.fromSVG)); if (entry.type === "color") { var color = item[entry.get](); if (color) { if (color._scaleToBounds) { var bounds = item.getBounds(); color.transform((new Matrix).translate(bounds.getPoint()).scale(bounds.getSize())) } } } } } }, {}), { id: function(item, value) { definitions[value] = item; if (item.setName) item.setName(value) }, "clip-path": function(item, value) { var clip = getDefinition(value); if (clip) { clip = clip.clone(); clip.setClipMask(true); if (item instanceof Group) { item.insertChild(0, clip) } else { return new Group(clip, item) } } }, gradientTransform: applyTransform, transform: applyTransform, "fill-opacity": applyOpacity, "stroke-opacity": applyOpacity, visibility: function(item, value) { if (item.setVisible) item.setVisible(value === "visible") }, display: function(item, value) { if (item.setVisible) item.setVisible(value !== null) }, "stop-color": function(item, value) { if (item.setColor) item.setColor(value) }, "stop-opacity": function(item, value) { if (item._color) item._color.setAlpha(parseFloat(value)) }, offset: function(item, value) { if (item.setOffset) { var percent = value.match(/(.*)%$/); item.setOffset(percent ? percent[1] / 100 : parseFloat(value)) } }, viewBox: function(item, value, name, node, styles) { var rect = new Rectangle(convertValue(value, "array")), size = getSize(node, null, null, true), group, matrix; if (item instanceof Group) { var scale = size ? size.divide(rect.getSize()) : 1, matrix = (new Matrix).scale(scale).translate(rect.getPoint().negate()); group = item } else if (item instanceof SymbolDefinition) { if (size) rect.setSize(size); group = item._item } if (group) { if (getAttribute(node, "overflow", styles) !== "visible") { var clip = new Shape.Rectangle(rect); clip.setClipMask(true); group.addChild(clip) } if (matrix) group.transform(matrix) } } }); function getAttribute(node, name, styles) { var attr = node.attributes[name], value = attr && attr.value; if (!value && node.style) { var style = Base.camelize(name); value = node.style[style]; if (!value && styles.node[style] !== styles.parent[style]) value = styles.node[style] } return !value ? undefined : value === "none" ? null : value } function applyAttributes(item, node, isRoot) { var parent = node.parentNode, styles = { node: DomElement.getStyles(node) || {}, parent: !isRoot && !/^defs$/i.test(parent.tagName) && DomElement.getStyles(parent) || {} }; Base.each(attributes, function(apply, name) { var value = getAttribute(node, name, styles); item = value !== undefined && apply(item, value, name, node, styles) || item }); return item } function getDefinition(value) { var match = value && value.match(/\((?:["'#]*)([^"')]+)/), name = match && match[1], res = name && definitions[window ? name.replace(window.location.href.split("#")[0] + "#", "") : name]; if (res && res._scaleToBounds) { res = res.clone(); res._scaleToBounds = true } return res } function importNode(node, options, isRoot) { var type = node.nodeName.toLowerCase(), isElement = type !== "#document", body = document.body, container, parent, next; if (isRoot && isElement) { rootSize = paper.getView().getSize(); rootSize = getSize(node, null, null, true) || rootSize; container = SvgElement.create("svg", { style: "stroke-width: 1px; stroke-miterlimit: 10" }); parent = node.parentNode; next = node.nextSibling; container.appendChild(node); body.appendChild(container) } var settings = paper.settings, applyMatrix = settings.applyMatrix, insertItems = settings.insertItems; settings.applyMatrix = false; settings.insertItems = false; var importer = importers[type], item = importer && importer(node, type, options, isRoot) || null; settings.insertItems = insertItems; settings.applyMatrix = applyMatrix; if (item) { if (isElement && !(item instanceof Group)) item = applyAttributes(item, node, isRoot); var onImport = options.onImport, data = isElement && node.getAttribute("data-paper-data"); if (onImport) item = onImport(node, item, options) || item; if (options.expandShapes && item instanceof Shape) { item.remove(); item = item.toPath() } if (data) item._data = JSON.parse(data) } if (container) { body.removeChild(container); if (parent) { if (next) { parent.insertBefore(node, next) } else { parent.appendChild(node) } } } if (isRoot) { definitions = {}; if (item && Base.pick(options.applyMatrix, applyMatrix)) item.matrix.apply(true, true) } return item } function importSVG(source, options, owner) { if (!source) return null; options = typeof options === "function" ? { onLoad: options } : options || {}; var scope = paper, item = null; function onLoad(svg) { try { var node = typeof svg === "object" ? svg : (new self.DOMParser).parseFromString(svg, "image/svg+xml"); if (!node.nodeName) { node = null; throw new Error("Unsupported SVG source: " + source) } paper = scope; item = importNode(node, options, true); if (!options || options.insert !== false) { owner._insertItem(undefined, item) } var onLoad = options.onLoad; if (onLoad) onLoad(item, svg) } catch (e) { onError(e) } } function onError(message, status) { var onError = options.onError; if (onError) { onError(message, status) } else { throw new Error(message) } } if (typeof source === "string" && !/^.*</.test(source)) { var node = document.getElementById(source); if (node) { onLoad(node) } else { Http.request({ url: source, async: true, onLoad: onLoad, onError: onError }) } } else if (typeof File !== "undefined" && source instanceof File) { var reader = new FileReader; reader.onload = function() { onLoad(reader.result) }; reader.onerror = function() { onError(reader.error) }; return reader.readAsText(source) } else { onLoad(source) } return item } Item.inject({ importSVG: function(node, options) { return importSVG(node, options, this) } }); Project.inject({ importSVG: function(node, options) { this.activate(); return importSVG(node, options, this) } }) }; Base.exports.PaperScript = function() { var global = this, acorn = global.acorn; if (!acorn && "function" !== "undefined") { try { acorn = __webpack_require__(1157) } catch (e) {} } if (!acorn) { var exports, module; acorn = exports = module = {}; (function(root, mod) { if (typeof exports == "object" && typeof module == "object") return mod(exports); if (true) return !(__WEBPACK_AMD_DEFINE_ARRAY__ = [exports], __WEBPACK_AMD_DEFINE_FACTORY__ = mod, __WEBPACK_AMD_DEFINE_RESULT__ = typeof __WEBPACK_AMD_DEFINE_FACTORY__ === "function" ? __WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__) : __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); mod(root.acorn || (root.acorn = {})) })(this, function(exports) { "use strict"; exports.version = "0.5.0"; var options, input, inputLen, sourceFile; exports.parse = function(inpt, opts) { input = String(inpt); inputLen = input.length; setOptions(opts); initTokenState(); return parseTopLevel(options.program) }; var defaultOptions = exports.defaultOptions = { ecmaVersion: 5, strictSemicolons: false, allowTrailingCommas: true, forbidReserved: false, allowReturnOutsideFunction: false, locations: false, onComment: null, ranges: false, program: null, sourceFile: null, directSourceFile: null }; function setOptions(opts) { options = opts || {}; for (var opt in defaultOptions) if (!Object.prototype.hasOwnProperty.call(options, opt)) options[opt] = defaultOptions[opt]; sourceFile = options.sourceFile || null } var getLineInfo = exports.getLineInfo = function(input, offset) { for (var line = 1, cur = 0;;) { lineBreak.lastIndex = cur; var match = lineBreak.exec(input); if (match && match.index < offset) { ++line; cur = match.index + match[0].length } else break } return { line: line, column: offset - cur } }; exports.tokenize = function(inpt, opts) { input = String(inpt); inputLen = input.length; setOptions(opts); initTokenState(); var t = {}; function getToken(forceRegexp) { lastEnd = tokEnd; readToken(forceRegexp); t.start = tokStart; t.end = tokEnd; t.startLoc = tokStartLoc; t.endLoc = tokEndLoc; t.type = tokType; t.value = tokVal; return t } getToken.jumpTo = function(pos, reAllowed) { tokPos = pos; if (options.locations) { tokCurLine = 1; tokLineStart = lineBreak.lastIndex = 0; var match; while ((match = lineBreak.exec(input)) && match.index < pos) { ++tokCurLine; tokLineStart = match.index + match[0].length } } tokRegexpAllowed = reAllowed; skipSpace() }; return getToken }; var tokPos; var tokStart, tokEnd; var tokStartLoc, tokEndLoc; var tokType, tokVal; var tokRegexpAllowed; var tokCurLine, tokLineStart; var lastStart, lastEnd, lastEndLoc; var inFunction, labels, strict; function raise(pos, message) { var loc = getLineInfo(input, pos); message += " (" + loc.line + ":" + loc.column + ")"; var err = new SyntaxError(message); err.pos = pos; err.loc = loc; err.raisedAt = tokPos; throw err } var empty = []; var _num = { type: "num" }, _regexp = { type: "regexp" }, _string = { type: "string" }; var _name = { type: "name" }, _eof = { type: "eof" }; var _break = { keyword: "break" }, _case = { keyword: "case", beforeExpr: true }, _catch = { keyword: "catch" }; var _continue = { keyword: "continue" }, _debugger = { keyword: "debugger" }, _default = { keyword: "default" }; var _do = { keyword: "do", isLoop: true }, _else = { keyword: "else", beforeExpr: true }; var _finally = { keyword: "finally" }, _for = { keyword: "for", isLoop: true }, _function = { keyword: "function" }; var _if = { keyword: "if" }, _return = { keyword: "return", beforeExpr: true }, _switch = { keyword: "switch" }; var _throw = { keyword: "throw", beforeExpr: true }, _try = { keyword: "try" }, _var = { keyword: "var" }; var _while = { keyword: "while", isLoop: true }, _with = { keyword: "with" }, _new = { keyword: "new", beforeExpr: true }; var _this = { keyword: "this" }; var _null = { keyword: "null", atomValue: null }, _true = { keyword: "true", atomValue: true }; var _false = { keyword: "false", atomValue: false }; var _in = { keyword: "in", binop: 7, beforeExpr: true }; var keywordTypes = { break: _break, case: _case, catch: _catch, continue: _continue, debugger: _debugger, default: _default, do: _do, else: _else, finally: _finally, for: _for, function: _function, if: _if, return: _return, switch: _switch, throw: _throw, try: _try, var: _var, while: _while, with: _with, null: _null, true: _true, false: _false, new: _new, in: _in, instanceof: { keyword: "instanceof", binop: 7, beforeExpr: true }, this: _this, typeof: { keyword: "typeof", prefix: true, beforeExpr: true }, void: { keyword: "void", prefix: true, beforeExpr: true }, delete: { keyword: "delete", prefix: true, beforeExpr: true } }; var _bracketL = { type: "[", beforeExpr: true }, _bracketR = { type: "]" }, _braceL = { type: "{", beforeExpr: true }; var _braceR = { type: "}" }, _parenL = { type: "(", beforeExpr: true }, _parenR = { type: ")" }; var _comma = { type: ",", beforeExpr: true }, _semi = { type: ";", beforeExpr: true }; var _colon = { type: ":", beforeExpr: true }, _dot = { type: "." }, _question = { type: "?", beforeExpr: true }; var _slash = { binop: 10, beforeExpr: true }, _eq = { isAssign: true, beforeExpr: true }; var _assign = { isAssign: true, beforeExpr: true }; var _incDec = { postfix: true, prefix: true, isUpdate: true }, _prefix = { prefix: true, beforeExpr: true }; var _logicalOR = { binop: 1, beforeExpr: true }; var _logicalAND = { binop: 2, beforeExpr: true }; var _bitwiseOR = { binop: 3, beforeExpr: true }; var _bitwiseXOR = { binop: 4, beforeExpr: true }; var _bitwiseAND = { binop: 5, beforeExpr: true }; var _equality = { binop: 6, beforeExpr: true }; var _relational = { binop: 7, beforeExpr: true }; var _bitShift = { binop: 8, beforeExpr: true }; var _plusMin = { binop: 9, prefix: true, beforeExpr: true }; var _multiplyModulo = { binop: 10, beforeExpr: true }; exports.tokTypes = { bracketL: _bracketL, bracketR: _bracketR, braceL: _braceL, braceR: _braceR, parenL: _parenL, parenR: _parenR, comma: _comma, semi: _semi, colon: _colon, dot: _dot, question: _question, slash: _slash, eq: _eq, name: _name, eof: _eof, num: _num, regexp: _regexp, string: _string }; for (var kw in keywordTypes) exports.tokTypes["_" + kw] = keywordTypes[kw]; function makePredicate(words) { words = words.split(" "); var f = "", cats = []; out: for (var i = 0; i < words.length; ++i) { for (var j = 0; j < cats.length; ++j) if (cats[j][0].length == words[i].length) { cats[j].push(words[i]); continue out } cats.push([words[i]]) } function compareTo(arr) { if (arr.length == 1) return f += "return str === " + JSON.stringify(arr[0]) + ";"; f += "switch(str){"; for (var i = 0; i < arr.length; ++i) f += "case " + JSON.stringify(arr[i]) + ":"; f += "return true}return false;" } if (cats.length > 3) { cats.sort(function(a, b) { return b.length - a.length }); f += "switch(str.length){"; for (var i = 0; i < cats.length; ++i) { var cat = cats[i]; f += "case " + cat[0].length + ":"; compareTo(cat) } f += "}" } else { compareTo(words) } return new Function("str", f) } var isReservedWord3 = makePredicate("abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile"); var isReservedWord5 = makePredicate("class enum extends super const export import"); var isStrictReservedWord = makePredicate("implements interface let package private protected public static yield"); var isStrictBadIdWord = makePredicate("eval arguments"); var isKeyword = makePredicate("break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this"); var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/; var nonASCIIidentifierStartChars = "ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԧԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠࢢ-ࢬऄ-हऽॐक़-ॡॱ-ॷॹ-ॿঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-ళవ-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤜᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々-〇〡-〩〱-〵〸-〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚗꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꪀ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ"; var nonASCIIidentifierChars = "̀-ͯ҃-֑҇-ׇֽֿׁׂׅׄؐ-ؚؠ-ىٲ-ۓۧ-ۨۻ-ۼܰ-݊ࠀ-ࠔࠛ-ࠣࠥ-ࠧࠩ-࠭ࡀ-ࡗࣤ-ࣾऀ-ःऺ-़ा-ॏ॑-ॗॢ-ॣ०-९ঁ-ঃ়া-ৄেৈৗয়-ৠਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢ-ૣ૦-૯ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୟ-ୠ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఁ-ఃె-ైొ-్ౕౖౢ-ౣ౦-౯ಂಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢ-ೣ೦-೯ംഃെ-ൈൗൢ-ൣ൦-൯ංඃ්ා-ුූෘ-ෟෲෳิ-ฺเ-ๅ๐-๙ິ-ູ່-ໍ໐-໙༘༙༠-༩༹༵༷ཁ-ཇཱ-྄྆-྇ྍ-ྗྙ-ྼ࿆က-ဩ၀-၉ၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟ᜎ-ᜐᜠ-ᜰᝀ-ᝐᝲᝳក-ឲ៝០-៩᠋-᠍᠐-᠙ᤠ-ᤫᤰ-᤻ᥑ-ᥭᦰ-ᧀᧈ-ᧉ᧐-᧙ᨀ-ᨕᨠ-ᩓ᩠-᩿᩼-᪉᪐-᪙ᭆ-ᭋ᭐-᭙᭫-᭳᮰-᮹᯦-᯳ᰀ-ᰢ᱀-᱉ᱛ-ᱽ᳐-᳒ᴀ-ᶾḁ-ἕ‿⁀⁔⃐-⃥⃜⃡-⃰ⶁ-ⶖⷠ-ⷿ〡-〨゙゚Ꙁ-ꙭꙴ-꙽ꚟ꛰-꛱ꟸ-ꠀ꠆ꠋꠣ-ꠧꢀ-ꢁꢴ-꣄꣐-꣙ꣳ-ꣷ꤀-꤉ꤦ-꤭ꤰ-ꥅꦀ-ꦃ꦳-꧀ꨀ-ꨧꩀ-ꩁꩌ-ꩍ꩐-꩙ꩻꫠ-ꫩꫲ-ꫳꯀ-ꯡ꯬꯭꯰-꯹ﬠ-ﬨ︀-️︠-︦︳︴﹍-﹏0-9_"; var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); var newline = /[\n\r\u2028\u2029]/; var lineBreak = /\r\n|[\n\r\u2028\u2029]/g; var isIdentifierStart = exports.isIdentifierStart = function(code) { if (code < 65) return code === 36; if (code < 91) return true; if (code < 97) return code === 95; if (code < 123) return true; return code >= 170 && nonASCIIidentifierStart.test(String.fromCharCode(code)) }; var isIdentifierChar = exports.isIdentifierChar = function(code) { if (code < 48) return code === 36; if (code < 58) return true; if (code < 65) return false; if (code < 91) return true; if (code < 97) return code === 95; if (code < 123) return true; return code >= 170 && nonASCIIidentifier.test(String.fromCharCode(code)) }; function line_loc_t() { this.line = tokCurLine; this.column = tokPos - tokLineStart } function initTokenState() { tokCurLine = 1; tokPos = tokLineStart = 0; tokRegexpAllowed = true; skipSpace() } function finishToken(type, val) { tokEnd = tokPos; if (options.locations) tokEndLoc = new line_loc_t; tokType = type; skipSpace(); tokVal = val; tokRegexpAllowed = type.beforeExpr } function skipBlockComment() { var startLoc = options.onComment && options.locations && new line_loc_t; var start = tokPos, end = input.indexOf("*/", tokPos += 2); if (end === -1) raise(tokPos - 2, "Unterminated comment"); tokPos = end + 2; if (options.locations) { lineBreak.lastIndex = start; var match; while ((match = lineBreak.exec(input)) && match.index < tokPos) { ++tokCurLine; tokLineStart = match.index + match[0].length } } if (options.onComment) options.onComment(true, input.slice(start + 2, end), start, tokPos, startLoc, options.locations && new line_loc_t) } function skipLineComment() { var start = tokPos; var startLoc = options.onComment && options.locations && new line_loc_t; var ch = input.charCodeAt(tokPos += 2); while (tokPos < inputLen && ch !== 10 && ch !== 13 && ch !== 8232 && ch !== 8233) { ++tokPos; ch = input.charCodeAt(tokPos) } if (options.onComment) options.onComment(false, input.slice(start + 2, tokPos), start, tokPos, startLoc, options.locations && new line_loc_t) } function skipSpace() { while (tokPos < inputLen) { var ch = input.charCodeAt(tokPos); if (ch === 32) { ++tokPos } else if (ch === 13) { ++tokPos; var next = input.charCodeAt(tokPos); if (next === 10) { ++tokPos } if (options.locations) { ++tokCurLine; tokLineStart = tokPos } } else if (ch === 10 || ch === 8232 || ch === 8233) { ++tokPos; if (options.locations) { ++tokCurLine; tokLineStart = tokPos } } else if (ch > 8 && ch < 14) { ++tokPos } else if (ch === 47) { var next = input.charCodeAt(tokPos + 1); if (next === 42) { skipBlockComment() } else if (next === 47) { skipLineComment() } else break } else if (ch === 160) { ++tokPos } else if (ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) { ++tokPos } else { break } } } function readToken_dot() { var next = input.charCodeAt(tokPos + 1); if (next >= 48 && next <= 57) return readNumber(true); ++tokPos; return finishToken(_dot) } function readToken_slash() { var next = input.charCodeAt(tokPos + 1); if (tokRegexpAllowed) { ++tokPos; return readRegexp() } if (next === 61) return finishOp(_assign, 2); return finishOp(_slash, 1) } function readToken_mult_modulo() { var next = input.charCodeAt(tokPos + 1); if (next === 61) return finishOp(_assign, 2); return finishOp(_multiplyModulo, 1) } function readToken_pipe_amp(code) { var next = input.charCodeAt(tokPos + 1); if (next === code) return finishOp(code === 124 ? _logicalOR : _logicalAND, 2); if (next === 61) return finishOp(_assign, 2); return finishOp(code === 124 ? _bitwiseOR : _bitwiseAND, 1) } function readToken_caret() { var next = input.charCodeAt(tokPos + 1); if (next === 61) return finishOp(_assign, 2); return finishOp(_bitwiseXOR, 1) } function readToken_plus_min(code) { var next = input.charCodeAt(tokPos + 1); if (next === code) { if (next == 45 && input.charCodeAt(tokPos + 2) == 62 && newline.test(input.slice(lastEnd, tokPos))) { tokPos += 3; skipLineComment(); skipSpace(); return readToken() } return finishOp(_incDec, 2) } if (next === 61) return finishOp(_assign, 2); return finishOp(_plusMin, 1) } function readToken_lt_gt(code) { var next = input.charCodeAt(tokPos + 1); var size = 1; if (next === code) { size = code === 62 && input.charCodeAt(tokPos + 2) === 62 ? 3 : 2; if (input.charCodeAt(tokPos + size) === 61) return finishOp(_assign, size + 1); return finishOp(_bitShift, size) } if (next == 33 && code == 60 && input.charCodeAt(tokPos + 2) == 45 && input.charCodeAt(tokPos + 3) == 45) { tokPos += 4; skipLineComment(); skipSpace(); return readToken() } if (next === 61) size = input.charCodeAt(tokPos + 2) === 61 ? 3 : 2; return finishOp(_relational, size) } function readToken_eq_excl(code) { var next = input.charCodeAt(tokPos + 1); if (next === 61) return finishOp(_equality, input.charCodeAt(tokPos + 2) === 61 ? 3 : 2); return finishOp(code === 61 ? _eq : _prefix, 1) } function getTokenFromCode(code) { switch (code) { case 46: return readToken_dot(); case 40: ++tokPos; return finishToken(_parenL); case 41: ++tokPos; return finishToken(_parenR); case 59: ++tokPos; return finishToken(_semi); case 44: ++tokPos; return finishToken(_comma); case 91: ++tokPos; return finishToken(_bracketL); case 93: ++tokPos; return finishToken(_bracketR); case 123: ++tokPos; return finishToken(_braceL); case 125: ++tokPos; return finishToken(_braceR); case 58: ++tokPos; return finishToken(_colon); case 63: ++tokPos; return finishToken(_question); case 48: var next = input.charCodeAt(tokPos + 1); if (next === 120 || next === 88) return readHexNumber(); case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: return readNumber(false); case 34: case 39: return readString(code); case 47: return readToken_slash(code); case 37: case 42: return readToken_mult_modulo(); case 124: case 38: return readToken_pipe_amp(code); case 94: return readToken_caret(); case 43: case 45: return readToken_plus_min(code); case 60: case 62: return readToken_lt_gt(code); case 61: case 33: return readToken_eq_excl(code); case 126: return finishOp(_prefix, 1) } return false } function readToken(forceRegexp) { if (!forceRegexp) tokStart = tokPos; else tokPos = tokStart + 1; if (options.locations) tokStartLoc = new line_loc_t; if (forceRegexp) return readRegexp(); if (tokPos >= inputLen) return finishToken(_eof); var code = input.charCodeAt(tokPos); if (isIdentifierStart(code) || code === 92) return readWord(); var tok = getTokenFromCode(code); if (tok === false) { var ch = String.fromCharCode(code); if (ch === "\\" || nonASCIIidentifierStart.test(ch)) return readWord(); raise(tokPos, "Unexpected character '" + ch + "'") } return tok } function finishOp(type, size) { var str = input.slice(tokPos, tokPos + size); tokPos += size; finishToken(type, str) } function readRegexp() { var content = "", escaped, inClass, start = tokPos; for (;;) { if (tokPos >= inputLen) raise(start, "Unterminated regular expression"); var ch = input.charAt(tokPos); if (newline.test(ch)) raise(start, "Unterminated regular expression"); if (!escaped) { if (ch === "[") inClass = true; else if (ch === "]" && inClass) inClass = false; else if (ch === "/" && !inClass) break; escaped = ch === "\\" } else escaped = false; ++tokPos } var content = input.slice(start, tokPos); ++tokPos; var mods = readWord1(); if (mods && !/^[gmsiy]*$/.test(mods)) raise(start, "Invalid regexp flag"); try { var value = new RegExp(content, mods) } catch (e) { if (e instanceof SyntaxError) raise(start, e.message); raise(e) } return finishToken(_regexp, value) } function readInt(radix, len) { var start = tokPos, total = 0; for (var i = 0, e = len == null ? Infinity : len; i < e; ++i) { var code = input.charCodeAt(tokPos), val; if (code >= 97) val = code - 97 + 10; else if (code >= 65) val = code - 65 + 10; else if (code >= 48 && code <= 57) val = code - 48; else val = Infinity; if (val >= radix) break; ++tokPos; total = total * radix + val } if (tokPos === start || len != null && tokPos - start !== len) return null; return total } function readHexNumber() { tokPos += 2; var val = readInt(16); if (val == null) raise(tokStart + 2, "Expected hexadecimal number"); if (isIdentifierStart(input.charCodeAt(tokPos))) raise(tokPos, "Identifier directly after number"); return finishToken(_num, val) } function readNumber(startsWithDot) { var start = tokPos, isFloat = false, octal = input.charCodeAt(tokPos) === 48; if (!startsWithDot && readInt(10) === null) raise(start, "Invalid number"); if (input.charCodeAt(tokPos) === 46) { ++tokPos; readInt(10); isFloat = true } var next = input.charCodeAt(tokPos); if (next === 69 || next === 101) { next = input.charCodeAt(++tokPos); if (next === 43 || next === 45) ++tokPos; if (readInt(10) === null) raise(start, "Invalid number"); isFloat = true } if (isIdentifierStart(input.charCodeAt(tokPos))) raise(tokPos, "Identifier directly after number"); var str = input.slice(start, tokPos), val; if (isFloat) val = parseFloat(str); else if (!octal || str.length === 1) val = parseInt(str, 10); else if (/[89]/.test(str) || strict) raise(start, "Invalid number"); else val = parseInt(str, 8); return finishToken(_num, val) } function readString(quote) { tokPos++; var out = ""; for (;;) { if (tokPos >= inputLen) raise(tokStart, "Unterminated string constant"); var ch = input.charCodeAt(tokPos); if (ch === quote) { ++tokPos; return finishToken(_string, out) } if (ch === 92) { ch = input.charCodeAt(++tokPos); var octal = /^[0-7]+/.exec(input.slice(tokPos, tokPos + 3)); if (octal) octal = octal[0]; while (octal && parseInt(octal, 8) > 255) octal = octal.slice(0, -1); if (octal === "0") octal = null; ++tokPos; if (octal) { if (strict) raise(tokPos - 2, "Octal literal in strict mode"); out += String.fromCharCode(parseInt(octal, 8)); tokPos += octal.length - 1 } else { switch (ch) { case 110: out += "\n"; break; case 114: out += "\r"; break; case 120: out += String.fromCharCode(readHexChar(2)); break; case 117: out += String.fromCharCode(readHexChar(4)); break; case 85: out += String.fromCharCode(readHexChar(8)); break; case 116: out += "\t"; break; case 98: out += "\b"; break; case 118: out += "\v"; break; case 102: out += "\f"; break; case 48: out += "\0"; break; case 13: if (input.charCodeAt(tokPos) === 10) ++tokPos; case 10: if (options.locations) { tokLineStart = tokPos; ++tokCurLine } break; default: out += String.fromCharCode(ch); break } } } else { if (ch === 13 || ch === 10 || ch === 8232 || ch === 8233) raise(tokStart, "Unterminated string constant"); out += String.fromCharCode(ch); ++tokPos } } } function readHexChar(len) { var n = readInt(16, len); if (n === null) raise(tokStart, "Bad character escape sequence"); return n } var containsEsc; function readWord1() { containsEsc = false; var word, first = true, start = tokPos; for (;;) { var ch = input.charCodeAt(tokPos); if (isIdentifierChar(ch)) { if (containsEsc) word += input.charAt(tokPos); ++tokPos } else if (ch === 92) { if (!containsEsc) word = input.slice(start, tokPos); containsEsc = true; if (input.charCodeAt(++tokPos) != 117) raise(tokPos, "Expecting Unicode escape sequence \\uXXXX"); ++tokPos; var esc = readHexChar(4); var escStr = String.fromCharCode(esc); if (!escStr) raise(tokPos - 1, "Invalid Unicode escape"); if (!(first ? isIdentifierStart(esc) : isIdentifierChar(esc))) raise(tokPos - 4, "Invalid Unicode escape"); word += escStr } else { break } first = false } return containsEsc ? word : input.slice(start, tokPos) } function readWord() { var word = readWord1(); var type = _name; if (!containsEsc && isKeyword(word)) type = keywordTypes[word]; return finishToken(type, word) } function next() { lastStart = tokStart; lastEnd = tokEnd; lastEndLoc = tokEndLoc; readToken() } function setStrict(strct) { strict = strct; tokPos = tokStart; if (options.locations) { while (tokPos < tokLineStart) { tokLineStart = input.lastIndexOf("\n", tokLineStart - 2) + 1; --tokCurLine } } skipSpace(); readToken() } function node_t() { this.type = null; this.start = tokStart; this.end = null } function node_loc_t() { this.start = tokStartLoc; this.end = null; if (sourceFile !== null) this.source = sourceFile } function startNode() { var node = new node_t; if (options.locations) node.loc = new node_loc_t; if (options.directSourceFile) node.sourceFile = options.directSourceFile; if (options.ranges) node.range = [tokStart, 0]; return node } function startNodeFrom(other) { var node = new node_t; node.start = other.start; if (options.locations) { node.loc = new node_loc_t; node.loc.start = other.loc.start } if (options.ranges) node.range = [other.range[0], 0]; return node } function finishNode(node, type) { node.type = type; node.end = lastEnd; if (options.locations) node.loc.end = lastEndLoc; if (options.ranges) node.range[1] = lastEnd; return node } function isUseStrict(stmt) { return options.ecmaVersion >= 5 && stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && stmt.expression.value === "use strict" } function eat(type) { if (tokType === type) { next(); return true } } function canInsertSemicolon() { return !options.strictSemicolons && (tokType === _eof || tokType === _braceR || newline.test(input.slice(lastEnd, tokStart))) } function semicolon() { if (!eat(_semi) && !canInsertSemicolon()) unexpected() } function expect(type) { if (tokType === type) next(); else unexpected() } function unexpected() { raise(tokStart, "Unexpected token") } function checkLVal(expr) { if (expr.type !== "Identifier" && expr.type !== "MemberExpression") raise(expr.start, "Assigning to rvalue"); if (strict && expr.type === "Identifier" && isStrictBadIdWord(expr.name)) raise(expr.start, "Assigning to " + expr.name + " in strict mode") } function parseTopLevel(program) { lastStart = lastEnd = tokPos; if (options.locations) lastEndLoc = new line_loc_t; inFunction = strict = null; labels = []; readToken(); var node = program || startNode(), first = true; if (!program) node.body = []; while (tokType !== _eof) { var stmt = parseStatement(); node.body.push(stmt); if (first && isUseStrict(stmt)) setStrict(true); first = false } return finishNode(node, "Program") } var loopLabel = { kind: "loop" }, switchLabel = { kind: "switch" }; function parseStatement() { if (tokType === _slash || tokType === _assign && tokVal == "/=") readToken(true); var starttype = tokType, node = startNode(); switch (starttype) { case _break: case _continue: next(); var isBreak = starttype === _break; if (eat(_semi) || canInsertSemicolon()) node.label = null; else if (tokType !== _name) unexpected(); else { node.label = parseIdent(); semicolon() } for (var i = 0; i < labels.length; ++i) { var lab = labels[i]; if (node.label == null || lab.name === node.label.name) { if (lab.kind != null && (isBreak || lab.kind === "loop")) break; if (node.label && isBreak) break } } if (i === labels.length) raise(node.start, "Unsyntactic " + starttype.keyword); return finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement"); case _debugger: next(); semicolon(); return finishNode(node, "DebuggerStatement"); case _do: next(); labels.push(loopLabel); node.body = parseStatement(); labels.pop(); expect(_while); node.test = parseParenExpression(); semicolon(); return finishNode(node, "DoWhileStatement"); case _for: next(); labels.push(loopLabel); expect(_parenL); if (tokType === _semi) return parseFor(node, null); if (tokType === _var) { var init = startNode(); next(); parseVar(init, true); finishNode(init, "VariableDeclaration"); if (init.declarations.length === 1 && eat(_in)) return parseForIn(node, init); return parseFor(node, init) } var init = parseExpression(false, true); if (eat(_in)) { checkLVal(init); return parseForIn(node, init) } return parseFor(node, init); case _function: next(); return parseFunction(node, true); case _if: next(); node.test = parseParenExpression(); node.consequent = parseStatement(); node.alternate = eat(_else) ? parseStatement() : null; return finishNode(node, "IfStatement"); case _return: if (!inFunction && !options.allowReturnOutsideFunction) raise(tokStart, "'return' outside of function"); next(); if (eat(_semi) || canInsertSemicolon()) node.argument = null; else { node.argument = parseExpression(); semicolon() } return finishNode(node, "ReturnStatement"); case _switch: next(); node.discriminant = parseParenExpression(); node.cases = []; expect(_braceL); labels.push(switchLabel); for (var cur, sawDefault; tokType != _braceR;) { if (tokType === _case || tokType === _default) { var isCase = tokType === _case; if (cur) finishNode(cur, "SwitchCase"); node.cases.push(cur = startNode()); cur.consequent = []; next(); if (isCase) cur.test = parseExpression(); else { if (sawDefault) raise(lastStart, "Multiple default clauses"); sawDefault = true; cur.test = null } expect(_colon) } else { if (!cur) unexpected(); cur.consequent.push(parseStatement()) } } if (cur) finishNode(cur, "SwitchCase"); next(); labels.pop(); return finishNode(node, "SwitchStatement"); case _throw: next(); if (newline.test(input.slice(lastEnd, tokStart))) raise(lastEnd, "Illegal newline after throw"); node.argument = parseExpression(); semicolon(); return finishNode(node, "ThrowStatement"); case _try: next(); node.block = parseBlock(); node.handler = null; if (tokType === _catch) { var clause = startNode(); next(); expect(_parenL); clause.param = parseIdent(); if (strict && isStrictBadIdWord(clause.param.name)) raise(clause.param.start, "Binding " + clause.param.name + " in strict mode"); expect(_parenR); clause.guard = null; clause.body = parseBlock(); node.handler = finishNode(clause, "CatchClause") } node.guardedHandlers = empty; node.finalizer = eat(_finally) ? parseBlock() : null; if (!node.handler && !node.finalizer) raise(node.start, "Missing catch or finally clause"); return finishNode(node, "TryStatement"); case _var: next(); parseVar(node); semicolon(); return finishNode(node, "VariableDeclaration"); case _while: next(); node.test = parseParenExpression(); labels.push(loopLabel); node.body = parseStatement(); labels.pop(); return finishNode(node, "WhileStatement"); case _with: if (strict) raise(tokStart, "'with' in strict mode"); next(); node.object = parseParenExpression(); node.body = parseStatement(); return finishNode(node, "WithStatement"); case _braceL: return parseBlock(); case _semi: next(); return finishNode(node, "EmptyStatement"); default: var maybeName = tokVal, expr = parseExpression(); if (starttype === _name && expr.type === "Identifier" && eat(_colon)) { for (var i = 0; i < labels.length; ++i) if (labels[i].name === maybeName) raise(expr.start, "Label '" + maybeName + "' is already declared"); var kind = tokType.isLoop ? "loop" : tokType === _switch ? "switch" : null; labels.push({ name: maybeName, kind: kind }); node.body = parseStatement(); labels.pop(); node.label = expr; return finishNode(node, "LabeledStatement") } else { node.expression = expr; semicolon(); return finishNode(node, "ExpressionStatement") } } } function parseParenExpression() { expect(_parenL); var val = parseExpression(); expect(_parenR); return val } function parseBlock(allowStrict) { var node = startNode(), first = true, strict = false, oldStrict; node.body = []; expect(_braceL); while (!eat(_braceR)) { var stmt = parseStatement(); node.body.push(stmt); if (first && allowStrict && isUseStrict(stmt)) { oldStrict = strict; setStrict(strict = true) } first = false } if (strict && !oldStrict) setStrict(false); return finishNode(node, "BlockStatement") } function parseFor(node, init) { node.init = init; expect(_semi); node.test = tokType === _semi ? null : parseExpression(); expect(_semi); node.update = tokType === _parenR ? null : parseExpression(); expect(_parenR); node.body = parseStatement(); labels.pop(); return finishNode(node, "ForStatement") } function parseForIn(node, init) { node.left = init; node.right = parseExpression(); expect(_parenR); node.body = parseStatement(); labels.pop(); return finishNode(node, "ForInStatement") } function parseVar(node, noIn) { node.declarations = []; node.kind = "var"; for (;;) { var decl = startNode(); decl.id = parseIdent(); if (strict && isStrictBadIdWord(decl.id.name)) raise(decl.id.start, "Binding " + decl.id.name + " in strict mode"); decl.init = eat(_eq) ? parseExpression(true, noIn) : null; node.declarations.push(finishNode(decl, "VariableDeclarator")); if (!eat(_comma)) break } return node } function parseExpression(noComma, noIn) { var expr = parseMaybeAssign(noIn); if (!noComma && tokType === _comma) { var node = startNodeFrom(expr); node.expressions = [expr]; while (eat(_comma)) node.expressions.push(parseMaybeAssign(noIn)); return finishNode(node, "SequenceExpression") } return expr } function parseMaybeAssign(noIn) { var left = parseMaybeConditional(noIn); if (tokType.isAssign) { var node = startNodeFrom(left); node.operator = tokVal; node.left = left; next(); node.right = parseMaybeAssign(noIn); checkLVal(left); return finishNode(node, "AssignmentExpression") } return left } function parseMaybeConditional(noIn) { var expr = parseExprOps(noIn); if (eat(_question)) { var node = startNodeFrom(expr); node.test = expr; node.consequent = parseExpression(true); expect(_colon); node.alternate = parseExpression(true, noIn); return finishNode(node, "ConditionalExpression") } return expr } function parseExprOps(noIn) { return parseExprOp(parseMaybeUnary(), -1, noIn) } function parseExprOp(left, minPrec, noIn) { var prec = tokType.binop; if (prec != null && (!noIn || tokType !== _in)) { if (prec > minPrec) { var node = startNodeFrom(left); node.left = left; node.operator = tokVal; var op = tokType; next(); node.right = parseExprOp(parseMaybeUnary(), prec, noIn); var exprNode = finishNode(node, op === _logicalOR || op === _logicalAND ? "LogicalExpression" : "BinaryExpression"); return parseExprOp(exprNode, minPrec, noIn) } } return left } function parseMaybeUnary() { if (tokType.prefix) { var node = startNode(), update = tokType.isUpdate; node.operator = tokVal; node.prefix = true; tokRegexpAllowed = true; next(); node.argument = parseMaybeUnary(); if (update) checkLVal(node.argument); else if (strict && node.operator === "delete" && node.argument.type === "Identifier") raise(node.start, "Deleting local variable in strict mode"); return finishNode(node, update ? "UpdateExpression" : "UnaryExpression") } var expr = parseExprSubscripts(); while (tokType.postfix && !canInsertSemicolon()) { var node = startNodeFrom(expr); node.operator = tokVal; node.prefix = false; node.argument = expr; checkLVal(expr); next(); expr = finishNode(node, "UpdateExpression") } return expr } function parseExprSubscripts() { return parseSubscripts(parseExprAtom()) } function parseSubscripts(base, noCalls) { if (eat(_dot)) { var node = startNodeFrom(base); node.object = base; node.property = parseIdent(true); node.computed = false; return parseSubscripts(finishNode(node, "MemberExpression"), noCalls) } else if (eat(_bracketL)) { var node = startNodeFrom(base); node.object = base; node.property = parseExpression(); node.computed = true; expect(_bracketR); return parseSubscripts(finishNode(node, "MemberExpression"), noCalls) } else if (!noCalls && eat(_parenL)) { var node = startNodeFrom(base); node.callee = base; node.arguments = parseExprList(_parenR, false); return parseSubscripts(finishNode(node, "CallExpression"), noCalls) } else return base } function parseExprAtom() { switch (tokType) { case _this: var node = startNode(); next(); return finishNode(node, "ThisExpression"); case _name: return parseIdent(); case _num: case _string: case _regexp: var node = startNode(); node.value = tokVal; node.raw = input.slice(tokStart, tokEnd); next(); return finishNode(node, "Literal"); case _null: case _true: case _false: var node = startNode(); node.value = tokType.atomValue; node.raw = tokType.keyword; next(); return finishNode(node, "Literal"); case _parenL: var tokStartLoc1 = tokStartLoc, tokStart1 = tokStart; next(); var val = parseExpression(); val.start = tokStart1; val.end = tokEnd; if (options.locations) { val.loc.start = tokStartLoc1; val.loc.end = tokEndLoc } if (options.ranges) val.range = [tokStart1, tokEnd]; expect(_parenR); return val; case _bracketL: var node = startNode(); next(); node.elements = parseExprList(_bracketR, true, true); return finishNode(node, "ArrayExpression"); case _braceL: return parseObj(); case _function: var node = startNode(); next(); return parseFunction(node, false); case _new: return parseNew(); default: unexpected() } } function parseNew() { var node = startNode(); next(); node.callee = parseSubscripts(parseExprAtom(), true); if (eat(_parenL)) node.arguments = parseExprList(_parenR, false); else node.arguments = empty; return finishNode(node, "NewExpression") } function parseObj() { var node = startNode(), first = true, sawGetSet = false; node.properties = []; next(); while (!eat(_braceR)) { if (!first) { expect(_comma); if (options.allowTrailingCommas && eat(_braceR)) break } else first = false; var prop = { key: parsePropertyName() }, isGetSet = false, kind; if (eat(_colon)) { prop.value = parseExpression(true); kind = prop.kind = "init" } else if (options.ecmaVersion >= 5 && prop.key.type === "Identifier" && (prop.key.name === "get" || prop.key.name === "set")) { isGetSet = sawGetSet = true; kind = prop.kind = prop.key.name; prop.key = parsePropertyName(); if (tokType !== _parenL) unexpected(); prop.value = parseFunction(startNode(), false) } else unexpected(); if (prop.key.type === "Identifier" && (strict || sawGetSet)) { for (var i = 0; i < node.properties.length; ++i) { var other = node.properties[i]; if (other.key.name === prop.key.name) { var conflict = kind == other.kind || isGetSet && other.kind === "init" || kind === "init" && (other.kind === "get" || other.kind === "set"); if (conflict && !strict && kind === "init" && other.kind === "init") conflict = false; if (conflict) raise(prop.key.start, "Redefinition of property") } } } node.properties.push(prop) } return finishNode(node, "ObjectExpression") } function parsePropertyName() { if (tokType === _num || tokType === _string) return parseExprAtom(); return parseIdent(true) } function parseFunction(node, isStatement) { if (tokType === _name) node.id = parseIdent(); else if (isStatement) unexpected(); else node.id = null; node.params = []; var first = true; expect(_parenL); while (!eat(_parenR)) { if (!first) expect(_comma); else first = false; node.params.push(parseIdent()) } var oldInFunc = inFunction, oldLabels = labels; inFunction = true; labels = []; node.body = parseBlock(true); inFunction = oldInFunc; labels = oldLabels; if (strict || node.body.body.length && isUseStrict(node.body.body[0])) { for (var i = node.id ? -1 : 0; i < node.params.length; ++i) { var id = i < 0 ? node.id : node.params[i]; if (isStrictReservedWord(id.name) || isStrictBadIdWord(id.name)) raise(id.start, "Defining '" + id.name + "' in strict mode"); if (i >= 0) for (var j = 0; j < i; ++j) if (id.name === node.params[j].name) raise(id.start, "Argument name clash in strict mode") } } return finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression") } function parseExprList(close, allowTrailingComma, allowEmpty) { var elts = [], first = true; while (!eat(close)) { if (!first) { expect(_comma); if (allowTrailingComma && options.allowTrailingCommas && eat(close)) break } else first = false; if (allowEmpty && tokType === _comma) elts.push(null); else elts.push(parseExpression(true)) } return elts } function parseIdent(liberal) { var node = startNode(); if (liberal && options.forbidReserved == "everywhere") liberal = false; if (tokType === _name) { if (!liberal && (options.forbidReserved && (options.ecmaVersion === 3 ? isReservedWord3 : isReservedWord5)(tokVal) || strict && isStrictReservedWord(tokVal)) && input.slice(tokStart, tokEnd).indexOf("\\") == -1) raise(tokStart, "The keyword '" + tokVal + "' is reserved"); node.name = tokVal } else if (liberal && tokType.keyword) { node.name = tokType.keyword } else { unexpected() } tokRegexpAllowed = false; next(); return finishNode(node, "Identifier") } }); if (!acorn.version) acorn = null } function parse(code, options) { return (global.acorn || acorn).parse(code, options) } var binaryOperators = { "+": "__add", "-": "__subtract", "*": "__multiply", "/": "__divide", "%": "__modulo", "==": "__equals", "!=": "__equals" }; var unaryOperators = { "-": "__negate", "+": "__self" }; var fields = Base.each(["add", "subtract", "multiply", "divide", "modulo", "equals", "negate"], function(name) { this["__" + name] = "#" + name }, { __self: function() { return this } }); Point.inject(fields); Size.inject(fields); Color.inject(fields); function __$__(left, operator, right) { var handler = binaryOperators[operator]; if (left && left[handler]) { var res = left[handler](right); return operator === "!=" ? !res : res } switch (operator) { case "+": return left + right; case "-": return left - right; case "*": return left * right; case "/": return left / right; case "%": return left % right; case "==": return left == right; case "!=": return left != right } } function $__(operator, value) { var handler = unaryOperators[operator]; if (value && value[handler]) return value[handler](); switch (operator) { case "+": return +value; case "-": return -value } } function compile(code, options) { if (!code) return ""; options = options || {}; var insertions = []; function getOffset(offset) { for (var i = 0, l = insertions.length; i < l; i++) { var insertion = insertions[i]; if (insertion[0] >= offset) break; offset += insertion[1] } return offset } function getCode(node) { return code.substring(getOffset(node.range[0]), getOffset(node.range[1])) } function getBetween(left, right) { return code.substring(getOffset(left.range[1]), getOffset(right.range[0])) } function replaceCode(node, str) { var start = getOffset(node.range[0]), end = getOffset(node.range[1]), insert = 0; for (var i = insertions.length - 1; i >= 0; i--) { if (start > insertions[i][0]) { insert = i + 1; break } } insertions.splice(insert, 0, [start, str.length - end + start]); code = code.substring(0, start) + str + code.substring(end) } function walkAST(node, parent) { if (!node) return; for (var key in node) { if (key === "range" || key === "loc") continue; var value = node[key]; if (Array.isArray(value)) { for (var i = 0, l = value.length; i < l; i++) walkAST(value[i], node) } else if (value && typeof value === "object") { walkAST(value, node) } } switch (node.type) { case "UnaryExpression": if (node.operator in unaryOperators && node.argument.type !== "Literal") { var arg = getCode(node.argument); replaceCode(node, '$__("' + node.operator + '", ' + arg + ")") } break; case "BinaryExpression": if (node.operator in binaryOperators && node.left.type !== "Literal") { var left = getCode(node.left), right = getCode(node.right), between = getBetween(node.left, node.right), operator = node.operator; replaceCode(node, "__$__(" + left + "," + between.replace(new RegExp("\\" + operator), '"' + operator + '"') + ", " + right + ")") } break; case "UpdateExpression": case "AssignmentExpression": var parentType = parent && parent.type; if (!(parentType === "ForStatement" || parentType === "BinaryExpression" && /^[=!<>]/.test(parent.operator) || parentType === "MemberExpression" && parent.computed)) { if (node.type === "UpdateExpression") { var arg = getCode(node.argument), exp = "__$__(" + arg + ', "' + node.operator[0] + '", 1)', str = arg + " = " + exp; if (!node.prefix && (parentType === "AssignmentExpression" || parentType === "VariableDeclarator")) { if (getCode(parent.left || parent.id) === arg) str = exp; str = arg + "; " + str } replaceCode(node, str) } else { if (/^.=$/.test(node.operator) && node.left.type !== "Literal") { var left = getCode(node.left), right = getCode(node.right), exp = left + " = __$__(" + left + ', "' + node.operator[0] + '", ' + right + ")"; replaceCode(node, /^\(.*\)$/.test(getCode(node)) ? "(" + exp + ")" : exp) } } } break; case "ExportDefaultDeclaration": replaceCode({ range: [node.start, node.declaration.start] }, "module.exports = "); break; case "ExportNamedDeclaration": var declaration = node.declaration; var specifiers = node.specifiers; if (declaration) { var declarations = declaration.declarations; if (declarations) { declarations.forEach(function(dec) { replaceCode(dec, "module.exports." + getCode(dec)) }); replaceCode({ range: [node.start, declaration.start + declaration.kind.length] }, "") } } else if (specifiers) { var exports = specifiers.map(function(specifier) { var name = getCode(specifier); return "module.exports." + name + " = " + name + "; " }).join(""); if (exports) { replaceCode(node, exports) } } break } } function encodeVLQ(value) { var res = "", base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; value = (Math.abs(value) << 1) + (value < 0 ? 1 : 0); while (value || !res) { var next = value & 32 - 1; value >>= 5; if (value) next |= 32; res += base64[next] } return res } var url = options.url || "", agent = paper.agent, version = agent.versionNumber, offsetCode = false, sourceMaps = options.sourceMaps, source = options.source || code, lineBreaks = /\r\n|\n|\r/gm, offset = options.offset || 0, map; if (sourceMaps && (agent.chrome && version >= 30 || agent.webkit && version >= 537.76 || agent.firefox && version >= 23 || agent.node)) { if (agent.node) { offset -= 2 } else if (window && url && !window.location.href.indexOf(url)) { var html = document.getElementsByTagName("html")[0].innerHTML; offset = html.substr(0, html.indexOf(code) + 1).match(lineBreaks).length + 1 } offsetCode = offset > 0 && !(agent.chrome && version >= 36 || agent.safari && version >= 600 || agent.firefox && version >= 40 || agent.node); var mappings = ["AA" + encodeVLQ(offsetCode ? 0 : offset) + "A"]; mappings.length = (code.match(lineBreaks) || []).length + 1 + (offsetCode ? offset : 0); map = { version: 3, file: url, names: [], mappings: mappings.join(";AACA"), sourceRoot: "", sources: [url], sourcesContent: [source] } } walkAST(parse(code, { ranges: true, preserveParens: true, sourceType: "module" })); if (map) { if (offsetCode) { code = new Array(offset + 1).join("\n") + code } if (/^(inline|both)$/.test(sourceMaps)) { code += "\n//# sourceMappingURL=data:application/json;base64," + self.btoa(unescape(encodeURIComponent(JSON.stringify(map)))) } code += "\n//# sourceURL=" + (url || "paperscript") } return { url: url, source: source, code: code, map: map } } function execute(code, scope, options) { paper = scope; var view = scope.getView(), tool = /\btool\.\w+|\s+on(?:Key|Mouse)(?:Up|Down|Move|Drag)\b/.test(code) && !/\bnew\s+Tool\b/.test(code) ? new Tool : null, toolHandlers = tool ? tool._events : [], handlers = ["onFrame", "onResize"].concat(toolHandlers), params = [], args = [], func, compiled = typeof code === "object" ? code : compile(code, options); code = compiled.code; function expose(scope, hidden) { for (var key in scope) { if ((hidden || !/^_/.test(key)) && new RegExp("([\\b\\s\\W]|^)" + key.replace(/\$/g, "\\$") + "\\b").test(code)) { params.push(key); args.push(scope[key]) } } } expose({ __$__: __$__, $__: $__, paper: scope, view: view, tool: tool }, true); expose(scope); code = "var module = { exports: {} }; " + code; var exports = Base.each(handlers, function(key) { if (new RegExp("\\s+" + key + "\\b").test(code)) { params.push(key); this.push("module.exports." + key + " = " + key + ";") } }, []).join("\n"); if (exports) { code += "\n" + exports } code += "\nreturn module.exports;"; var agent = paper.agent; if (document && (agent.chrome || agent.firefox && agent.versionNumber < 40)) { var script = document.createElement("script"), head = document.head || document.getElementsByTagName("head")[0]; if (agent.firefox) code = "\n" + code; script.appendChild(document.createTextNode("document.__paperscript__ = function(" + params + ") {" + code + "\n}")); head.appendChild(script); func = document.__paperscript__; delete document.__paperscript__; head.removeChild(script) } else { func = Function(params, code) } var exports = func && func.apply(scope, args); var obj = exports || {}; Base.each(toolHandlers, function(key) { var value = obj[key]; if (value) tool[key] = value }); if (view) { if (obj.onResize) view.setOnResize(obj.onResize); view.emit("resize", { size: view.size, delta: new Point }); if (obj.onFrame) view.setOnFrame(obj.onFrame); view.requestUpdate() } return exports } function loadScript(script) { if (/^text\/(?:x-|)paperscript$/.test(script.type) && PaperScope.getAttribute(script, "ignore") !== "true") { var canvasId = PaperScope.getAttribute(script, "canvas"), canvas = document.getElementById(canvasId), src = script.src || script.getAttribute("data-src"), async = PaperScope.hasAttribute(script, "async"), scopeAttribute = "data-paper-scope"; if (!canvas) throw new Error('Unable to find canvas with id "' + canvasId + '"'); var scope = PaperScope.get(canvas.getAttribute(scopeAttribute)) || (new PaperScope).setup(canvas); canvas.setAttribute(scopeAttribute, scope._id); if (src) { Http.request({ url: src, async: async, mimeType: "text/plain", onLoad: function(code) { execute(code, scope, src) } }) } else { execute(script.innerHTML, scope, script.baseURI) } script.setAttribute("data-paper-ignore", "true"); return scope } } function loadAll() { Base.each(document && document.getElementsByTagName("script"), loadScript) } function load(script) { return script ? loadScript(script) : loadAll() } if (window) { if (document.readyState === "complete") { setTimeout(loadAll) } else { DomEvent.add(window, { load: loadAll }) } } return { compile: compile, execute: execute, load: load, parse: parse } }.call(this); var paper = new(PaperScope.inject(Base.exports, { Base: Base, Numerical: Numerical, Key: Key, DomEvent: DomEvent, DomElement: DomElement, document: document, window: window, Symbol: SymbolDefinition, PlacedSymbol: SymbolItem })); if (paper.agent.node) { __webpack_require__(1158)(paper) } if (true) { !(__WEBPACK_AMD_DEFINE_FACTORY__ = paper, __WEBPACK_AMD_DEFINE_RESULT__ = typeof __WEBPACK_AMD_DEFINE_FACTORY__ === "function" ? __WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module) : __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)) } else if (typeof module === "object" && module) { module.exports = paper } return paper }.call(this, typeof self === "object" ? self : null) }, , function(module, exports, __webpack_require__) { (function(global) { __webpack_require__(475); var CONST = __webpack_require__(26); var Extend = __webpack_require__(19); var Phaser = { Actions: __webpack_require__(225), Animation: __webpack_require__(541), Cache: __webpack_require__(542), Cameras: __webpack_require__(543), Class: __webpack_require__(0), Create: __webpack_require__(586), Curves: __webpack_require__(592), Data: __webpack_require__(595), Display: __webpack_require__(597), DOM: __webpack_require__(626), Events: __webpack_require__(628), Game: __webpack_require__(630), GameObjects: __webpack_require__(664), Geom: __webpack_require__(377), Input: __webpack_require__(927), Loader: __webpack_require__(950), Math: __webpack_require__(973), Physics: __webpack_require__(1011), Plugins: __webpack_require__(1076), Renderer: __webpack_require__(1078), Scene: __webpack_require__(321), Scenes: __webpack_require__(1083), Sound: __webpack_require__(1085), Structs: __webpack_require__(1086), Textures: __webpack_require__(1087), Tilemaps: __webpack_require__(1089), Time: __webpack_require__(1138), Tweens: __webpack_require__(1140), Utils: __webpack_require__(1144) }; if (typeof PLUGIN_CAMERA3D) { Phaser.Cameras.Sprite3D = __webpack_require__(1152); Phaser.GameObjects.Sprite3D = __webpack_require__(140); Phaser.GameObjects.Factories.Sprite3D = __webpack_require__(1154); Phaser.GameObjects.Creators.Sprite3D = __webpack_require__(1155) } if (typeof PLUGIN_FBINSTANT) { Phaser.FacebookInstantGamesPlugin = __webpack_require__(334) } Phaser = Extend(false, Phaser, CONST); module.exports = Phaser; global.Phaser = Phaser }).call(exports, __webpack_require__(142)) }, function(module, exports, __webpack_require__) { module.exports = { Angle: __webpack_require__(484), Call: __webpack_require__(485), GetFirst: __webpack_require__(486), GetLast: __webpack_require__(487), GridAlign: __webpack_require__(488), IncAlpha: __webpack_require__(499), IncX: __webpack_require__(500), IncXY: __webpack_require__(501), IncY: __webpack_require__(502), PlaceOnCircle: __webpack_require__(503), PlaceOnEllipse: __webpack_require__(504), PlaceOnLine: __webpack_require__(505), PlaceOnRectangle: __webpack_require__(506), PlaceOnTriangle: __webpack_require__(507), PlayAnimation: __webpack_require__(508), PropertyValueInc: __webpack_require__(35), PropertyValueSet: __webpack_require__(27), RandomCircle: __webpack_require__(509), RandomEllipse: __webpack_require__(510), RandomLine: __webpack_require__(511), RandomRectangle: __webpack_require__(512), RandomTriangle: __webpack_require__(513), Rotate: __webpack_require__(514), RotateAround: __webpack_require__(515), RotateAroundDistance: __webpack_require__(516), ScaleX: __webpack_require__(517), ScaleXY: __webpack_require__(518), ScaleY: __webpack_require__(519), SetAlpha: __webpack_require__(520), SetBlendMode: __webpack_require__(521), SetDepth: __webpack_require__(522), SetHitArea: __webpack_require__(523), SetOrigin: __webpack_require__(524), SetRotation: __webpack_require__(525), SetScale: __webpack_require__(526), SetScaleX: __webpack_require__(527), SetScaleY: __webpack_require__(528), SetTint: __webpack_require__(529), SetVisible: __webpack_require__(530), SetX: __webpack_require__(531), SetXY: __webpack_require__(532), SetY: __webpack_require__(533), ShiftPosition: __webpack_require__(534), Shuffle: __webpack_require__(535), SmootherStep: __webpack_require__(536), SmoothStep: __webpack_require__(537), Spread: __webpack_require__(538), ToggleVisible: __webpack_require__(539), WrapInRectangle: __webpack_require__(540) } }, function(module, exports, __webpack_require__) { var ALIGN_CONST = __webpack_require__(143); var AlignInMap = []; AlignInMap[ALIGN_CONST.BOTTOM_CENTER] = __webpack_require__(227); AlignInMap[ALIGN_CONST.BOTTOM_LEFT] = __webpack_require__(228); AlignInMap[ALIGN_CONST.BOTTOM_RIGHT] = __webpack_require__(229); AlignInMap[ALIGN_CONST.CENTER] = __webpack_require__(230); AlignInMap[ALIGN_CONST.LEFT_CENTER] = __webpack_require__(232); AlignInMap[ALIGN_CONST.RIGHT_CENTER] = __webpack_require__(233); AlignInMap[ALIGN_CONST.TOP_CENTER] = __webpack_require__(234); AlignInMap[ALIGN_CONST.TOP_LEFT] = __webpack_require__(235); AlignInMap[ALIGN_CONST.TOP_RIGHT] = __webpack_require__(236); var QuickSet = function(child, alignIn, position, offsetX, offsetY) { return AlignInMap[position](child, alignIn, offsetX, offsetY) }; module.exports = QuickSet }, function(module, exports, __webpack_require__) { var GetBottom = __webpack_require__(38); var GetCenterX = __webpack_require__(74); var SetBottom = __webpack_require__(39); var SetCenterX = __webpack_require__(75); var BottomCenter = function(gameObject, alignIn, offsetX, offsetY) { if (offsetX === undefined) { offsetX = 0 } if (offsetY === undefined) { offsetY = 0 } SetCenterX(gameObject, GetCenterX(alignIn) + offsetX); SetBottom(gameObject, GetBottom(alignIn) + offsetY); return gameObject }; module.exports = BottomCenter }, function(module, exports, __webpack_require__) { var GetBottom = __webpack_require__(38); var GetLeft = __webpack_require__(40); var SetBottom = __webpack_require__(39); var SetLeft = __webpack_require__(41); var BottomLeft = function(gameObject, alignIn, offsetX, offsetY) { if (offsetX === undefined) { offsetX = 0 } if (offsetY === undefined) { offsetY = 0 } SetLeft(gameObject, GetLeft(alignIn) - offsetX); SetBottom(gameObject, GetBottom(alignIn) + offsetY); return gameObject }; module.exports = BottomLeft }, function(module, exports, __webpack_require__) { var GetBottom = __webpack_require__(38); var GetRight = __webpack_require__(42); var SetBottom = __webpack_require__(39); var SetRight = __webpack_require__(43); var BottomRight = function(gameObject, alignIn, offsetX, offsetY) { if (offsetX === undefined) { offsetX = 0 } if (offsetY === undefined) { offsetY = 0 } SetRight(gameObject, GetRight(alignIn) + offsetX); SetBottom(gameObject, GetBottom(alignIn) + offsetY); return gameObject }; module.exports = BottomRight }, function(module, exports, __webpack_require__) { var CenterOn = __webpack_require__(231); var GetCenterX = __webpack_require__(74); var GetCenterY = __webpack_require__(77); var Center = function(gameObject, alignIn, offsetX, offsetY) { if (offsetX === undefined) { offsetX = 0 } if (offsetY === undefined) { offsetY = 0 } CenterOn(gameObject, GetCenterX(alignIn) + offsetX, GetCenterY(alignIn) + offsetY); return gameObject }; module.exports = Center }, function(module, exports, __webpack_require__) { var SetCenterX = __webpack_require__(75); var SetCenterY = __webpack_require__(76); var CenterOn = function(gameObject, x, y) { SetCenterX(gameObject, x); return SetCenterY(gameObject, y) }; module.exports = CenterOn }, function(module, exports, __webpack_require__) { var GetCenterY = __webpack_require__(77); var GetLeft = __webpack_require__(40); var SetCenterY = __webpack_require__(76); var SetLeft = __webpack_require__(41); var LeftCenter = function(gameObject, alignIn, offsetX, offsetY) { if (offsetX === undefined) { offsetX = 0 } if (offsetY === undefined) { offsetY = 0 } SetLeft(gameObject, GetLeft(alignIn) - offsetX); SetCenterY(gameObject, GetCenterY(alignIn) + offsetY); return gameObject }; module.exports = LeftCenter }, function(module, exports, __webpack_require__) { var GetCenterY = __webpack_require__(77); var GetRight = __webpack_require__(42); var SetCenterY = __webpack_require__(76); var SetRight = __webpack_require__(43); var RightCenter = function(gameObject, alignIn, offsetX, offsetY) { if (offsetX === undefined) { offsetX = 0 } if (offsetY === undefined) { offsetY = 0 } SetRight(gameObject, GetRight(alignIn) + offsetX); SetCenterY(gameObject, GetCenterY(alignIn) + offsetY); return gameObject }; module.exports = RightCenter }, function(module, exports, __webpack_require__) { var GetCenterX = __webpack_require__(74); var GetTop = __webpack_require__(44); var SetCenterX = __webpack_require__(75); var SetTop = __webpack_require__(45); var TopCenter = function(gameObject, alignIn, offsetX, offsetY) { if (offsetX === undefined) { offsetX = 0 } if (offsetY === undefined) { offsetY = 0 } SetCenterX(gameObject, GetCenterX(alignIn) + offsetX); SetTop(gameObject, GetTop(alignIn) - offsetY); return gameObject }; module.exports = TopCenter }, function(module, exports, __webpack_require__) { var GetLeft = __webpack_require__(40); var GetTop = __webpack_require__(44); var SetLeft = __webpack_require__(41); var SetTop = __webpack_require__(45); var TopLeft = function(gameObject, alignIn, offsetX, offsetY) { if (offsetX === undefined) { offsetX = 0 } if (offsetY === undefined) { offsetY = 0 } SetLeft(gameObject, GetLeft(alignIn) - offsetX); SetTop(gameObject, GetTop(alignIn) - offsetY); return gameObject }; module.exports = TopLeft }, function(module, exports, __webpack_require__) { var GetRight = __webpack_require__(42); var GetTop = __webpack_require__(44); var SetRight = __webpack_require__(43); var SetTop = __webpack_require__(45); var TopRight = function(gameObject, alignIn, offsetX, offsetY) { if (offsetX === undefined) { offsetX = 0 } if (offsetY === undefined) { offsetY = 0 } SetRight(gameObject, GetRight(alignIn) + offsetX); SetTop(gameObject, GetTop(alignIn) - offsetY); return gameObject }; module.exports = TopRight }, function(module, exports, __webpack_require__) { var CircumferencePoint = __webpack_require__(144); var FromPercent = __webpack_require__(90); var MATH_CONST = __webpack_require__(18); var Point = __webpack_require__(6); var GetPoint = function(circle, position, out) { if (out === undefined) { out = new Point } var angle = FromPercent(position, 0, MATH_CONST.PI2); return CircumferencePoint(circle, angle, out) }; module.exports = GetPoint }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var RandomDataGenerator = new Class({ initialize: function RandomDataGenerator(seeds) { if (seeds === undefined) { seeds = [(Date.now() * Math.random()).toString()] } this.c = 1; this.s0 = 0; this.s1 = 0; this.s2 = 0; this.n = 0; this.signs = [-1, 1]; if (seeds) { this.init(seeds) } }, rnd: function() { var t = 2091639 * this.s0 + this.c * 2.3283064365386963e-10; this.c = t | 0; this.s0 = this.s1; this.s1 = this.s2; this.s2 = t - this.c; return this.s2 }, hash: function(data) { var h; var n = this.n; data = data.toString(); for (var i = 0; i < data.length; i++) { n += data.charCodeAt(i); h = .02519603282416938 * n; n = h >>> 0; h -= n; h *= n; n = h >>> 0; h -= n; n += h * 4294967296 } this.n = n; return (n >>> 0) * 2.3283064365386963e-10 }, init: function(seeds) { if (typeof seeds === "string") { this.state(seeds) } else { this.sow(seeds) } }, sow: function(seeds) { this.n = 4022871197; this.s0 = this.hash(" "); this.s1 = this.hash(" "); this.s2 = this.hash(" "); this.c = 1; if (!seeds) { return } for (var i = 0; i < seeds.length && seeds[i] != null; i++) { var seed = seeds[i]; this.s0 -= this.hash(seed); this.s0 += ~~(this.s0 < 0); this.s1 -= this.hash(seed); this.s1 += ~~(this.s1 < 0); this.s2 -= this.hash(seed); this.s2 += ~~(this.s2 < 0) } }, integer: function() { return this.rnd() * 4294967296 }, frac: function() { return this.rnd() + (this.rnd() * 2097152 | 0) * 11102230246251565e-32 }, real: function() { return this.integer() + this.frac() }, integerInRange: function(min, max) { return Math.floor(this.realInRange(0, max - min + 1) + min) }, between: function(min, max) { return Math.floor(this.realInRange(0, max - min + 1) + min) }, realInRange: function(min, max) { return this.frac() * (max - min) + min }, normal: function() { return 1 - 2 * this.frac() }, uuid: function() { var a = ""; var b = ""; for (b = a = ""; a++ < 36; b += ~a % 5 | a * 3 & 4 ? (a ^ 15 ? 8 ^ this.frac() * (a ^ 20 ? 16 : 4) : 4).toString(16) : "-") {} return b }, pick: function(array) { return array[this.integerInRange(0, array.length - 1)] }, sign: function() { return this.pick(this.signs) }, weightedPick: function(array) { return array[~~(Math.pow(this.frac(), 2) * (array.length - 1) + .5)] }, timestamp: function(min, max) { return this.realInRange(min || 9466848e5, max || 1577862e6) }, angle: function() { return this.integerInRange(-180, 180) }, rotation: function() { return this.realInRange(-3.1415926, 3.1415926) }, state: function(state) { if (typeof state === "string" && state.match(/^!rnd/)) { state = state.split(","); this.c = parseFloat(state[1]); this.s0 = parseFloat(state[2]); this.s1 = parseFloat(state[3]); this.s2 = parseFloat(state[4]) } return ["!rnd", this.c, this.s0, this.s1, this.s2].join(",") }, shuffle: function(array) { var len = array.length - 1; for (var i = len; i > 0; i--) { var randomIndex = Math.floor(this.frac() * (len + 1)); var itemAtIndex = array[randomIndex]; array[randomIndex] = array[i]; array[i] = itemAtIndex } return array } }); module.exports = RandomDataGenerator }, function(module, exports, __webpack_require__) { var Circumference = __webpack_require__(240); var CircumferencePoint = __webpack_require__(144); var FromPercent = __webpack_require__(90); var MATH_CONST = __webpack_require__(18); var GetPoints = function(circle, quantity, stepRate, out) { if (out === undefined) { out = [] } if (!quantity) { quantity = Circumference(circle) / stepRate } for (var i = 0; i < quantity; i++) { var angle = FromPercent(i / quantity, 0, MATH_CONST.PI2); out.push(CircumferencePoint(circle, angle)) } return out }; module.exports = GetPoints }, function(module, exports) { var Circumference = function(circle) { return 2 * (Math.PI * circle.radius) }; module.exports = Circumference }, function(module, exports, __webpack_require__) { var Clamp = __webpack_require__(23); var _FLAG = 2; var Alpha = { _alpha: 1, _alphaTL: 1, _alphaTR: 1, _alphaBL: 1, _alphaBR: 1, clearAlpha: function() { return this.setAlpha(1) }, setAlpha: function(topLeft, topRight, bottomLeft, bottomRight) { if (topLeft === undefined) { topLeft = 1 } if (topRight === undefined) { this.alpha = topLeft } else { this._alphaTL = Clamp(topLeft, 0, 1); this._alphaTR = Clamp(topRight, 0, 1); this._alphaBL = Clamp(bottomLeft, 0, 1); this._alphaBR = Clamp(bottomRight, 0, 1) } return this }, alpha: { get: function() { return this._alpha }, set: function(value) { var v = Clamp(value, 0, 1); this._alpha = v; this._alphaTL = v; this._alphaTR = v; this._alphaBL = v; this._alphaBR = v; if (v === 0) { this.renderFlags &= ~_FLAG } else { this.renderFlags |= _FLAG } } }, alphaTopLeft: { get: function() { return this._alphaTL }, set: function(value) { var v = Clamp(value, 0, 1); this._alphaTL = v; if (v !== 0) { this.renderFlags |= _FLAG } } }, alphaTopRight: { get: function() { return this._alphaTR }, set: function(value) { var v = Clamp(value, 0, 1); this._alphaTR = v; if (v !== 0) { this.renderFlags |= _FLAG } } }, alphaBottomLeft: { get: function() { return this._alphaBL }, set: function(value) { var v = Clamp(value, 0, 1); this._alphaBL = v; if (v !== 0) { this.renderFlags |= _FLAG } } }, alphaBottomRight: { get: function() { return this._alphaBR }, set: function(value) { var v = Clamp(value, 0, 1); this._alphaBR = v; if (v !== 0) { this.renderFlags |= _FLAG } } } }; module.exports = Alpha }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Animation = new Class({ initialize: function Animation(parent) { this.parent = parent; this.animationManager = parent.scene.sys.anims; this.animationManager.once("remove", this.remove, this); this.isPlaying = false; this.currentAnim = null; this.currentFrame = null; this._timeScale = 1; this.frameRate = 0; this.duration = 0; this.msPerFrame = 0; this.skipMissedFrames = true; this._delay = 0; this._repeat = 0; this._repeatDelay = 0; this._yoyo = false; this.forward = true; this._reverse = false; this.accumulator = 0; this.nextTick = 0; this.repeatCounter = 0; this.pendingRepeat = false; this._paused = false; this._wasPlaying = false; this._pendingStop = 0; this._pendingStopValue }, setDelay: function(value) { if (value === undefined) { value = 0 } this._delay = value; return this.parent }, getDelay: function() { return this._delay }, delayedPlay: function(delay, key, startFrame) { this.play(key, true, startFrame); this.nextTick += delay; return this.parent }, getCurrentKey: function() { if (this.currentAnim) { return this.currentAnim.key } }, load: function(key, startFrame) { if (startFrame === undefined) { startFrame = 0 } if (this.isPlaying) { this.stop() } this.animationManager.load(this, key, startFrame); return this.parent }, pause: function(atFrame) { if (!this._paused) { this._paused = true; this._wasPlaying = this.isPlaying; this.isPlaying = false } if (atFrame !== undefined) { this.updateFrame(atFrame) } return this.parent }, resume: function(fromFrame) { if (this._paused) { this._paused = false; this.isPlaying = this._wasPlaying } if (fromFrame !== undefined) { this.updateFrame(fromFrame) } return this.parent }, isPaused: { get: function() { return this._paused } }, play: function(key, ignoreIfPlaying, startFrame) { if (ignoreIfPlaying === undefined) { ignoreIfPlaying = false } if (startFrame === undefined) { startFrame = 0 } if (ignoreIfPlaying && this.isPlaying && this.currentAnim.key === key) { return this.parent } this.forward = true; this._reverse = false; return this._startAnimation(key, startFrame) }, playReverse: function(key, ignoreIfPlaying, startFrame) { if (ignoreIfPlaying === undefined) { ignoreIfPlaying = false } if (startFrame === undefined) { startFrame = 0 } if (ignoreIfPlaying && this.isPlaying && this.currentAnim.key === key) { return this.parent } this.forward = false; this._reverse = true; return this._startAnimation(key, startFrame) }, _startAnimation: function(key, startFrame) { this.load(key, startFrame); var anim = this.currentAnim; var gameObject = this.parent; this.repeatCounter = this._repeat === -1 ? Number.MAX_VALUE : this._repeat; anim.getFirstTick(this); this.isPlaying = true; this.pendingRepeat = false; if (anim.showOnStart) { gameObject.visible = true } gameObject.emit("animationstart", this.currentAnim, this.currentFrame, gameObject); return gameObject }, reverse: function(key) { if (!this.isPlaying || this.currentAnim.key !== key) { return this.parent } this._reverse = !this._reverse; this.forward = !this.forward; return this.parent }, getProgress: function() { var p = this.currentFrame.progress; if (!this.forward) { p = 1 - p } return p }, setProgress: function(value) { if (!this.forward) { value = 1 - value } this.setCurrentFrame(this.currentAnim.getFrameByProgress(value)); return this.parent }, remove: function(key, animation) { if (animation === undefined) { animation = this.currentAnim } if (this.isPlaying && animation.key === this.currentAnim.key) { this.stop(); this.setCurrentFrame(this.currentAnim.frames[0]) } }, getRepeat: function() { return this._repeat }, setRepeat: function(value) { this._repeat = value; this.repeatCounter = 0; return this.parent }, getRepeatDelay: function() { return this._repeatDelay }, setRepeatDelay: function(value) { this._repeatDelay = value; return this.parent }, restart: function(includeDelay) { if (includeDelay === undefined) { includeDelay = false } this.currentAnim.getFirstTick(this, includeDelay); this.forward = true; this.isPlaying = true; this.pendingRepeat = false; this._paused = false; this.updateFrame(this.currentAnim.frames[0]); var gameObject = this.parent; gameObject.emit("animationrestart", this.currentAnim, this.currentFrame, gameObject); return this.parent }, stop: function() { this._pendingStop = 0; this.isPlaying = false; var gameObject = this.parent; gameObject.emit("animationcomplete", this.currentAnim, this.currentFrame, gameObject); return gameObject }, stopAfterDelay: function(delay) { this._pendingStop = 1; this._pendingStopValue = delay; return this.parent }, stopOnRepeat: function() { this._pendingStop = 2; return this.parent }, stopOnFrame: function(frame) { this._pendingStop = 3; this._pendingStopValue = frame; return this.parent }, setTimeScale: function(value) { if (value === undefined) { value = 1 } this._timeScale = value; return this.parent }, getTimeScale: function() { return this._timeScale }, getTotalFrames: function() { return this.currentAnim.frames.length }, update: function(time, delta) { if (!this.currentAnim || !this.isPlaying || this.currentAnim.paused) { return } this.accumulator += delta * this._timeScale; if (this._pendingStop === 1) { this._pendingStopValue -= delta; if (this._pendingStopValue <= 0) { return this.currentAnim.completeAnimation(this) } } if (this.accumulator >= this.nextTick) { this.currentAnim.setFrame(this) } }, setCurrentFrame: function(animationFrame) { var gameObject = this.parent; this.currentFrame = animationFrame; gameObject.texture = animationFrame.frame.texture; gameObject.frame = animationFrame.frame; if (gameObject.isCropped) { gameObject.frame.updateCropUVs(gameObject._crop, gameObject.flipX, gameObject.flipY) } gameObject.setSizeToFrame(); if (animationFrame.frame.customPivot) { gameObject.setOrigin(animationFrame.frame.pivotX, animationFrame.frame.pivotY) } else { gameObject.updateDisplayOrigin() } return gameObject }, updateFrame: function(animationFrame) { var gameObject = this.setCurrentFrame(animationFrame); if (this.isPlaying) { if (animationFrame.setAlpha) { gameObject.alpha = animationFrame.alpha } var anim = this.currentAnim; gameObject.emit("animationupdate", anim, animationFrame, gameObject); if (this._pendingStop === 3 && this._pendingStopValue === animationFrame) { this.currentAnim.completeAnimation(this) } } }, setYoyo: function(value) { if (value === undefined) { value = false } this._yoyo = value; return this.parent }, getYoyo: function() { return this._yoyo }, destroy: function() { this.animationManager.off("remove", this.remove, this); this.animationManager = null; this.parent = null; this.currentAnim = null; this.currentFrame = null } }); module.exports = Animation }, function(module, exports, __webpack_require__) { var BlendModes = __webpack_require__(61); var BlendMode = { _blendMode: BlendModes.NORMAL, blendMode: { get: function() { return this._blendMode }, set: function(value) { if (typeof value === "string") { value = BlendModes[value] } value |= 0; if (value >= -1) { this._blendMode = value } } }, setBlendMode: function(value) { this.blendMode = value; return this } }; module.exports = BlendMode }, function(module, exports) { var Depth = { _depth: 0, depth: { get: function() { return this._depth }, set: function(value) { this.scene.sys.queueDepthSort(); this._depth = value } }, setDepth: function(value) { if (value === undefined) { value = 0 } this.depth = value; return this } }; module.exports = Depth }, function(module, exports, __webpack_require__) { var GetPoint = __webpack_require__(146); var Perimeter = __webpack_require__(108); var GetPoints = function(rectangle, quantity, stepRate, out) { if (out === undefined) { out = [] } if (!quantity) { quantity = Perimeter(rectangle) / stepRate } for (var i = 0; i < quantity; i++) { var position = i / quantity; out.push(GetPoint(rectangle, position)) } return out }; module.exports = GetPoints }, function(module, exports, __webpack_require__) { var Point = __webpack_require__(6); var GetPoint = function(line, position, out) { if (out === undefined) { out = new Point } out.x = line.x1 + (line.x2 - line.x1) * position; out.y = line.y1 + (line.y2 - line.y1) * position; return out }; module.exports = GetPoint }, function(module, exports) { var RotateAround = function(point, x, y, angle) { var c = Math.cos(angle); var s = Math.sin(angle); var tx = point.x - x; var ty = point.y - y; point.x = tx * c - ty * s + x; point.y = tx * s + ty * c + y; return point }; module.exports = RotateAround }, function(module, exports, __webpack_require__) { var BitmapMask = __webpack_require__(249); var GeometryMask = __webpack_require__(250); var Mask = { mask: null, setMask: function(mask) { this.mask = mask; return this }, clearMask: function(destroyMask) { if (destroyMask === undefined) { destroyMask = false } if (destroyMask && this.mask) { this.mask.destroy() } this.mask = null; return this }, createBitmapMask: function(renderable) { if (renderable === undefined && this.texture) { renderable = this } return new BitmapMask(this.scene, renderable) }, createGeometryMask: function(graphics) { if (graphics === undefined && this.type === "Graphics") { graphics = this } return new GeometryMask(this.scene, graphics) } }; module.exports = Mask }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var BitmapMask = new Class({ initialize: function BitmapMask(scene, renderable) { var renderer = scene.sys.game.renderer; this.renderer = renderer; this.bitmapMask = renderable; this.maskTexture = null; this.mainTexture = null; this.dirty = true; this.mainFramebuffer = null; this.maskFramebuffer = null; this.invertAlpha = false; if (renderer && renderer.gl) { var width = renderer.width; var height = renderer.height; var pot = (width & width - 1) === 0 && (height & height - 1) === 0; var gl = renderer.gl; var wrap = pot ? gl.REPEAT : gl.CLAMP_TO_EDGE; var filter = gl.LINEAR; this.mainTexture = renderer.createTexture2D(0, filter, filter, wrap, wrap, gl.RGBA, null, width, height); this.maskTexture = renderer.createTexture2D(0, filter, filter, wrap, wrap, gl.RGBA, null, width, height); this.mainFramebuffer = renderer.createFramebuffer(width, height, this.mainTexture, false); this.maskFramebuffer = renderer.createFramebuffer(width, height, this.maskTexture, false); renderer.onContextRestored(function(renderer) { var width = renderer.width; var height = renderer.height; var pot = (width & width - 1) === 0 && (height & height - 1) === 0; var gl = renderer.gl; var wrap = pot ? gl.REPEAT : gl.CLAMP_TO_EDGE; var filter = gl.LINEAR; this.mainTexture = renderer.createTexture2D(0, filter, filter, wrap, wrap, gl.RGBA, null, width, height); this.maskTexture = renderer.createTexture2D(0, filter, filter, wrap, wrap, gl.RGBA, null, width, height); this.mainFramebuffer = renderer.createFramebuffer(width, height, this.mainTexture, false); this.maskFramebuffer = renderer.createFramebuffer(width, height, this.maskTexture, false) }, this) } }, setBitmap: function(renderable) { this.bitmapMask = renderable }, preRenderWebGL: function(renderer, maskedObject, camera) { renderer.pipelines.BitmapMaskPipeline.beginMask(this, maskedObject, camera) }, postRenderWebGL: function(renderer) { renderer.pipelines.BitmapMaskPipeline.endMask(this) }, preRenderCanvas: function() {}, postRenderCanvas: function() {}, destroy: function() { this.bitmapMask = null; var renderer = this.renderer; if (renderer && renderer.gl) { renderer.deleteTexture(this.mainTexture); renderer.deleteTexture(this.maskTexture); renderer.deleteFramebuffer(this.mainFramebuffer); renderer.deleteFramebuffer(this.maskFramebuffer) } this.mainTexture = null; this.maskTexture = null; this.mainFramebuffer = null; this.maskFramebuffer = null; this.renderer = null } }); module.exports = BitmapMask }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var GeometryMask = new Class({ initialize: function GeometryMask(scene, graphicsGeometry) { this.geometryMask = graphicsGeometry }, setShape: function(graphicsGeometry) { this.geometryMask = graphicsGeometry }, preRenderWebGL: function(renderer, mask, camera) { var gl = renderer.gl; var geometryMask = this.geometryMask; renderer.flush(); gl.enable(gl.STENCIL_TEST); gl.clear(gl.STENCIL_BUFFER_BIT); gl.colorMask(false, false, false, false); gl.stencilFunc(gl.NOTEQUAL, 1, 1); gl.stencilOp(gl.REPLACE, gl.REPLACE, gl.REPLACE); geometryMask.renderWebGL(renderer, geometryMask, 0, camera); renderer.flush(); gl.colorMask(true, true, true, true); gl.stencilFunc(gl.EQUAL, 1, 1); gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP) }, postRenderWebGL: function(renderer) { var gl = renderer.gl; renderer.flush(); gl.disable(gl.STENCIL_TEST) }, preRenderCanvas: function(renderer, mask, camera) { var geometryMask = this.geometryMask; renderer.currentContext.save(); geometryMask.renderCanvas(renderer, geometryMask, 0, camera, null, null, true); renderer.currentContext.clip() }, postRenderCanvas: function(renderer) { renderer.currentContext.restore() }, destroy: function() { this.geometryMask = null } }); module.exports = GeometryMask }, function(module, exports) { var ScrollFactor = { scrollFactorX: 1, scrollFactorY: 1, setScrollFactor: function(x, y) { if (y === undefined) { y = x } this.scrollFactorX = x; this.scrollFactorY = y; return this } }; module.exports = ScrollFactor }, function(module, exports) { var ToJSON = function(gameObject) { var out = { name: gameObject.name, type: gameObject.type, x: gameObject.x, y: gameObject.y, depth: gameObject.depth, scale: { x: gameObject.scaleX, y: gameObject.scaleY }, origin: { x: gameObject.originX, y: gameObject.originY }, flipX: gameObject.flipX, flipY: gameObject.flipY, rotation: gameObject.rotation, alpha: gameObject.alpha, visible: gameObject.visible, scaleMode: gameObject.scaleMode, blendMode: gameObject.blendMode, textureKey: "", frameKey: "", data: {} }; if (gameObject.texture) { out.textureKey = gameObject.texture.key; out.frameKey = gameObject.frame.name } return out }; module.exports = ToJSON }, function(module, exports, __webpack_require__) { var MATH_CONST = __webpack_require__(18); var TransformMatrix = __webpack_require__(48); var WrapAngle = __webpack_require__(150); var WrapAngleDegrees = __webpack_require__(151); var _FLAG = 4; var Transform = { _scaleX: 1, _scaleY: 1, _rotation: 0, x: 0, y: 0, z: 0, w: 0, scaleX: { get: function() { return this._scaleX }, set: function(value) { this._scaleX = value; if (this._scaleX === 0) { this.renderFlags &= ~_FLAG } else { this.renderFlags |= _FLAG } } }, scaleY: { get: function() { return this._scaleY }, set: function(value) { this._scaleY = value; if (this._scaleY === 0) { this.renderFlags &= ~_FLAG } else { this.renderFlags |= _FLAG } } }, angle: { get: function() { return WrapAngleDegrees(this._rotation * MATH_CONST.RAD_TO_DEG) }, set: function(value) { this.rotation = WrapAngleDegrees(value) * MATH_CONST.DEG_TO_RAD } }, rotation: { get: function() { return this._rotation }, set: function(value) { this._rotation = WrapAngle(value) } }, setPosition: function(x, y, z, w) { if (x === undefined) { x = 0 } if (y === undefined) { y = x } if (z === undefined) { z = 0 } if (w === undefined) { w = 0 } this.x = x; this.y = y; this.z = z; this.w = w; return this }, setRandomPosition: function(x, y, width, height) { if (x === undefined) { x = 0 } if (y === undefined) { y = 0 } if (width === undefined) { width = this.scene.sys.game.config.width } if (height === undefined) { height = this.scene.sys.game.config.height } this.x = x + Math.random() * width; this.y = y + Math.random() * height; return this }, setRotation: function(radians) { if (radians === undefined) { radians = 0 } this.rotation = radians; return this }, setAngle: function(degrees) { if (degrees === undefined) { degrees = 0 } this.angle = degrees; return this }, setScale: function(x, y) { if (x === undefined) { x = 1 } if (y === undefined) { y = x } this.scaleX = x; this.scaleY = y; return this }, setX: function(value) { if (value === undefined) { value = 0 } this.x = value; return this }, setY: function(value) { if (value === undefined) { value = 0 } this.y = value; return this }, setZ: function(value) { if (value === undefined) { value = 0 } this.z = value; return this }, setW: function(value) { if (value === undefined) { value = 0 } this.w = value; return this }, getLocalTransformMatrix: function(tempMatrix) { if (tempMatrix === undefined) { tempMatrix = new TransformMatrix } return tempMatrix.applyITRS(this.x, this.y, this._rotation, this._scaleX, this._scaleY) }, getWorldTransformMatrix: function(tempMatrix, parentMatrix) { if (tempMatrix === undefined) { tempMatrix = new TransformMatrix } if (parentMatrix === undefined) { parentMatrix = new TransformMatrix } var parent = this.parentContainer; if (!parent) { return this.getLocalTransformMatrix(tempMatrix) } tempMatrix.applyITRS(this.x, this.y, this._rotation, this._scaleX, this._scaleY); while (parent) { parentMatrix.applyITRS(parent.x, parent.y, parent._rotation, parent._scaleX, parent._scaleY); parentMatrix.multiply(tempMatrix, tempMatrix); parent = parent.parentContainer } return tempMatrix } }; module.exports = Transform }, function(module, exports) { var _FLAG = 1; var Visible = { _visible: true, visible: { get: function() { return this._visible }, set: function(value) { if (value) { this._visible = true; this.renderFlags |= _FLAG } else { this._visible = false; this.renderFlags &= ~_FLAG } } }, setVisible: function(value) { this.visible = value; return this } }; module.exports = Visible }, function(module, exports, __webpack_require__) { var Perimeter = __webpack_require__(108); var Point = __webpack_require__(6); var MarchingAnts = function(rect, step, quantity, out) { if (out === undefined) { out = [] } if (!step && !quantity) { return out } if (!step) { step = Perimeter(rect) / quantity } else { quantity = Math.round(Perimeter(rect) / step) } var x = rect.x; var y = rect.y; var face = 0; for (var i = 0; i < quantity; i++) { out.push(new Point(x, y)); switch (face) { case 0: x += step; if (x >= rect.right) { face = 1; y += x - rect.right; x = rect.right } break; case 1: y += step; if (y >= rect.bottom) { face = 2; x -= y - rect.bottom; y = rect.bottom } break; case 2: x -= step; if (x <= rect.left) { face = 3; y -= rect.left - x; x = rect.left } break; case 3: y -= step; if (y <= rect.top) { face = 0; y = rect.top } break } } return out }; module.exports = MarchingAnts }, function(module, exports) { var RotateLeft = function(array, total) { if (total === undefined) { total = 1 } var element = null; for (var i = 0; i < total; i++) { element = array.shift(); array.push(element) } return element }; module.exports = RotateLeft }, function(module, exports) { var RotateRight = function(array, total) { if (total === undefined) { total = 1 } var element = null; for (var i = 0; i < total; i++) { element = array.pop(); array.unshift(element) } return element }; module.exports = RotateRight }, function(module, exports) { var BresenhamPoints = function(line, stepRate, results) { if (stepRate === undefined) { stepRate = 1 } if (results === undefined) { results = [] } var x1 = Math.round(line.x1); var y1 = Math.round(line.y1); var x2 = Math.round(line.x2); var y2 = Math.round(line.y2); var dx = Math.abs(x2 - x1); var dy = Math.abs(y2 - y1); var sx = x1 < x2 ? 1 : -1; var sy = y1 < y2 ? 1 : -1; var err = dx - dy; results.push({ x: x1, y: y1 }); var i = 1; while (!(x1 === x2 && y1 === y2)) { var e2 = err << 1; if (e2 > -dy) { err -= dy; x1 += sx } if (e2 < dx) { err += dx; y1 += sy } if (i % stepRate === 0) { results.push({ x: x1, y: y1 }) } i++ } return results }; module.exports = BresenhamPoints }, function(module, exports, __webpack_require__) { var Clamp = __webpack_require__(23); var Class = __webpack_require__(0); var FindClosestInSorted = __webpack_require__(260); var Frame = __webpack_require__(261); var GetValue = __webpack_require__(4); var Animation = new Class({ initialize: function Animation(manager, key, config) { this.manager = manager; this.key = key; this.type = "frame"; this.frames = this.getFrames(manager.textureManager, GetValue(config, "frames", []), GetValue(config, "defaultTextureKey", null)); this.frameRate = GetValue(config, "frameRate", null); this.duration = GetValue(config, "duration", null); if (this.duration === null && this.frameRate === null) { this.frameRate = 24; this.duration = this.frameRate / this.frames.length * 1e3 } else if (this.duration && this.frameRate === null) { this.frameRate = this.frames.length / (this.duration / 1e3) } else { this.duration = this.frames.length / this.frameRate * 1e3 } this.msPerFrame = 1e3 / this.frameRate; this.skipMissedFrames = GetValue(config, "skipMissedFrames", true); this.delay = GetValue(config, "delay", 0); this.repeat = GetValue(config, "repeat", 0); this.repeatDelay = GetValue(config, "repeatDelay", 0); this.yoyo = GetValue(config, "yoyo", false); this.showOnStart = GetValue(config, "showOnStart", false); this.hideOnComplete = GetValue(config, "hideOnComplete", false); this.paused = false; this.manager.on("pauseall", this.pause, this); this.manager.on("resumeall", this.resume, this) }, addFrame: function(config) { return this.addFrameAt(this.frames.length, config) }, addFrameAt: function(index, config) { var newFrames = this.getFrames(this.manager.textureManager, config); if (newFrames.length > 0) { if (index === 0) { this.frames = newFrames.concat(this.frames) } else if (index === this.frames.length) { this.frames = this.frames.concat(newFrames) } else { var pre = this.frames.slice(0, index); var post = this.frames.slice(index); this.frames = pre.concat(newFrames, post) } this.updateFrameSequence() } return this }, checkFrame: function(index) { return index >= 0 && index < this.frames.length }, completeAnimation: function(component) { if (this.hideOnComplete) { component.parent.visible = false } component.stop() }, getFirstTick: function(component, includeDelay) { if (includeDelay === undefined) { includeDelay = true } component.accumulator = 0; component.nextTick = component.msPerFrame + component.currentFrame.duration; if (includeDelay) { component.nextTick += component._delay } }, getFrameAt: function(index) { return this.frames[index] }, getFrames: function(textureManager, frames, defaultTextureKey) { var out = []; var prev; var animationFrame; var index = 1; var i; var textureKey; if (typeof frames === "string") { textureKey = frames; var texture = textureManager.get(textureKey); var frameKeys = texture.getFrameNames(); frames = []; frameKeys.forEach(function(idx, value) { frames.push({ key: textureKey, frame: value }) }) } if (!Array.isArray(frames) || frames.length === 0) { return out } for (i = 0; i < frames.length; i++) { var item = frames[i]; var key = GetValue(item, "key", defaultTextureKey); if (!key) { continue } var frame = GetValue(item, "frame", 0); var textureFrame = textureManager.getFrame(key, frame); animationFrame = new Frame(key, frame, index, textureFrame); animationFrame.duration = GetValue(item, "duration", 0); animationFrame.isFirst = !prev; if (prev) { prev.nextFrame = animationFrame; animationFrame.prevFrame = prev } out.push(animationFrame); prev = animationFrame; index++ } if (out.length > 0) { animationFrame.isLast = true; animationFrame.nextFrame = out[0]; out[0].prevFrame = animationFrame; var slice = 1 / (out.length - 1); for (i = 0; i < out.length; i++) { out[i].progress = i * slice } } return out }, getNextTick: function(component) { component.accumulator -= component.nextTick; component.nextTick = component.msPerFrame + component.currentFrame.duration }, load: function(component, startFrame) { if (startFrame >= this.frames.length) { startFrame = 0 } if (component.currentAnim !== this) { component.currentAnim = this; component.frameRate = this.frameRate; component.duration = this.duration; component.msPerFrame = this.msPerFrame; component.skipMissedFrames = this.skipMissedFrames; component._delay = this.delay; component._repeat = this.repeat; component._repeatDelay = this.repeatDelay; component._yoyo = this.yoyo } var frame = this.frames[startFrame]; if (startFrame === 0 && !component.forward) { frame = this.getLastFrame() } component.updateFrame(frame) }, getFrameByProgress: function(value) { value = Clamp(value, 0, 1); return FindClosestInSorted(value, this.frames, "progress") }, nextFrame: function(component) { var frame = component.currentFrame; if (frame.isLast) { if (component._yoyo) { this.handleYoyoFrame(component, false) } else if (component.repeatCounter > 0) { if (component._reverse && component.forward) { component.forward = false } else { this.repeatAnimation(component) } } else { this.completeAnimation(component) } } else { this.updateAndGetNextTick(component, frame.nextFrame) } }, handleYoyoFrame: function(component, isReverse) { if (!isReverse) { isReverse = false } if (component._reverse === !isReverse && component.repeatCounter > 0) { component.forward = isReverse; this.repeatAnimation(component); return } if (component._reverse !== isReverse && component.repeatCounter === 0) { this.completeAnimation(component); return } component.forward = isReverse; var frame = isReverse ? component.currentFrame.nextFrame : component.currentFrame.prevFrame; this.updateAndGetNextTick(component, frame) }, getLastFrame: function() { return this.frames[this.frames.length - 1] }, previousFrame: function(component) { var frame = component.currentFrame; if (frame.isFirst) { if (component._yoyo) { this.handleYoyoFrame(component, true) } else if (component.repeatCounter > 0) { if (component._reverse && !component.forward) { component.currentFrame = this.getLastFrame(); this.repeatAnimation(component) } else { component.forward = true; this.repeatAnimation(component) } } else { this.completeAnimation(component) } } else { this.updateAndGetNextTick(component, frame.prevFrame) } }, updateAndGetNextTick: function(component, frame) { component.updateFrame(frame); this.getNextTick(component) }, removeFrame: function(frame) { var index = this.frames.indexOf(frame); if (index !== -1) { this.removeFrameAt(index) } return this }, removeFrameAt: function(index) { this.frames.splice(index, 1); this.updateFrameSequence(); return this }, repeatAnimation: function(component) { if (component._pendingStop === 2) { return this.completeAnimation(component) } if (component._repeatDelay > 0 && component.pendingRepeat === false) { component.pendingRepeat = true; component.accumulator -= component.nextTick; component.nextTick += component._repeatDelay } else { component.repeatCounter--; component.updateFrame(component.currentFrame[component.forward ? "nextFrame" : "prevFrame"]); if (component.isPlaying) { this.getNextTick(component); component.pendingRepeat = false; component.parent.emit("animationrepeat", this, component.currentFrame, component.repeatCounter, component.parent) } } }, setFrame: function(component) { if (component.forward) { this.nextFrame(component) } else { this.previousFrame(component) } }, toJSON: function() { var output = { key: this.key, type: this.type, frames: [], frameRate: this.frameRate, duration: this.duration, skipMissedFrames: this.skipMissedFrames, delay: this.delay, repeat: this.repeat, repeatDelay: this.repeatDelay, yoyo: this.yoyo, showOnStart: this.showOnStart, hideOnComplete: this.hideOnComplete }; this.frames.forEach(function(frame) { output.frames.push(frame.toJSON()) }); return output }, updateFrameSequence: function() { var len = this.frames.length; var slice = 1 / (len - 1); for (var i = 0; i < len; i++) { var frame = this.frames[i]; frame.index = i + 1; frame.isFirst = false; frame.isLast = false; frame.progress = i * slice; if (i === 0) { frame.isFirst = true; frame.isLast = len === 1; frame.prevFrame = this.frames[len - 1]; frame.nextFrame = this.frames[i + 1] } else if (i === len - 1) { frame.isLast = true; frame.prevFrame = this.frames[len - 2]; frame.nextFrame = this.frames[0] } else if (len > 1) { frame.prevFrame = this.frames[i - 1]; frame.nextFrame = this.frames[i + 1] } } return this }, pause: function() { this.paused = true; return this }, resume: function() { this.paused = false; return this }, destroy: function() { this.manager.off("pauseall", this.pause, this); this.manager.off("resumeall", this.resume, this); this.manager.remove(this.key); for (var i = 0; i < this.frames.length; i++) { this.frames[i].destroy() } this.frames = []; this.manager = null } }); module.exports = Animation }, function(module, exports) { var FindClosestInSorted = function(value, array, key) { if (!array.length) { return NaN } else if (array.length === 1) { return array[0] } var i = 1; var low; var high; if (key) { if (value < array[0][key]) { return array[0] } while (array[i][key] < value) { i++ } } else { while (array[i] < value) { i++ } } if (i > array.length) { i = array.length } if (key) { low = array[i - 1][key]; high = array[i][key]; return high - value <= value - low ? array[i] : array[i - 1] } else { low = array[i - 1]; high = array[i]; return high - value <= value - low ? high : low } }; module.exports = FindClosestInSorted }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var AnimationFrame = new Class({ initialize: function AnimationFrame(textureKey, textureFrame, index, frame) { this.textureKey = textureKey; this.textureFrame = textureFrame; this.index = index; this.frame = frame; this.isFirst = false; this.isLast = false; this.prevFrame = null; this.nextFrame = null; this.duration = 0; this.progress = 0 }, toJSON: function() { return { key: this.textureKey, frame: this.textureFrame, duration: this.duration } }, destroy: function() { this.frame = undefined } }); module.exports = AnimationFrame }, function(module, exports, __webpack_require__) { var Animation = __webpack_require__(259); var Class = __webpack_require__(0); var CustomMap = __webpack_require__(157); var EventEmitter = __webpack_require__(11); var GetValue = __webpack_require__(4); var Pad = __webpack_require__(158); var AnimationManager = new Class({ Extends: EventEmitter, initialize: function AnimationManager(game) { EventEmitter.call(this); this.game = game; this.textureManager = null; this.globalTimeScale = 1; this.anims = new CustomMap; this.paused = false; this.name = "AnimationManager"; game.events.once("boot", this.boot, this) }, boot: function() { this.textureManager = this.game.textures; this.game.events.once("destroy", this.destroy, this) }, add: function(key, animation) { if (this.anims.has(key)) { console.warn("Animation with key", key, "already exists"); return } animation.key = key; this.anims.set(key, animation); this.emit("add", key, animation); return this }, create: function(config) { var key = config.key; if (!key || this.anims.has(key)) { console.warn("Invalid Animation Key, or Key already in use: " + key); return } var anim = new Animation(this, key, config); this.anims.set(key, anim); this.emit("add", key, anim); return anim }, fromJSON: function(data, clearCurrentAnimations) { if (clearCurrentAnimations === undefined) { clearCurrentAnimations = false } if (clearCurrentAnimations) { this.anims.clear() } if (typeof data === "string") { data = JSON.parse(data) } var output = []; if (data.hasOwnProperty("anims") && Array.isArray(data.anims)) { for (var i = 0; i < data.anims.length; i++) { output.push(this.create(data.anims[i])) } if (data.hasOwnProperty("globalTimeScale")) { this.globalTimeScale = data.globalTimeScale } } else if (data.hasOwnProperty("key") && data.type === "frame") { output.push(this.create(data)) } return output }, generateFrameNames: function(key, config) { var prefix = GetValue(config, "prefix", ""); var start = GetValue(config, "start", 0); var end = GetValue(config, "end", 0); var suffix = GetValue(config, "suffix", ""); var zeroPad = GetValue(config, "zeroPad", 0); var out = GetValue(config, "outputArray", []); var frames = GetValue(config, "frames", false); var texture = this.textureManager.get(key); if (!texture) { return out } var diff = start < end ? 1 : -1; end += diff; var i; var frame; if (!config) { frames = texture.getFrameNames(); for (i = 0; i < frames.length; i++) { out.push({ key: key, frame: frames[i] }) } } else if (Array.isArray(frames)) { for (i = 0; i < frames.length; i++) { frame = prefix + Pad(frames[i], zeroPad, "0", 1) + suffix; if (texture.has(frame)) { out.push({ key: key, frame: frame }) } } } else { for (i = start; i !== end; i += diff) { frame = prefix + Pad(i, zeroPad, "0", 1) + suffix; if (texture.has(frame)) { out.push({ key: key, frame: frame }) } } } return out }, generateFrameNumbers: function(key, config) { var startFrame = GetValue(config, "start", 0); var endFrame = GetValue(config, "end", -1); var firstFrame = GetValue(config, "first", false); var out = GetValue(config, "outputArray", []); var frames = GetValue(config, "frames", false); var texture = this.textureManager.get(key); if (!texture) { return out } if (firstFrame && texture.has(firstFrame)) { out.push({ key: key, frame: firstFrame }) } var i; if (Array.isArray(frames)) { for (i = 0; i < frames.length; i++) { if (texture.has(frames[i])) { out.push({ key: key, frame: frames[i] }) } } } else { if (endFrame === -1) { endFrame = texture.frameTotal } for (i = startFrame; i <= endFrame; i++) { if (texture.has(i)) { out.push({ key: key, frame: i }) } } } return out }, get: function(key) { return this.anims.get(key) }, load: function(child, key, startFrame) { var anim = this.get(key); if (anim) { anim.load(child, startFrame) } return child }, pauseAll: function() { if (!this.paused) { this.paused = true; this.emit("pauseall") } return this }, play: function(key, child) { if (!Array.isArray(child)) { child = [child] } var anim = this.get(key); if (!anim) { return } for (var i = 0; i < child.length; i++) { child[i].anims.play(key) } return this }, remove: function(key) { var anim = this.get(key); if (anim) { this.emit("remove", key, anim); this.anims.delete(key) } return anim }, resumeAll: function() { if (this.paused) { this.paused = false; this.emit("resumeall") } return this }, staggerPlay: function(key, children, stagger) { if (stagger === undefined) { stagger = 0 } if (!Array.isArray(children)) { children = [children] } var anim = this.get(key); if (!anim) { return } for (var i = 0; i < children.length; i++) { children[i].anims.delayedPlay(stagger * i, key) } return this }, toJSON: function(key) { if (key !== undefined && key !== "") { return this.anims.get(key).toJSON() } else { var output = { anims: [], globalTimeScale: this.globalTimeScale }; this.anims.each(function(animationKey, animation) { output.anims.push(animation.toJSON()) }); return output } }, destroy: function() { this.anims.clear(); this.textureManager = null; this.game = null } }); module.exports = AnimationManager }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var CustomMap = __webpack_require__(157); var EventEmitter = __webpack_require__(11); var BaseCache = new Class({ initialize: function BaseCache() { this.entries = new CustomMap; this.events = new EventEmitter }, add: function(key, data) { this.entries.set(key, data); this.events.emit("add", this, key, data); return this }, has: function(key) { return this.entries.has(key) }, exists: function(key) { return this.entries.has(key) }, get: function(key) { return this.entries.get(key) }, remove: function(key) { var entry = this.get(key); if (entry) { this.entries.delete(key); this.events.emit("remove", this, key, entry.data) } return this }, destroy: function() { this.entries.clear(); this.events.removeAllListeners(); this.entries = null; this.events = null } }); module.exports = BaseCache }, function(module, exports, __webpack_require__) { var BaseCache = __webpack_require__(263); var Class = __webpack_require__(0); var CacheManager = new Class({ initialize: function CacheManager(game) { this.game = game; this.binary = new BaseCache; this.bitmapFont = new BaseCache; this.json = new BaseCache; this.physics = new BaseCache; this.shader = new BaseCache; this.audio = new BaseCache; this.text = new BaseCache; this.html = new BaseCache; this.obj = new BaseCache; this.tilemap = new BaseCache; this.xml = new BaseCache; this.custom = {}; this.game.events.once("destroy", this.destroy, this) }, addCustom: function(key) { if (!this.custom.hasOwnProperty(key)) { this.custom[key] = new BaseCache } return this.custom[key] }, destroy: function() { var keys = ["binary", "bitmapFont", "json", "physics", "shader", "audio", "text", "html", "obj", "tilemap", "xml"]; for (var i = 0; i < keys.length; i++) { this[keys[i]].destroy(); this[keys[i]] = null } for (var key in this.custom) { this.custom[key].destroy() } this.custom = null; this.game = null } }); module.exports = CacheManager }, function(module, exports, __webpack_require__) { var BaseCamera = __webpack_require__(111); var CanvasPool = __webpack_require__(28); var CenterOn = __webpack_require__(162); var Clamp = __webpack_require__(23); var Class = __webpack_require__(0); var Components = __webpack_require__(14); var Effects = __webpack_require__(273); var Linear = __webpack_require__(113); var Rectangle = __webpack_require__(9); var Vector2 = __webpack_require__(3); var Camera = new Class({ Extends: BaseCamera, Mixins: [Components.Flip, Components.Tint], initialize: function Camera(x, y, width, height) { BaseCamera.call(this, x, y, width, height); this.inputEnabled = true; this.fadeEffect = new Effects.Fade(this); this.flashEffect = new Effects.Flash(this); this.shakeEffect = new Effects.Shake(this); this.panEffect = new Effects.Pan(this); this.zoomEffect = new Effects.Zoom(this); this.lerp = new Vector2(1, 1); this.followOffset = new Vector2; this.deadzone = null; this._follow = null; this.renderToTexture = false; this.canvas = null; this.context = null; this.glTexture = null; this.framebuffer = null; this.pipeline = null }, setRenderToTexture: function(pipeline) { var renderer = this.scene.sys.game.renderer; if (renderer.gl) { this.glTexture = renderer.createTextureFromSource(null, this.width, this.height, 0); this.framebuffer = renderer.createFramebuffer(this.width, this.height, this.glTexture, false) } else { this.canvas = CanvasPool.create2D(this, this.width, this.height); this.context = this.canvas.getContext("2d") } this.renderToTexture = true; if (pipeline) { this.setPipeline(pipeline) } return this }, setPipeline: function(pipeline) { if (typeof pipeline === "string") { var renderer = this.scene.sys.game.renderer; if (renderer.gl && renderer.hasPipeline(pipeline)) { this.pipeline = renderer.getPipeline(pipeline) } } else { this.pipeline = pipeline } return this }, clearRenderToTexture: function() { var renderer = this.scene.sys.game.renderer; if (renderer.gl) { if (this.framebuffer) { renderer.deleteFramebuffer(this.framebuffer) } if (this.glTexture) { renderer.deleteTexture(this.glTexture) } this.framebuffer = null; this.glTexture = null; this.pipeline = null } else { CanvasPool.remove(this); this.canvas = null; this.context = null } this.renderToTexture = false; return this }, setDeadzone: function(width, height) { if (width === undefined) { this.deadzone = null } else { if (this.deadzone) { this.deadzone.width = width; this.deadzone.height = height } else { this.deadzone = new Rectangle(0, 0, width, height) } if (this._follow) { var originX = this.width / 2; var originY = this.height / 2; var fx = this._follow.x - this.followOffset.x; var fy = this._follow.y - this.followOffset.y; this.midPoint.set(fx, fy); this.scrollX = fx - originX; this.scrollY = fy - originY } CenterOn(this.deadzone, this.midPoint.x, this.midPoint.y) } return this }, fadeIn: function(duration, red, green, blue, callback, context) { return this.fadeEffect.start(false, duration, red, green, blue, true, callback, context) }, fadeOut: function(duration, red, green, blue, callback, context) { return this.fadeEffect.start(true, duration, red, green, blue, true, callback, context) }, fadeFrom: function(duration, red, green, blue, force, callback, context) { return this.fadeEffect.start(false, duration, red, green, blue, force, callback, context) }, fade: function(duration, red, green, blue, force, callback, context) { return this.fadeEffect.start(true, duration, red, green, blue, force, callback, context) }, flash: function(duration, red, green, blue, force, callback, context) { return this.flashEffect.start(duration, red, green, blue, force, callback, context) }, shake: function(duration, intensity, force, callback, context) { return this.shakeEffect.start(duration, intensity, force, callback, context) }, pan: function(x, y, duration, ease, force, callback, context) { return this.panEffect.start(x, y, duration, ease, force, callback, context) }, zoomTo: function(zoom, duration, ease, force, callback, context) { return this.zoomEffect.start(zoom, duration, ease, force, callback, context) }, preRender: function(baseScale, resolution) { var width = this.width; var height = this.height; var halfWidth = width * .5; var halfHeight = height * .5; var zoom = this.zoom * baseScale; var matrix = this.matrix; var originX = width * this.originX; var originY = height * this.originY; var follow = this._follow; var deadzone = this.deadzone; var sx = this.scrollX; var sy = this.scrollY; if (deadzone) { CenterOn(deadzone, this.midPoint.x, this.midPoint.y) } if (follow) { var fx = follow.x - this.followOffset.x; var fy = follow.y - this.followOffset.y; if (deadzone) { if (fx < deadzone.x) { sx = Linear(sx, sx - (deadzone.x - fx), this.lerp.x) } else if (fx > deadzone.right) { sx = Linear(sx, sx + (fx - deadzone.right), this.lerp.x) } if (fy < deadzone.y) { sy = Linear(sy, sy - (deadzone.y - fy), this.lerp.y) } else if (fy > deadzone.bottom) { sy = Linear(sy, sy + (fy - deadzone.bottom), this.lerp.y) } } else { sx = Linear(sx, fx - originX, this.lerp.x); sy = Linear(sy, fy - originY, this.lerp.y) } } if (this.useBounds) { sx = this.clampX(sx); sy = this.clampY(sy) } if (this.roundPixels) { originX = Math.round(originX); originY = Math.round(originY) } this.scrollX = sx; this.scrollY = sy; var midX = sx + halfWidth; var midY = sy + halfHeight; this.midPoint.set(midX, midY); var displayWidth = width / zoom; var displayHeight = height / zoom; this.worldView.setTo(midX - displayWidth / 2, midY - displayHeight / 2, displayWidth, displayHeight); matrix.loadIdentity(); matrix.scale(resolution, resolution); matrix.translate(this.x + originX, this.y + originY); matrix.rotate(this.rotation); matrix.scale(zoom, zoom); matrix.translate(-originX, -originY); this.shakeEffect.preRender() }, setLerp: function(x, y) { if (x === undefined) { x = 1 } if (y === undefined) { y = x } this.lerp.set(x, y); return this }, setFollowOffset: function(x, y) { if (x === undefined) { x = 0 } if (y === undefined) { y = 0 } this.followOffset.set(x, y); return this }, startFollow: function(target, roundPixels, lerpX, lerpY, offsetX, offsetY) { if (roundPixels === undefined) { roundPixels = false } if (lerpX === undefined) { lerpX = 1 } if (lerpY === undefined) { lerpY = lerpX } if (offsetX === undefined) { offsetX = 0 } if (offsetY === undefined) { offsetY = offsetX } this._follow = target; this.roundPixels = roundPixels; lerpX = Clamp(lerpX, 0, 1); lerpY = Clamp(lerpY, 0, 1); this.lerp.set(lerpX, lerpY); this.followOffset.set(offsetX, offsetY); var originX = this.width / 2; var originY = this.height / 2; var fx = target.x - offsetX; var fy = target.y - offsetY; this.midPoint.set(fx, fy); this.scrollX = fx - originX; this.scrollY = fy - originY; return this }, stopFollow: function() { this._follow = null; return this }, resetFX: function() { this.panEffect.reset(); this.shakeEffect.reset(); this.flashEffect.reset(); this.fadeEffect.reset(); return this }, update: function(time, delta) { if (this.visible) { this.panEffect.update(time, delta); this.zoomEffect.update(time, delta); this.shakeEffect.update(time, delta); this.flashEffect.update(time, delta); this.fadeEffect.update(time, delta) } }, destroy: function() { this.clearRenderToTexture(); this.resetFX(); BaseCamera.prototype.destroy.call(this); this._follow = null; this.deadzone = null } }); module.exports = Camera }, function(module, exports, __webpack_require__) { var Color = __webpack_require__(49); var HexStringToColor = function(hex) { var color = new Color; hex = hex.replace(/^(?:#|0x)?([a-f\d])([a-f\d])([a-f\d])$/i, function(m, r, g, b) { return r + r + g + g + b + b }); var result = /^(?:#|0x)?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); if (result) { var r = parseInt(result[1], 16); var g = parseInt(result[2], 16); var b = parseInt(result[3], 16); color.setTo(r, g, b) } return color }; module.exports = HexStringToColor }, function(module, exports) { var GetColor32 = function(red, green, blue, alpha) { return alpha << 24 | red << 16 | green << 8 | blue }; module.exports = GetColor32 }, function(module, exports) { var RGBToHSV = function(r, g, b, out) { if (out === undefined) { out = { h: 0, s: 0, v: 0 } } r /= 255; g /= 255; b /= 255; var min = Math.min(r, g, b); var max = Math.max(r, g, b); var d = max - min; var h = 0; var s = max === 0 ? 0 : d / max; var v = max; if (max !== min) { if (max === r) { h = (g - b) / d + (g < b ? 6 : 0) } else if (max === g) { h = (b - r) / d + 2 } else if (max === b) { h = (r - g) / d + 4 } h /= 6 } if (out.hasOwnProperty("_h")) { out._h = h; out._s = s; out._v = v } else { out.h = h; out.s = s; out.v = v } return out }; module.exports = RGBToHSV }, function(module, exports, __webpack_require__) { var Color = __webpack_require__(49); var IntegerToRGB = __webpack_require__(270); var IntegerToColor = function(input) { var rgb = IntegerToRGB(input); return new Color(rgb.r, rgb.g, rgb.b, rgb.a) }; module.exports = IntegerToColor }, function(module, exports) { var IntegerToRGB = function(color) { if (color > 16777215) { return { a: color >>> 24, r: color >> 16 & 255, g: color >> 8 & 255, b: color & 255 } } else { return { a: 255, r: color >> 16 & 255, g: color >> 8 & 255, b: color & 255 } } }; module.exports = IntegerToRGB }, function(module, exports, __webpack_require__) { var Color = __webpack_require__(49); var ObjectToColor = function(input) { return new Color(input.r, input.g, input.b, input.a) }; module.exports = ObjectToColor }, function(module, exports, __webpack_require__) { var Color = __webpack_require__(49); var RGBStringToColor = function(rgb) { var color = new Color; var result = /^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?))?\s*\)$/.exec(rgb.toLowerCase()); if (result) { var r = parseInt(result[1], 10); var g = parseInt(result[2], 10); var b = parseInt(result[3], 10); var a = result[4] !== undefined ? parseFloat(result[4]) : 1; color.setTo(r, g, b, a * 255) } return color }; module.exports = RGBStringToColor }, function(module, exports, __webpack_require__) { module.exports = { Fade: __webpack_require__(548), Flash: __webpack_require__(549), Pan: __webpack_require__(550), Shake: __webpack_require__(583), Zoom: __webpack_require__(584) } }, function(module, exports, __webpack_require__) { module.exports = { In: __webpack_require__(551), Out: __webpack_require__(552), InOut: __webpack_require__(553) } }, function(module, exports, __webpack_require__) { module.exports = { In: __webpack_require__(554), Out: __webpack_require__(555), InOut: __webpack_require__(556) } }, function(module, exports, __webpack_require__) { module.exports = { In: __webpack_require__(557), Out: __webpack_require__(558), InOut: __webpack_require__(559) } }, function(module, exports, __webpack_require__) { module.exports = { In: __webpack_require__(560), Out: __webpack_require__(561), InOut: __webpack_require__(562) } }, function(module, exports, __webpack_require__) { module.exports = { In: __webpack_require__(563), Out: __webpack_require__(564), InOut: __webpack_require__(565) } }, function(module, exports, __webpack_require__) { module.exports = { In: __webpack_require__(566), Out: __webpack_require__(567), InOut: __webpack_require__(568) } }, function(module, exports, __webpack_require__) { module.exports = __webpack_require__(569) }, function(module, exports, __webpack_require__) { module.exports = { In: __webpack_require__(570), Out: __webpack_require__(571), InOut: __webpack_require__(572) } }, function(module, exports, __webpack_require__) { module.exports = { In: __webpack_require__(573), Out: __webpack_require__(574), InOut: __webpack_require__(575) } }, function(module, exports, __webpack_require__) { module.exports = { In: __webpack_require__(576), Out: __webpack_require__(577), InOut: __webpack_require__(578) } }, function(module, exports, __webpack_require__) { module.exports = { In: __webpack_require__(579), Out: __webpack_require__(580), InOut: __webpack_require__(581) } }, function(module, exports, __webpack_require__) { module.exports = __webpack_require__(582) }, function(module, exports, __webpack_require__) { var Arne16 = __webpack_require__(287); var CanvasPool = __webpack_require__(28); var GetValue = __webpack_require__(4); var GenerateTexture = function(config) { var data = GetValue(config, "data", []); var canvas = GetValue(config, "canvas", null); var palette = GetValue(config, "palette", Arne16); var pixelWidth = GetValue(config, "pixelWidth", 1); var pixelHeight = GetValue(config, "pixelHeight", pixelWidth); var resizeCanvas = GetValue(config, "resizeCanvas", true); var clearCanvas = GetValue(config, "clearCanvas", true); var preRender = GetValue(config, "preRender", null); var postRender = GetValue(config, "postRender", null); var width = Math.floor(Math.abs(data[0].length * pixelWidth)); var height = Math.floor(Math.abs(data.length * pixelHeight)); if (!canvas) { canvas = CanvasPool.create2D(this, width, height); resizeCanvas = false; clearCanvas = false } if (resizeCanvas) { canvas.width = width; canvas.height = height } var ctx = canvas.getContext("2d"); if (clearCanvas) { ctx.clearRect(0, 0, width, height) } if (preRender) { preRender(canvas, ctx) } for (var y = 0; y < data.length; y++) { var row = data[y]; for (var x = 0; x < row.length; x++) { var d = row[x]; if (d !== "." && d !== " ") { ctx.fillStyle = palette[d]; ctx.fillRect(x * pixelWidth, y * pixelHeight, pixelWidth, pixelHeight) } } } if (postRender) { postRender(canvas, ctx) } return canvas }; module.exports = GenerateTexture }, function(module, exports) { module.exports = { 0: "#000", 1: "#9D9D9D", 2: "#FFF", 3: "#BE2633", 4: "#E06F8B", 5: "#493C2B", 6: "#A46422", 7: "#EB8931", 8: "#F7E26B", 9: "#2F484E", A: "#44891A", B: "#A3CE27", C: "#1B2632", D: "#005784", E: "#31A2F2", F: "#B2DCEF" } }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var CubicBezier = __webpack_require__(289); var Curve = __webpack_require__(79); var Vector2 = __webpack_require__(3); var CubicBezierCurve = new Class({ Extends: Curve, initialize: function CubicBezierCurve(p0, p1, p2, p3) { Curve.call(this, "CubicBezierCurve"); if (Array.isArray(p0)) { p3 = new Vector2(p0[6], p0[7]); p2 = new Vector2(p0[4], p0[5]); p1 = new Vector2(p0[2], p0[3]); p0 = new Vector2(p0[0], p0[1]) } this.p0 = p0; this.p1 = p1; this.p2 = p2; this.p3 = p3 }, getStartPoint: function(out) { if (out === undefined) { out = new Vector2 } return out.copy(this.p0) }, getResolution: function(divisions) { return divisions }, getPoint: function(t, out) { if (out === undefined) { out = new Vector2 } var p0 = this.p0; var p1 = this.p1; var p2 = this.p2; var p3 = this.p3; return out.set(CubicBezier(t, p0.x, p1.x, p2.x, p3.x), CubicBezier(t, p0.y, p1.y, p2.y, p3.y)) }, draw: function(graphics, pointsTotal) { if (pointsTotal === undefined) { pointsTotal = 32 } var points = this.getPoints(pointsTotal); graphics.beginPath(); graphics.moveTo(this.p0.x, this.p0.y); for (var i = 1; i < points.length; i++) { graphics.lineTo(points[i].x, points[i].y) } graphics.strokePath(); return graphics }, toJSON: function() { return { type: this.type, points: [this.p0.x, this.p0.y, this.p1.x, this.p1.y, this.p2.x, this.p2.y, this.p3.x, this.p3.y] } } }); CubicBezierCurve.fromJSON = function(data) { var points = data.points; var p0 = new Vector2(points[0], points[1]); var p1 = new Vector2(points[2], points[3]); var p2 = new Vector2(points[4], points[5]); var p3 = new Vector2(points[6], points[7]); return new CubicBezierCurve(p0, p1, p2, p3) }; module.exports = CubicBezierCurve }, function(module, exports) { function P0(t, p) { var k = 1 - t; return k * k * k * p } function P1(t, p) { var k = 1 - t; return 3 * k * k * t * p } function P2(t, p) { return 3 * (1 - t) * t * t * p } function P3(t, p) { return t * t * t * p } var CubicBezierInterpolation = function(t, p0, p1, p2, p3) { return P0(t, p0) + P1(t, p1) + P2(t, p2) + P3(t, p3) }; module.exports = CubicBezierInterpolation }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Curve = __webpack_require__(79); var DegToRad = __webpack_require__(36); var GetValue = __webpack_require__(4); var RadToDeg = __webpack_require__(165); var Vector2 = __webpack_require__(3); var EllipseCurve = new Class({ Extends: Curve, initialize: function EllipseCurve(x, y, xRadius, yRadius, startAngle, endAngle, clockwise, rotation) { if (typeof x === "object") { var config = x; x = GetValue(config, "x", 0); y = GetValue(config, "y", 0); xRadius = GetValue(config, "xRadius", 0); yRadius = GetValue(config, "yRadius", xRadius); startAngle = GetValue(config, "startAngle", 0); endAngle = GetValue(config, "endAngle", 360); clockwise = GetValue(config, "clockwise", false); rotation = GetValue(config, "rotation", 0) } else { if (yRadius === undefined) { yRadius = xRadius } if (startAngle === undefined) { startAngle = 0 } if (endAngle === undefined) { endAngle = 360 } if (clockwise === undefined) { clockwise = false } if (rotation === undefined) { rotation = 0 } } Curve.call(this, "EllipseCurve"); this.p0 = new Vector2(x, y); this._xRadius = xRadius; this._yRadius = yRadius; this._startAngle = DegToRad(startAngle); this._endAngle = DegToRad(endAngle); this._clockwise = clockwise; this._rotation = DegToRad(rotation) }, getStartPoint: function(out) { if (out === undefined) { out = new Vector2 } return this.getPoint(0, out) }, getResolution: function(divisions) { return divisions * 2 }, getPoint: function(t, out) { if (out === undefined) { out = new Vector2 } var twoPi = Math.PI * 2; var deltaAngle = this._endAngle - this._startAngle; var samePoints = Math.abs(deltaAngle) < Number.EPSILON; while (deltaAngle < 0) { deltaAngle += twoPi } while (deltaAngle > twoPi) { deltaAngle -= twoPi } if (deltaAngle < Number.EPSILON) { if (samePoints) { deltaAngle = 0 } else { deltaAngle = twoPi } } if (this._clockwise && !samePoints) { if (deltaAngle === twoPi) { deltaAngle = -twoPi } else { deltaAngle = deltaAngle - twoPi } } var angle = this._startAngle + t * deltaAngle; var x = this.p0.x + this._xRadius * Math.cos(angle); var y = this.p0.y + this._yRadius * Math.sin(angle); if (this._rotation !== 0) { var cos = Math.cos(this._rotation); var sin = Math.sin(this._rotation); var tx = x - this.p0.x; var ty = y - this.p0.y; x = tx * cos - ty * sin + this.p0.x; y = tx * sin + ty * cos + this.p0.y } return out.set(x, y) }, setXRadius: function(value) { this.xRadius = value; return this }, setYRadius: function(value) { this.yRadius = value; return this }, setWidth: function(value) { this.xRadius = value * 2; return this }, setHeight: function(value) { this.yRadius = value * 2; return this }, setStartAngle: function(value) { this.startAngle = value; return this }, setEndAngle: function(value) { this.endAngle = value; return this }, setClockwise: function(value) { this.clockwise = value; return this }, setRotation: function(value) { this.rotation = value; return this }, x: { get: function() { return this.p0.x }, set: function(value) { this.p0.x = value } }, y: { get: function() { return this.p0.y }, set: function(value) { this.p0.y = value } }, xRadius: { get: function() { return this._xRadius }, set: function(value) { this._xRadius = value } }, yRadius: { get: function() { return this._yRadius }, set: function(value) { this._yRadius = value } }, startAngle: { get: function() { return RadToDeg(this._startAngle) }, set: function(value) { this._startAngle = DegToRad(value) } }, endAngle: { get: function() { return RadToDeg(this._endAngle) }, set: function(value) { this._endAngle = DegToRad(value) } }, clockwise: { get: function() { return this._clockwise }, set: function(value) { this._clockwise = value } }, angle: { get: function() { return RadToDeg(this._rotation) }, set: function(value) { this._rotation = DegToRad(value) } }, rotation: { get: function() { return this._rotation }, set: function(value) { this._rotation = value } }, toJSON: function() { return { type: this.type, x: this.p0.x, y: this.p0.y, xRadius: this._xRadius, yRadius: this._yRadius, startAngle: RadToDeg(this._startAngle), endAngle: RadToDeg(this._endAngle), clockwise: this._clockwise, rotation: RadToDeg(this._rotation) } } }); EllipseCurve.fromJSON = function(data) { return new EllipseCurve(data) }; module.exports = EllipseCurve }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Curve = __webpack_require__(79); var FromPoints = __webpack_require__(164); var Rectangle = __webpack_require__(9); var Vector2 = __webpack_require__(3); var tmpVec2 = new Vector2; var LineCurve = new Class({ Extends: Curve, initialize: function LineCurve(p0, p1) { Curve.call(this, "LineCurve"); if (Array.isArray(p0)) { p1 = new Vector2(p0[2], p0[3]); p0 = new Vector2(p0[0], p0[1]) } this.p0 = p0; this.p1 = p1 }, getBounds: function(out) { if (out === undefined) { out = new Rectangle } return FromPoints([this.p0, this.p1], out) }, getStartPoint: function(out) { if (out === undefined) { out = new Vector2 } return out.copy(this.p0) }, getResolution: function(divisions) { if (divisions === undefined) { divisions = 1 } return divisions }, getPoint: function(t, out) { if (out === undefined) { out = new Vector2 } if (t === 1) { return out.copy(this.p1) } out.copy(this.p1).subtract(this.p0).scale(t).add(this.p0); return out }, getPointAt: function(u, out) { return this.getPoint(u, out) }, getTangent: function() { var tangent = tmpVec2.copy(this.p1).subtract(this.p0); return tangent.normalize() }, draw: function(graphics) { graphics.lineBetween(this.p0.x, this.p0.y, this.p1.x, this.p1.y); return graphics }, toJSON: function() { return { type: this.type, points: [this.p0.x, this.p0.y, this.p1.x, this.p1.y] } } }); LineCurve.fromJSON = function(data) { var points = data.points; var p0 = new Vector2(points[0], points[1]); var p1 = new Vector2(points[2], points[3]); return new LineCurve(p0, p1) }; module.exports = LineCurve }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Curve = __webpack_require__(79); var QuadraticBezierInterpolation = __webpack_require__(293); var Vector2 = __webpack_require__(3); var QuadraticBezier = new Class({ Extends: Curve, initialize: function QuadraticBezier(p0, p1, p2) { Curve.call(this, "QuadraticBezier"); if (Array.isArray(p0)) { p2 = new Vector2(p0[4], p0[5]); p1 = new Vector2(p0[2], p0[3]); p0 = new Vector2(p0[0], p0[1]) } this.p0 = p0; this.p1 = p1; this.p2 = p2 }, getStartPoint: function(out) { if (out === undefined) { out = new Vector2 } return out.copy(this.p0) }, getResolution: function(divisions) { return divisions }, getPoint: function(t, out) { if (out === undefined) { out = new Vector2 } var p0 = this.p0; var p1 = this.p1; var p2 = this.p2; return out.set(QuadraticBezierInterpolation(t, p0.x, p1.x, p2.x), QuadraticBezierInterpolation(t, p0.y, p1.y, p2.y)) }, draw: function(graphics, pointsTotal) { if (pointsTotal === undefined) { pointsTotal = 32 } var points = this.getPoints(pointsTotal); graphics.beginPath(); graphics.moveTo(this.p0.x, this.p0.y); for (var i = 1; i < points.length; i++) { graphics.lineTo(points[i].x, points[i].y) } graphics.strokePath(); return graphics }, toJSON: function() { return { type: this.type, points: [this.p0.x, this.p0.y, this.p1.x, this.p1.y, this.p2.x, this.p2.y] } } }); QuadraticBezier.fromJSON = function(data) { var points = data.points; var p0 = new Vector2(points[0], points[1]); var p1 = new Vector2(points[2], points[3]); var p2 = new Vector2(points[4], points[5]); return new QuadraticBezier(p0, p1, p2) }; module.exports = QuadraticBezier }, function(module, exports) { function P0(t, p) { var k = 1 - t; return k * k * p } function P1(t, p) { return 2 * (1 - t) * t * p } function P2(t, p) { return t * t * p } var QuadraticBezierInterpolation = function(t, p0, p1, p2) { return P0(t, p0) + P1(t, p1) + P2(t, p2) }; module.exports = QuadraticBezierInterpolation }, function(module, exports, __webpack_require__) { var CatmullRom = __webpack_require__(166); var Class = __webpack_require__(0); var Curve = __webpack_require__(79); var Vector2 = __webpack_require__(3); var SplineCurve = new Class({ Extends: Curve, initialize: function SplineCurve(points) { if (points === undefined) { points = [] } Curve.call(this, "SplineCurve"); this.points = []; this.addPoints(points) }, addPoints: function(points) { for (var i = 0; i < points.length; i++) { var p = new Vector2; if (typeof points[i] === "number") { p.x = points[i]; p.y = points[i + 1]; i++ } else if (Array.isArray(points[i])) { p.x = points[i][0]; p.y = points[i][1] } else { p.x = points[i].x; p.y = points[i].y } this.points.push(p) } return this }, addPoint: function(x, y) { var vec = new Vector2(x, y); this.points.push(vec); return vec }, getStartPoint: function(out) { if (out === undefined) { out = new Vector2 } return out.copy(this.points[0]) }, getResolution: function(divisions) { return divisions * this.points.length }, getPoint: function(t, out) { if (out === undefined) { out = new Vector2 } var points = this.points; var point = (points.length - 1) * t; var intPoint = Math.floor(point); var weight = point - intPoint; var p0 = points[intPoint === 0 ? intPoint : intPoint - 1]; var p1 = points[intPoint]; var p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1]; var p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2]; return out.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y)) }, toJSON: function() { var points = []; for (var i = 0; i < this.points.length; i++) { points.push(this.points[i].x); points.push(this.points[i].y) } return { type: this.type, points: points } } }); SplineCurve.fromJSON = function(data) { return new SplineCurve(data.points) }; module.exports = SplineCurve }, function(module, exports) { var CanvasInterpolation = { setCrisp: function(canvas) { var types = ["optimizeSpeed", "crisp-edges", "-moz-crisp-edges", "-webkit-optimize-contrast", "optimize-contrast", "pixelated"]; types.forEach(function(type) { canvas.style["image-rendering"] = type }); canvas.style.msInterpolationMode = "nearest-neighbor"; return canvas }, setBicubic: function(canvas) { canvas.style["image-rendering"] = "auto"; canvas.style.msInterpolationMode = "bicubic"; return canvas } }; module.exports = CanvasInterpolation }, function(module, exports, __webpack_require__) { var Color = __webpack_require__(49); Color.ColorToRGBA = __webpack_require__(619); Color.ComponentToHex = __webpack_require__(297); Color.GetColor = __webpack_require__(160); Color.GetColor32 = __webpack_require__(267); Color.HexStringToColor = __webpack_require__(266); Color.HSLToColor = __webpack_require__(620); Color.HSVColorWheel = __webpack_require__(621); Color.HSVToRGB = __webpack_require__(161); Color.HueToComponent = __webpack_require__(298); Color.IntegerToColor = __webpack_require__(269); Color.IntegerToRGB = __webpack_require__(270); Color.Interpolate = __webpack_require__(622); Color.ObjectToColor = __webpack_require__(271); Color.RandomRGB = __webpack_require__(623); Color.RGBStringToColor = __webpack_require__(272); Color.RGBToHSV = __webpack_require__(268); Color.RGBToString = __webpack_require__(624); Color.ValueToColor = __webpack_require__(159); module.exports = Color }, function(module, exports) { var ComponentToHex = function(color) { var hex = color.toString(16); return hex.length === 1 ? "0" + hex : hex }; module.exports = ComponentToHex }, function(module, exports) { var HueToComponent = function(p, q, t) { if (t < 0) { t += 1 } if (t > 1) { t -= 1 } if (t < 1 / 6) { return p + (q - p) * 6 * t } if (t < 1 / 2) { return q } if (t < 2 / 3) { return p + (q - p) * (2 / 3 - t) * 6 } return p }; module.exports = HueToComponent }, function(module, exports, __webpack_require__) { var OS = __webpack_require__(92); var DOMContentLoaded = function(callback) { if (document.readyState === "complete" || document.readyState === "interactive") { callback(); return } var check = function() { document.removeEventListener("deviceready", check, true); document.removeEventListener("DOMContentLoaded", check, true); window.removeEventListener("load", check, true); callback() }; if (!document.body) { window.setTimeout(check, 20) } else if (OS.cordova && !OS.cocoonJS) { document.addEventListener("deviceready", check, false) } else { document.addEventListener("DOMContentLoaded", check, true); window.addEventListener("load", check, true) } }; module.exports = DOMContentLoaded }, function(module, exports) { var ParseXML = function(data) { var xml = ""; try { if (window["DOMParser"]) { var domparser = new DOMParser; xml = domparser.parseFromString(data, "text/xml") } else { xml = new ActiveXObject("Microsoft.XMLDOM"); xml.loadXML(data) } } catch (e) { xml = null } if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length) { return null } else { return xml } }; module.exports = ParseXML }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var NOOP = __webpack_require__(2); var RequestAnimationFrame = new Class({ initialize: function RequestAnimationFrame() { this.isRunning = false; this.callback = NOOP; this.tick = 0; this.isSetTimeOut = false; this.timeOutID = null; this.lastTime = 0; var _this = this; this.step = function step(timestamp) { _this.lastTime = _this.tick; _this.tick = timestamp; _this.timeOutID = window.requestAnimationFrame(step); _this.callback(timestamp) }; this.stepTimeout = function stepTimeout() { var d = Date.now(); var delay = Math.max(16 + _this.lastTime - d, 0); _this.lastTime = _this.tick; _this.tick = d; _this.timeOutID = window.setTimeout(stepTimeout, delay); _this.callback(d) } }, start: function(callback, forceSetTimeOut) { if (this.isRunning) { return } this.callback = callback; this.isSetTimeOut = forceSetTimeOut; this.isRunning = true; this.timeOutID = forceSetTimeOut ? window.setTimeout(this.stepTimeout, 0) : window.requestAnimationFrame(this.step) }, stop: function() { this.isRunning = false; if (this.isSetTimeOut) { clearTimeout(this.timeOutID) } else { window.cancelAnimationFrame(this.timeOutID) } }, destroy: function() { this.stop(); this.callback = NOOP } }); module.exports = RequestAnimationFrame }, function(module, exports, __webpack_require__) { module.exports = { os: __webpack_require__(92), browser: __webpack_require__(115), features: __webpack_require__(169), input: __webpack_require__(632), audio: __webpack_require__(633), video: __webpack_require__(634), fullscreen: __webpack_require__(635), canvasFeatures: __webpack_require__(303) } }, function(module, exports, __webpack_require__) { var CanvasPool = __webpack_require__(28); var CanvasFeatures = { supportInverseAlpha: false, supportNewBlendModes: false }; function checkBlendMode() { var pngHead = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAABAQMAAADD8p2OAAAAA1BMVEX/"; var pngEnd = "AAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJggg=="; var magenta = new Image; magenta.onload = function() { var yellow = new Image; yellow.onload = function() { var canvas = CanvasPool.create(yellow, 6, 1); var context = canvas.getContext("2d"); context.globalCompositeOperation = "multiply"; context.drawImage(magenta, 0, 0); context.drawImage(yellow, 2, 0); if (!context.getImageData(2, 0, 1, 1)) { return false } var data = context.getImageData(2, 0, 1, 1).data; CanvasPool.remove(yellow); CanvasFeatures.supportNewBlendModes = data[0] === 255 && data[1] === 0 && data[2] === 0 }; yellow.src = pngHead + "/wCKxvRF" + pngEnd }; magenta.src = pngHead + "AP804Oa6" + pngEnd; return false } function checkInverseAlpha() { var canvas = CanvasPool.create(this, 2, 1); var context = canvas.getContext("2d"); context.fillStyle = "rgba(10, 20, 30, 0.5)"; context.fillRect(0, 0, 1, 1); var s1 = context.getImageData(0, 0, 1, 1); if (s1 === null) { return false } context.putImageData(s1, 1, 0); var s2 = context.getImageData(1, 0, 1, 1); return s2.data[0] === s1.data[0] && s2.data[1] === s1.data[1] && s2.data[2] === s1.data[2] && s2.data[3] === s1.data[3] } function init() { if (document !== undefined) { CanvasFeatures.supportNewBlendModes = checkBlendMode(); CanvasFeatures.supportInverseAlpha = checkInverseAlpha() } return CanvasFeatures } module.exports = init() }, function(module, exports, __webpack_require__) { var CanvasSnapshot = __webpack_require__(305); var Class = __webpack_require__(0); var CONST = __webpack_require__(26); var GetBlendModes = __webpack_require__(306); var ScaleModes = __webpack_require__(89); var Smoothing = __webpack_require__(112); var TransformMatrix = __webpack_require__(48); var CanvasRenderer = new Class({ initialize: function CanvasRenderer(game) { this.game = game; this.type = CONST.CANVAS; this.drawCount = 0; this.width = game.config.width; this.height = game.config.height; this.config = { clearBeforeRender: game.config.clearBeforeRender, backgroundColor: game.config.backgroundColor, resolution: game.config.resolution, autoResize: game.config.autoResize, antialias: game.config.antialias, roundPixels: game.config.roundPixels }; this.scaleMode = game.config.antialias ? ScaleModes.LINEAR : ScaleModes.NEAREST; this.gameCanvas = game.canvas; this.gameContext = this.game.config.context ? this.game.config.context : this.gameCanvas.getContext("2d"); this.currentContext = this.gameContext; this.blendModes = GetBlendModes(); this.currentScaleMode = 0; this.snapshotCallback = null; this.snapshotType = null; this.snapshotEncoder = null; this._tempMatrix1 = new TransformMatrix; this._tempMatrix2 = new TransformMatrix; this._tempMatrix3 = new TransformMatrix; this._tempMatrix4 = new TransformMatrix; this.init() }, init: function() { this.resize(this.width, this.height) }, resize: function(width, height) { var resolution = this.config.resolution; this.width = width * resolution; this.height = height * resolution; this.gameCanvas.width = this.width; this.gameCanvas.height = this.height; if (this.config.autoResize) { this.gameCanvas.style.width = this.width / resolution + "px"; this.gameCanvas.style.height = this.height / resolution + "px" } if (this.scaleMode === ScaleModes.NEAREST) { Smoothing.disable(this.gameContext) } }, onContextLost: function() {}, onContextRestored: function() {}, resetTransform: function() { this.currentContext.setTransform(1, 0, 0, 1, 0, 0) }, setBlendMode: function(blendMode) { this.currentContext.globalCompositeOperation = blendMode; return this }, setContext: function(ctx) { this.currentContext = ctx ? ctx : this.gameContext; return this }, setAlpha: function(alpha) { this.currentContext.globalAlpha = alpha; return this }, preRender: function() { var ctx = this.gameContext; var config = this.config; var width = this.width; var height = this.height; if (config.clearBeforeRender) { ctx.clearRect(0, 0, width, height) } if (!config.transparent) { ctx.fillStyle = config.backgroundColor.rgba; ctx.fillRect(0, 0, width, height) } this.drawCount = 0 }, render: function(scene, children, interpolationPercentage, camera) { var list = children.list; var childCount = list.length; var cx = camera._cx; var cy = camera._cy; var cw = camera._cw; var ch = camera._ch; var ctx = camera.renderToTexture ? camera.context : scene.sys.context; var scissor = cx !== 0 || cy !== 0 || cw !== ctx.canvas.width || ch !== ctx.canvas.height; this.currentContext = ctx; if (!camera.transparent) { ctx.fillStyle = camera.backgroundColor.rgba; ctx.fillRect(cx, cy, cw, ch) } ctx.globalAlpha = camera.alpha; ctx.globalCompositeOperation = "source-over"; this.drawCount += list.length; if (scissor) { ctx.save(); ctx.beginPath(); ctx.rect(cx, cy, cw, ch); ctx.clip() } if (camera.renderToTexture) { camera.emit("prerender", camera) } camera.matrix.copyToContext(ctx); for (var i = 0; i < childCount; i++) { var child = list[i]; if (!child.willRender(camera)) { continue } if (child.mask) { child.mask.preRenderCanvas(this, child, camera) } child.renderCanvas(this, child, interpolationPercentage, camera); if (child.mask) { child.mask.postRenderCanvas(this, child, camera) } } ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalCompositeOperation = "source-over"; ctx.globalAlpha = 1; camera.flashEffect.postRenderCanvas(ctx); camera.fadeEffect.postRenderCanvas(ctx); camera.dirty = false; if (scissor) { ctx.restore() } if (camera.renderToTexture) { camera.emit("postrender", camera); scene.sys.context.drawImage(camera.canvas, cx, cy) } }, postRender: function() { var ctx = this.gameContext; ctx.globalAlpha = 1; ctx.globalCompositeOperation = "source-over"; if (this.snapshotCallback) { this.snapshotCallback(CanvasSnapshot(this.gameCanvas, this.snapshotType, this.snapshotEncoder)); this.snapshotCallback = null } }, snapshot: function(callback, type, encoderOptions) { this.snapshotCallback = callback; this.snapshotType = type; this.snapshotEncoder = encoderOptions }, batchSprite: function(sprite, frame, camera, parentTransformMatrix) { var alpha = camera.alpha * sprite.alpha; if (alpha === 0) { return } var ctx = this.currentContext; var camMatrix = this._tempMatrix1; var spriteMatrix = this._tempMatrix2; var calcMatrix = this._tempMatrix3; var cd = frame.canvasData; var frameX = cd.x; var frameY = cd.y; var frameWidth = frame.cutWidth; var frameHeight = frame.cutHeight; var res = frame.source.resolution; var x = -sprite.displayOriginX + frame.x; var y = -sprite.displayOriginY + frame.y; var fx = sprite.flipX ? -1 : 1; var fy = sprite.flipY ? -1 : 1; if (sprite.isCropped) { var crop = sprite._crop; if (crop.flipX !== sprite.flipX || crop.flipY !== sprite.flipY) { frame.updateCropUVs(crop, sprite.flipX, sprite.flipY) } frameWidth = crop.cw; frameHeight = crop.ch; frameX = crop.cx; frameY = crop.cy; x = -sprite.displayOriginX + crop.x; y = -sprite.displayOriginY + crop.y; if (fx === -1) { if (x >= 0) { x = -(x + frameWidth) } else if (x < 0) { x = Math.abs(x) - frameWidth } } if (fy === -1) { if (y >= 0) { y = -(y + frameHeight) } else if (y < 0) { y = Math.abs(y) - frameHeight } } } spriteMatrix.applyITRS(sprite.x, sprite.y, sprite.rotation, sprite.scaleX, sprite.scaleY); camMatrix.copyFrom(camera.matrix); if (parentTransformMatrix) { camMatrix.multiplyWithOffset(parentTransformMatrix, -camera.scrollX * sprite.scrollFactorX, -camera.scrollY * sprite.scrollFactorY); spriteMatrix.e = sprite.x; spriteMatrix.f = sprite.y; camMatrix.multiply(spriteMatrix, calcMatrix) } else { spriteMatrix.e -= camera.scrollX * sprite.scrollFactorX; spriteMatrix.f -= camera.scrollY * sprite.scrollFactorY; camMatrix.multiply(spriteMatrix, calcMatrix) } ctx.save(); calcMatrix.setToContext(ctx); ctx.scale(fx, fy); ctx.globalCompositeOperation = this.blendModes[sprite.blendMode]; ctx.globalAlpha = alpha; ctx.drawImage(frame.source.image, frameX, frameY, frameWidth, frameHeight, x, y, frameWidth / res, frameHeight / res); ctx.restore() }, destroy: function() { this.gameCanvas = null; this.gameContext = null; this.game = null } }); module.exports = CanvasRenderer }, function(module, exports) { var CanvasSnapshot = function(canvas, type, encoderOptions) { if (type === undefined) { type = "image/png" } if (encoderOptions === undefined) { encoderOptions = .92 } var src = canvas.toDataURL(type, encoderOptions); var image = new Image; image.src = src; return image }; module.exports = CanvasSnapshot }, function(module, exports, __webpack_require__) { var modes = __webpack_require__(61); var CanvasFeatures = __webpack_require__(303); var GetBlendModes = function() { var output = []; var useNew = CanvasFeatures.supportNewBlendModes; var so = "source-over"; output[modes.NORMAL] = so; output[modes.ADD] = "lighter"; output[modes.MULTIPLY] = useNew ? "multiply" : so; output[modes.SCREEN] = useNew ? "screen" : so; output[modes.OVERLAY] = useNew ? "overlay" : so; output[modes.DARKEN] = useNew ? "darken" : so; output[modes.LIGHTEN] = useNew ? "lighten" : so; output[modes.COLOR_DODGE] = useNew ? "color-dodge" : so; output[modes.COLOR_BURN] = useNew ? "color-burn" : so; output[modes.HARD_LIGHT] = useNew ? "hard-light" : so; output[modes.SOFT_LIGHT] = useNew ? "soft-light" : so; output[modes.DIFFERENCE] = useNew ? "difference" : so; output[modes.EXCLUSION] = useNew ? "exclusion" : so; output[modes.HUE] = useNew ? "hue" : so; output[modes.SATURATION] = useNew ? "saturation" : so; output[modes.COLOR] = useNew ? "color" : so; output[modes.LUMINOSITY] = useNew ? "luminosity" : so; return output }; module.exports = GetBlendModes }, function(module, exports, __webpack_require__) { var BaseCamera = __webpack_require__(111); var Class = __webpack_require__(0); var CONST = __webpack_require__(26); var IsSizePowerOfTwo = __webpack_require__(116); var SpliceOne = __webpack_require__(93); var TransformMatrix = __webpack_require__(48); var Utils = __webpack_require__(10); var WebGLSnapshot = __webpack_require__(308); var BitmapMaskPipeline = __webpack_require__(309); var ForwardDiffuseLightPipeline = __webpack_require__(310); var TextureTintPipeline = __webpack_require__(172); var WebGLRenderer = new Class({ initialize: function WebGLRenderer(game) { var renderer = this; var gameConfig = game.config; var contextCreationConfig = { alpha: gameConfig.transparent, depth: false, antialias: gameConfig.antialias, premultipliedAlpha: gameConfig.premultipliedAlpha, stencil: true, preserveDrawingBuffer: gameConfig.preserveDrawingBuffer, failIfMajorPerformanceCaveat: gameConfig.failIfMajorPerformanceCaveat, powerPreference: gameConfig.powerPreference }; this.config = { clearBeforeRender: gameConfig.clearBeforeRender, antialias: gameConfig.antialias, backgroundColor: gameConfig.backgroundColor, contextCreation: contextCreationConfig, resolution: gameConfig.resolution, autoResize: gameConfig.autoResize, roundPixels: gameConfig.roundPixels, maxTextures: gameConfig.maxTextures, maxTextureSize: gameConfig.maxTextureSize, batchSize: gameConfig.batchSize, maxLights: gameConfig.maxLights }; this.game = game; this.type = CONST.WEBGL; this.width = game.config.width; this.height = game.config.height; this.canvas = game.canvas; this.lostContextCallbacks = []; this.restoredContextCallbacks = []; this.blendModes = []; this.nativeTextures = []; this.contextLost = false; this.pipelines = null; this.snapshotState = { callback: null, type: null, encoder: null }; this.currentActiveTextureUnit = 0; this.currentTextures = new Array(16); this.currentFramebuffer = null; this.currentPipeline = null; this.currentProgram = null; this.currentVertexBuffer = null; this.currentIndexBuffer = null; this.currentBlendMode = Infinity; this.currentScissorEnabled = false; this.currentScissor = null; this.scissorStack = []; this.canvas.addEventListener("webglcontextlost", function(event) { renderer.contextLost = true; event.preventDefault(); for (var index = 0; index < renderer.lostContextCallbacks.length; ++index) { var callback = renderer.lostContextCallbacks[index]; callback[0].call(callback[1], renderer) } }, false); this.canvas.addEventListener("webglcontextrestored", function() { renderer.contextLost = false; renderer.init(renderer.config); for (var index = 0; index < renderer.restoredContextCallbacks.length; ++index) { var callback = renderer.restoredContextCallbacks[index]; callback[0].call(callback[1], renderer) } }, false); this.gl = null; this.supportedExtensions = null; this.extensions = {}; this.glFormats = []; this.compression = { ETC1: false, PVRTC: false, S3TC: false }; this.drawingBufferHeight = 0; this.blankTexture = null; this.defaultCamera = new BaseCamera(0, 0, 0, 0); this._tempMatrix1 = new TransformMatrix; this._tempMatrix2 = new TransformMatrix; this._tempMatrix3 = new TransformMatrix; this._tempMatrix4 = new TransformMatrix; this.init(this.config) }, init: function(config) { var gl; var canvas = this.canvas; var clearColor = config.backgroundColor; if (this.game.config.context) { gl = this.game.config.context } else { gl = canvas.getContext("webgl", config.contextCreation) || canvas.getContext("experimental-webgl", config.contextCreation) } if (!gl || gl.isContextLost()) { this.contextLost = true; throw new Error("WebGL unsupported") } this.gl = gl; this.game.context = gl; for (var i = 0; i <= 16; i++) { this.blendModes.push({ func: [gl.ONE, gl.ONE_MINUS_SRC_ALPHA], equation: gl.FUNC_ADD }) } this.blendModes[1].func = [gl.ONE, gl.DST_ALPHA]; this.blendModes[2].func = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA]; this.blendModes[3].func = [gl.ONE, gl.ONE_MINUS_SRC_COLOR]; this.glFormats[0] = gl.BYTE; this.glFormats[1] = gl.SHORT; this.glFormats[2] = gl.UNSIGNED_BYTE; this.glFormats[3] = gl.UNSIGNED_SHORT; this.glFormats[4] = gl.FLOAT; var exts = gl.getSupportedExtensions(); if (!config.maxTextures) { config.maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS) } if (!config.maxTextureSize) { config.maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE) } var extString = "WEBGL_compressed_texture_"; var wkExtString = "WEBKIT_" + extString; this.compression.ETC1 = gl.getExtension(extString + "etc1") || gl.getExtension(wkExtString + "etc1"); this.compression.PVRTC = gl.getExtension(extString + "pvrtc") || gl.getExtension(wkExtString + "pvrtc"); this.compression.S3TC = gl.getExtension(extString + "s3tc") || gl.getExtension(wkExtString + "s3tc"); this.supportedExtensions = exts; gl.disable(gl.DEPTH_TEST); gl.disable(gl.CULL_FACE); gl.enable(gl.BLEND); gl.clearColor(clearColor.redGL, clearColor.greenGL, clearColor.blueGL, 1); for (var index = 0; index < this.currentTextures.length; ++index) { this.currentTextures[index] = null } this.pipelines = {}; this.addPipeline("TextureTintPipeline", new TextureTintPipeline({ game: this.game, renderer: this })); this.addPipeline("BitmapMaskPipeline", new BitmapMaskPipeline({ game: this.game, renderer: this })); this.addPipeline("Light2D", new ForwardDiffuseLightPipeline({ game: this.game, renderer: this, maxLights: config.maxLights })); this.setBlendMode(CONST.BlendModes.NORMAL); this.resize(this.width, this.height); this.game.events.once("texturesready", this.boot, this); return this }, boot: function() { for (var pipelineName in this.pipelines) { this.pipelines[pipelineName].boot() } var blank = this.game.textures.getFrame("__DEFAULT"); this.pipelines.TextureTintPipeline.currentFrame = blank; this.blankTexture = blank }, resize: function(width, height) { var gl = this.gl; var pipelines = this.pipelines; var resolution = this.config.resolution; this.width = Math.floor(width * resolution); this.height = Math.floor(height * resolution); this.canvas.width = this.width; this.canvas.height = this.height; if (this.config.autoResize) { this.canvas.style.width = this.width / resolution + "px"; this.canvas.style.height = this.height / resolution + "px" } gl.viewport(0, 0, this.width, this.height); for (var pipelineName in pipelines) { pipelines[pipelineName].resize(width, height, resolution) } this.drawingBufferHeight = gl.drawingBufferHeight; this.defaultCamera.setSize(width, height); gl.scissor(0, this.drawingBufferHeight - this.height, this.width, this.height); return this }, onContextRestored: function(callback, target) { this.restoredContextCallbacks.push([callback, target]); return this }, onContextLost: function(callback, target) { this.lostContextCallbacks.push([callback, target]); return this }, hasExtension: function(extensionName) { return this.supportedExtensions ? this.supportedExtensions.indexOf(extensionName) : false }, getExtension: function(extensionName) { if (!this.hasExtension(extensionName)) { return null } if (!(extensionName in this.extensions)) { this.extensions[extensionName] = this.gl.getExtension(extensionName) } return this.extensions[extensionName] }, flush: function() { if (this.currentPipeline) { this.currentPipeline.flush() } }, hasPipeline: function(pipelineName) { return pipelineName in this.pipelines }, getPipeline: function(pipelineName) { return this.hasPipeline(pipelineName) ? this.pipelines[pipelineName] : null }, removePipeline: function(pipelineName) { delete this.pipelines[pipelineName]; return this }, addPipeline: function(pipelineName, pipelineInstance) { if (!this.hasPipeline(pipelineName)) { this.pipelines[pipelineName] = pipelineInstance } else { console.warn("Pipeline exists: " + pipelineName) } pipelineInstance.name = pipelineName; this.pipelines[pipelineName].resize(this.width, this.height, this.config.resolution); return pipelineInstance }, pushScissor: function(x, y, width, height) { var scissorStack = this.scissorStack; var scissor = [x, y, width, height]; scissorStack.push(scissor); this.setScissor(x, y, width, height); this.currentScissor = scissor; return scissor }, setScissor: function(x, y, width, height) { var gl = this.gl; var current = this.currentScissor; var cx = current[0]; var cy = current[1]; var cw = current[2]; var ch = current[3]; if (cx !== x || cy !== y || cw !== width || ch !== height) { this.flush(); if (width > 0 && height > 0) { gl.scissor(x, this.drawingBufferHeight - y - height, width, height) } } }, popScissor: function() { var scissorStack = this.scissorStack; scissorStack.pop(); var scissor = scissorStack[scissorStack.length - 1]; if (scissor) { this.setScissor(scissor[0], scissor[1], scissor[2], scissor[3]) } this.currentScissor = scissor }, setPipeline: function(pipelineInstance, gameObject) { if (this.currentPipeline !== pipelineInstance || this.currentPipeline.vertexBuffer !== this.currentVertexBuffer || this.currentPipeline.program !== this.currentProgram) { this.flush(); this.currentPipeline = pipelineInstance; this.currentPipeline.bind() } this.currentPipeline.onBind(gameObject); return this.currentPipeline }, setBlendMode: function(blendModeId) { var gl = this.gl; var blendMode = this.blendModes[blendModeId]; if (blendModeId !== CONST.BlendModes.SKIP_CHECK && this.currentBlendMode !== blendModeId) { this.flush(); gl.enable(gl.BLEND); gl.blendEquation(blendMode.equation); if (blendMode.func.length > 2) { gl.blendFuncSeparate(blendMode.func[0], blendMode.func[1], blendMode.func[2], blendMode.func[3]) } else { gl.blendFunc(blendMode.func[0], blendMode.func[1]) } this.currentBlendMode = blendModeId; return true } return false }, addBlendMode: function(func, equation) { var index = this.blendModes.push({ func: func, equation: equation }); return index - 1 }, updateBlendMode: function(index, func, equation) { if (this.blendModes[index]) { this.blendModes[index].func = func; if (equation) { this.blendModes[index].equation = equation } } return this }, removeBlendMode: function(index) { if (index > 16 && this.blendModes[index]) { this.blendModes.splice(index, 1) } return this }, setBlankTexture: function(force) { if (force === undefined) { force = false } if (force || this.currentActiveTextureUnit !== 0 || !this.currentTextures[0]) { this.setTexture2D(this.blankTexture.glTexture, 0) } }, setTexture2D: function(texture, textureUnit) { var gl = this.gl; if (texture !== this.currentTextures[textureUnit]) { this.flush(); if (this.currentActiveTextureUnit !== textureUnit) { gl.activeTexture(gl.TEXTURE0 + textureUnit); this.currentActiveTextureUnit = textureUnit } gl.bindTexture(gl.TEXTURE_2D, texture); this.currentTextures[textureUnit] = texture } return this }, setFramebuffer: function(framebuffer) { var gl = this.gl; var width = this.width; var height = this.height; if (framebuffer !== this.currentFramebuffer) { if (framebuffer && framebuffer.renderTexture) { width = framebuffer.renderTexture.width; height = framebuffer.renderTexture.height } else { this.flush() } gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer); gl.viewport(0, 0, width, height); this.currentFramebuffer = framebuffer } return this }, setProgram: function(program) { var gl = this.gl; if (program !== this.currentProgram) { this.flush(); gl.useProgram(program); this.currentProgram = program } return this }, setVertexBuffer: function(vertexBuffer) { var gl = this.gl; if (vertexBuffer !== this.currentVertexBuffer) { this.flush(); gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer); this.currentVertexBuffer = vertexBuffer } return this }, setIndexBuffer: function(indexBuffer) { var gl = this.gl; if (indexBuffer !== this.currentIndexBuffer) { this.flush(); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer); this.currentIndexBuffer = indexBuffer } return this }, createTextureFromSource: function(source, width, height, scaleMode) { var gl = this.gl; var filter = gl.NEAREST; var wrap = gl.CLAMP_TO_EDGE; var texture = null; width = source ? source.width : width; height = source ? source.height : height; if (IsSizePowerOfTwo(width, height)) { wrap = gl.REPEAT } if (scaleMode === CONST.ScaleModes.LINEAR && this.config.antialias) { filter = gl.LINEAR } if (!source && typeof width === "number" && typeof height === "number") { texture = this.createTexture2D(0, filter, filter, wrap, wrap, gl.RGBA, null, width, height) } else { texture = this.createTexture2D(0, filter, filter, wrap, wrap, gl.RGBA, source) } return texture }, createTexture2D: function(mipLevel, minFilter, magFilter, wrapT, wrapS, format, pixels, width, height, pma) { pma = pma === undefined || pma === null ? true : pma; var gl = this.gl; var texture = gl.createTexture(); this.setTexture2D(texture, 0); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrapS); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrapT); gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, pma); if (pixels === null || pixels === undefined) { gl.texImage2D(gl.TEXTURE_2D, mipLevel, format, width, height, 0, format, gl.UNSIGNED_BYTE, null) } else { gl.texImage2D(gl.TEXTURE_2D, mipLevel, format, format, gl.UNSIGNED_BYTE, pixels); width = pixels.width; height = pixels.height } this.setTexture2D(null, 0); texture.isAlphaPremultiplied = pma; texture.isRenderTexture = false; texture.width = width; texture.height = height; this.nativeTextures.push(texture); return texture }, createFramebuffer: function(width, height, renderTexture, addDepthStencilBuffer) { var gl = this.gl; var framebuffer = gl.createFramebuffer(); var complete = 0; this.setFramebuffer(framebuffer); if (addDepthStencilBuffer) { var depthStencilBuffer = gl.createRenderbuffer(); gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height); gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer) } renderTexture.isRenderTexture = true; renderTexture.isAlphaPremultiplied = false; gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, renderTexture, 0); complete = gl.checkFramebufferStatus(gl.FRAMEBUFFER); if (complete !== gl.FRAMEBUFFER_COMPLETE) { var errors = { 36054: "Incomplete Attachment", 36055: "Missing Attachment", 36057: "Incomplete Dimensions", 36061: "Framebuffer Unsupported" }; throw new Error("Framebuffer incomplete. Framebuffer status: " + errors[complete]) } framebuffer.renderTexture = renderTexture; this.setFramebuffer(null); return framebuffer }, createProgram: function(vertexShader, fragmentShader) { var gl = this.gl; var program = gl.createProgram(); var vs = gl.createShader(gl.VERTEX_SHADER); var fs = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(vs, vertexShader); gl.shaderSource(fs, fragmentShader); gl.compileShader(vs); gl.compileShader(fs); if (!gl.getShaderParameter(vs, gl.COMPILE_STATUS)) { throw new Error("Failed to compile Vertex Shader:\n" + gl.getShaderInfoLog(vs)) } if (!gl.getShaderParameter(fs, gl.COMPILE_STATUS)) { throw new Error("Failed to compile Fragment Shader:\n" + gl.getShaderInfoLog(fs)) } gl.attachShader(program, vs); gl.attachShader(program, fs); gl.linkProgram(program); if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { throw new Error("Failed to link program:\n" + gl.getProgramInfoLog(program)) } return program }, createVertexBuffer: function(initialDataOrSize, bufferUsage) { var gl = this.gl; var vertexBuffer = gl.createBuffer(); this.setVertexBuffer(vertexBuffer); gl.bufferData(gl.ARRAY_BUFFER, initialDataOrSize, bufferUsage); this.setVertexBuffer(null); return vertexBuffer }, createIndexBuffer: function(initialDataOrSize, bufferUsage) { var gl = this.gl; var indexBuffer = gl.createBuffer(); this.setIndexBuffer(indexBuffer); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, initialDataOrSize, bufferUsage); this.setIndexBuffer(null); return indexBuffer }, deleteTexture: function(texture) { var index = this.nativeTextures.indexOf(texture); if (index !== -1) { SpliceOne(this.nativeTextures, index) } this.gl.deleteTexture(texture); if (this.currentTextures[0] === texture) { this.setBlankTexture(true) } return this }, deleteFramebuffer: function(framebuffer) { this.gl.deleteFramebuffer(framebuffer); return this }, deleteProgram: function(program) { this.gl.deleteProgram(program); return this }, deleteBuffer: function(buffer) { this.gl.deleteBuffer(buffer); return this }, preRenderCamera: function(camera) { var cx = camera._cx; var cy = camera._cy; var cw = camera._cw; var ch = camera._ch; var TextureTintPipeline = this.pipelines.TextureTintPipeline; var color = camera.backgroundColor; if (camera.renderToTexture) { this.flush(); this.pushScissor(cx, cy, cw, -ch); this.setFramebuffer(camera.framebuffer); var gl = this.gl; gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT); TextureTintPipeline.projOrtho(cx, cw + cx, cy, ch + cy, -1e3, 1e3); if (color.alphaGL > 0) { TextureTintPipeline.drawFillRect(cx, cy, cw + cx, ch + cy, Utils.getTintFromFloats(color.redGL, color.greenGL, color.blueGL, 1), color.alphaGL) } camera.emit("prerender", camera) } else { this.pushScissor(cx, cy, cw, ch); if (color.alphaGL > 0) { TextureTintPipeline.drawFillRect(cx, cy, cw, ch, Utils.getTintFromFloats(color.redGL, color.greenGL, color.blueGL, 1), color.alphaGL) } } }, postRenderCamera: function(camera) { var TextureTintPipeline = this.pipelines.TextureTintPipeline; camera.flashEffect.postRenderWebGL(TextureTintPipeline, Utils.getTintFromFloats); camera.fadeEffect.postRenderWebGL(TextureTintPipeline, Utils.getTintFromFloats); camera.dirty = false; this.popScissor(); if (camera.renderToTexture) { TextureTintPipeline.flush(); this.setFramebuffer(null); camera.emit("postrender", camera); TextureTintPipeline.projOrtho(0, TextureTintPipeline.width, TextureTintPipeline.height, 0, -1e3, 1e3); var getTint = Utils.getTintAppendFloatAlpha; var pipeline = camera.pipeline ? camera.pipeline : TextureTintPipeline; pipeline.batchTexture(camera, camera.glTexture, camera.width, camera.height, camera.x, camera.y, camera.width, camera.height, camera.zoom, camera.zoom, camera.rotation, camera.flipX, !camera.flipY, 1, 1, 0, 0, 0, 0, camera.width, camera.height, getTint(camera._tintTL, camera._alphaTL), getTint(camera._tintTR, camera._alphaTR), getTint(camera._tintBL, camera._alphaBL), getTint(camera._tintBR, camera._alphaBR), camera._isTinted && camera.tintFill, 0, 0, this.defaultCamera, null); this.setBlankTexture(true) } }, preRender: function() { if (this.contextLost) { return } var gl = this.gl; var color = this.config.backgroundColor; var pipelines = this.pipelines; if (this.config.clearBeforeRender) { gl.clearColor(color.redGL, color.greenGL, color.blueGL, color.alphaGL); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT) } gl.enable(gl.SCISSOR_TEST); for (var key in pipelines) { pipelines[key].onPreRender() } this.currentScissor = [0, 0, this.width, this.height]; this.scissorStack = [this.currentScissor]; if (this.game.scene.customViewports) { gl.scissor(0, this.drawingBufferHeight - this.height, this.width, this.height) } this.setPipeline(this.pipelines.TextureTintPipeline) }, render: function(scene, children, interpolationPercentage, camera) { if (this.contextLost) { return } var list = children.list; var childCount = list.length; var pipelines = this.pipelines; for (var key in pipelines) { pipelines[key].onRender(scene, camera) } this.preRenderCamera(camera); for (var i = 0; i < childCount; i++) { var child = list[i]; if (!child.willRender(camera)) { continue } if (child.blendMode !== this.currentBlendMode) { this.setBlendMode(child.blendMode) } var mask = child.mask; if (mask) { mask.preRenderWebGL(this, child, camera); child.renderWebGL(this, child, interpolationPercentage, camera); mask.postRenderWebGL(this, child) } else { child.renderWebGL(this, child, interpolationPercentage, camera) } } this.setBlendMode(CONST.BlendModes.NORMAL); this.postRenderCamera(camera) }, postRender: function() { if (this.contextLost) { return } this.flush(); if (this.snapshotState.callback) { this.snapshotState.callback(WebGLSnapshot(this.canvas, this.snapshotState.type, this.snapshotState.encoder)); this.snapshotState.callback = null } var pipelines = this.pipelines; for (var key in pipelines) { pipelines[key].onPostRender() } }, snapshot: function(callback, type, encoderOptions) { this.snapshotState.callback = callback; this.snapshotState.type = type; this.snapshotState.encoder = encoderOptions; return this }, canvasToTexture: function(srcCanvas, dstTexture, noRepeat) { if (noRepeat === undefined) { noRepeat = false } var gl = this.gl; if (!dstTexture) { var wrapping = gl.CLAMP_TO_EDGE; if (!noRepeat && IsSizePowerOfTwo(srcCanvas.width, srcCanvas.height)) { wrapping = gl.REPEAT } dstTexture = this.createTexture2D(0, gl.NEAREST, gl.NEAREST, wrapping, wrapping, gl.RGBA, srcCanvas, srcCanvas.width, srcCanvas.height, true) } else { this.setTexture2D(dstTexture, 0); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, srcCanvas); dstTexture.width = srcCanvas.width; dstTexture.height = srcCanvas.height; this.setTexture2D(null, 0) } return dstTexture }, setTextureFilter: function(texture, filter) { var gl = this.gl; var glFilter = [gl.LINEAR, gl.NEAREST][filter]; this.setTexture2D(texture, 0); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, glFilter); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, glFilter); this.setTexture2D(null, 0); return this }, setFloat1: function(program, name, x) { this.setProgram(program); this.gl.uniform1f(this.gl.getUniformLocation(program, name), x); return this }, setFloat2: function(program, name, x, y) { this.setProgram(program); this.gl.uniform2f(this.gl.getUniformLocation(program, name), x, y); return this }, setFloat3: function(program, name, x, y, z) { this.setProgram(program); this.gl.uniform3f(this.gl.getUniformLocation(program, name), x, y, z); return this }, setFloat4: function(program, name, x, y, z, w) { this.setProgram(program); this.gl.uniform4f(this.gl.getUniformLocation(program, name), x, y, z, w); return this }, setFloat1v: function(program, name, arr) { this.setProgram(program); this.gl.uniform1fv(this.gl.getUniformLocation(program, name), arr); return this }, setFloat2v: function(program, name, arr) { this.setProgram(program); this.gl.uniform2fv(this.gl.getUniformLocation(program, name), arr); return this }, setFloat3v: function(program, name, arr) { this.setProgram(program); this.gl.uniform3fv(this.gl.getUniformLocation(program, name), arr); return this }, setFloat4v: function(program, name, arr) { this.setProgram(program); this.gl.uniform4fv(this.gl.getUniformLocation(program, name), arr); return this }, setInt1: function(program, name, x) { this.setProgram(program); this.gl.uniform1i(this.gl.getUniformLocation(program, name), x); return this }, setInt2: function(program, name, x, y) { this.setProgram(program); this.gl.uniform2i(this.gl.getUniformLocation(program, name), x, y); return this }, setInt3: function(program, name, x, y, z) { this.setProgram(program); this.gl.uniform3i(this.gl.getUniformLocation(program, name), x, y, z); return this }, setInt4: function(program, name, x, y, z, w) { this.setProgram(program); this.gl.uniform4i(this.gl.getUniformLocation(program, name), x, y, z, w); return this }, setMatrix2: function(program, name, transpose, matrix) { this.setProgram(program); this.gl.uniformMatrix2fv(this.gl.getUniformLocation(program, name), transpose, matrix); return this }, setMatrix3: function(program, name, transpose, matrix) { this.setProgram(program); this.gl.uniformMatrix3fv(this.gl.getUniformLocation(program, name), transpose, matrix); return this }, setMatrix4: function(program, name, transpose, matrix) { this.setProgram(program); this.gl.uniformMatrix4fv(this.gl.getUniformLocation(program, name), transpose, matrix); return this }, getMaxTextures: function() { return this.config.maxTextures }, getMaxTextureSize: function() { return this.config.maxTextureSize }, destroy: function() { for (var key in this.pipelines) { this.pipelines[key].destroy(); delete this.pipelines[key] } for (var index = 0; index < this.nativeTextures.length; ++index) { this.deleteTexture(this.nativeTextures[index]); delete this.nativeTextures[index] } delete this.gl; delete this.game; this.contextLost = true; this.extensions = {}; this.nativeTextures.length = 0 } }); module.exports = WebGLRenderer }, function(module, exports) { var WebGLSnapshot = function(sourceCanvas, type, encoderOptions) { if (!type) { type = "image/png" } if (!encoderOptions) { encoderOptions = .92 } var gl = sourceCanvas.getContext("experimental-webgl"); var pixels = new Uint8Array(gl.drawingBufferWidth * gl.drawingBufferHeight * 4); gl.readPixels(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight, gl.RGBA, gl.UNSIGNED_BYTE, pixels); var canvas = document.createElement("canvas"); var ctx = canvas.getContext("2d"); var imageData; canvas.width = gl.drawingBufferWidth; canvas.height = gl.drawingBufferHeight; imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); var data = imageData.data; for (var y = 0; y < canvas.height; y += 1) { for (var x = 0; x < canvas.width; x += 1) { var si = ((canvas.height - y) * canvas.width + x) * 4; var di = (y * canvas.width + x) * 4; data[di + 0] = pixels[si + 0]; data[di + 1] = pixels[si + 1]; data[di + 2] = pixels[si + 2]; data[di + 3] = pixels[si + 3] } } ctx.putImageData(imageData, 0, 0); var src = canvas.toDataURL(type, encoderOptions); var image = new Image; image.src = src; return image }; module.exports = WebGLSnapshot }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var ShaderSourceFS = __webpack_require__(637); var ShaderSourceVS = __webpack_require__(638); var WebGLPipeline = __webpack_require__(171); var BitmapMaskPipeline = new Class({ Extends: WebGLPipeline, initialize: function BitmapMaskPipeline(config) { WebGLPipeline.call(this, { game: config.game, renderer: config.renderer, gl: config.renderer.gl, topology: config.topology ? config.topology : config.renderer.gl.TRIANGLES, vertShader: config.vertShader ? config.vertShader : ShaderSourceVS, fragShader: config.fragShader ? config.fragShader : ShaderSourceFS, vertexCapacity: config.vertexCapacity ? config.vertexCapacity : 3, vertexSize: config.vertexSize ? config.vertexSize : Float32Array.BYTES_PER_ELEMENT * 2, vertices: new Float32Array([-1, +1, -1, -7, +7, +1]).buffer, attributes: [{ name: "inPosition", size: 2, type: config.renderer.gl.FLOAT, normalized: false, offset: 0 }] }); this.vertexViewF32 = new Float32Array(this.vertexData); this.maxQuads = 1; this.resolutionDirty = true }, onBind: function() { WebGLPipeline.prototype.onBind.call(this); var renderer = this.renderer; var program = this.program; if (this.resolutionDirty) { renderer.setFloat2(program, "uResolution", this.width, this.height); renderer.setInt1(program, "uMainSampler", 0); renderer.setInt1(program, "uMaskSampler", 1); this.resolutionDirty = false } return this }, resize: function(width, height, resolution) { WebGLPipeline.prototype.resize.call(this, width, height, resolution); this.resolutionDirty = true; return this }, beginMask: function(mask, maskedObject, camera) { var renderer = this.renderer; var gl = this.gl; var bitmapMask = mask.bitmapMask; if (bitmapMask && gl) { renderer.flush(); renderer.setFramebuffer(mask.maskFramebuffer); gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT); bitmapMask.renderWebGL(renderer, bitmapMask, 0, camera); renderer.flush(); renderer.setFramebuffer(mask.mainFramebuffer); gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT) } }, endMask: function(mask) { var renderer = this.renderer; var gl = this.gl; var bitmapMask = mask.bitmapMask; if (bitmapMask && gl) { renderer.setFramebuffer(null); renderer.setPipeline(this); renderer.setTexture2D(mask.maskTexture, 1); renderer.setTexture2D(mask.mainTexture, 0); renderer.setInt1(this.program, "uInvertMaskAlpha", mask.invertAlpha); gl.drawArrays(this.topology, 0, 3) } } }); module.exports = BitmapMaskPipeline }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var ShaderSourceFS = __webpack_require__(639); var TextureTintPipeline = __webpack_require__(172); var LIGHT_COUNT = 10; var ForwardDiffuseLightPipeline = new Class({ Extends: TextureTintPipeline, initialize: function ForwardDiffuseLightPipeline(config) { LIGHT_COUNT = config.maxLights; config.fragShader = ShaderSourceFS.replace("%LIGHT_COUNT%", LIGHT_COUNT.toString()); TextureTintPipeline.call(this, config); this.defaultNormalMap }, boot: function() { this.defaultNormalMap = this.game.textures.getFrame("__DEFAULT") }, onBind: function(gameObject) { TextureTintPipeline.prototype.onBind.call(this); var renderer = this.renderer; var program = this.program; this.mvpUpdate(); renderer.setInt1(program, "uNormSampler", 1); renderer.setFloat2(program, "uResolution", this.width, this.height); if (gameObject) { this.setNormalMap(gameObject) } return this }, onRender: function(scene, camera) { this.active = false; var lightManager = scene.sys.lights; if (!lightManager || lightManager.lights.length <= 0 || !lightManager.active) { return this } var lights = lightManager.cull(camera); var lightCount = Math.min(lights.length, LIGHT_COUNT); if (lightCount === 0) { return this } this.active = true; var renderer = this.renderer; var program = this.program; var cameraMatrix = camera.matrix; var point = { x: 0, y: 0 }; var height = renderer.height; var index; for (index = 0; index < LIGHT_COUNT; ++index) { renderer.setFloat1(program, "uLights[" + index + "].radius", 0) } renderer.setFloat4(program, "uCamera", camera.x, camera.y, camera.rotation, camera.zoom); renderer.setFloat3(program, "uAmbientLightColor", lightManager.ambientColor.r, lightManager.ambientColor.g, lightManager.ambientColor.b); for (index = 0; index < lightCount; ++index) { var light = lights[index]; var lightName = "uLights[" + index + "]."; cameraMatrix.transformPoint(light.x, light.y, point); renderer.setFloat2(program, lightName + "position", point.x - camera.scrollX * light.scrollFactorX * camera.zoom, height - (point.y - camera.scrollY * light.scrollFactorY * camera.zoom)); renderer.setFloat3(program, lightName + "color", light.r, light.g, light.b); renderer.setFloat1(program, lightName + "intensity", light.intensity); renderer.setFloat1(program, lightName + "radius", light.radius) } return this }, batchTexture: function(gameObject, texture, textureWidth, textureHeight, srcX, srcY, srcWidth, srcHeight, scaleX, scaleY, rotation, flipX, flipY, scrollFactorX, scrollFactorY, displayOriginX, displayOriginY, frameX, frameY, frameWidth, frameHeight, tintTL, tintTR, tintBL, tintBR, tintEffect, uOffset, vOffset, camera, parentTransformMatrix) { if (!this.active) { return } this.renderer.setPipeline(this); var normalTexture; if (gameObject.displayTexture) { normalTexture = gameObject.displayTexture.dataSource[gameObject.displayFrame.sourceIndex] } else if (gameObject.texture) { normalTexture = gameObject.texture.dataSource[gameObject.frame.sourceIndex] } else if (gameObject.tileset) { normalTexture = gameObject.tileset.image.dataSource[0] } if (!normalTexture) { console.warn("Normal map missing or invalid"); return } this.setTexture2D(normalTexture.glTexture, 1); var camMatrix = this._tempMatrix1; var spriteMatrix = this._tempMatrix2; var calcMatrix = this._tempMatrix3; var u0 = frameX / textureWidth + uOffset; var v0 = frameY / textureHeight + vOffset; var u1 = (frameX + frameWidth) / textureWidth + uOffset; var v1 = (frameY + frameHeight) / textureHeight + vOffset; var width = srcWidth; var height = srcHeight; var x = -displayOriginX; var y = -displayOriginY; if (gameObject.isCropped) { var crop = gameObject._crop; width = crop.width; height = crop.height; srcWidth = crop.width; srcHeight = crop.height; frameX = crop.x; frameY = crop.y; var ox = frameX; var oy = frameY; if (flipX) { ox = frameWidth - crop.x - crop.width } if (flipY && !texture.isRenderTexture) { oy = frameHeight - crop.y - crop.height } u0 = ox / textureWidth + uOffset; v0 = oy / textureHeight + vOffset; u1 = (ox + crop.width) / textureWidth + uOffset; v1 = (oy + crop.height) / textureHeight + vOffset; x = -displayOriginX + frameX; y = -displayOriginY + frameY } flipY = flipY ^ (texture.isRenderTexture ? 1 : 0); if (flipX) { width *= -1; x += srcWidth } if (flipY) { height *= -1; y += srcHeight } var xw = x + width; var yh = y + height; spriteMatrix.applyITRS(srcX, srcY, rotation, scaleX, scaleY); camMatrix.copyFrom(camera.matrix); if (parentTransformMatrix) { camMatrix.multiplyWithOffset(parentTransformMatrix, -camera.scrollX * scrollFactorX, -camera.scrollY * scrollFactorY); spriteMatrix.e = srcX; spriteMatrix.f = srcY; camMatrix.multiply(spriteMatrix, calcMatrix) } else { spriteMatrix.e -= camera.scrollX * scrollFactorX; spriteMatrix.f -= camera.scrollY * scrollFactorY; camMatrix.multiply(spriteMatrix, calcMatrix) } var tx0 = calcMatrix.getX(x, y); var ty0 = calcMatrix.getY(x, y); var tx1 = calcMatrix.getX(x, yh); var ty1 = calcMatrix.getY(x, yh); var tx2 = calcMatrix.getX(xw, yh); var ty2 = calcMatrix.getY(xw, yh); var tx3 = calcMatrix.getX(xw, y); var ty3 = calcMatrix.getY(xw, y); if (camera.roundPixels) { tx0 |= 0; ty0 |= 0; tx1 |= 0; ty1 |= 0; tx2 |= 0; ty2 |= 0; tx3 |= 0; ty3 |= 0 } this.setTexture2D(texture, 0); this.batchQuad(tx0, ty0, tx1, ty1, tx2, ty2, tx3, ty3, u0, v0, u1, v1, tintTL, tintTR, tintBL, tintBR, tintEffect) }, setNormalMap: function(gameObject) { if (!this.active || !gameObject) { return } var normalTexture; if (gameObject.texture) { normalTexture = gameObject.texture.dataSource[gameObject.frame.sourceIndex] } if (!normalTexture) { normalTexture = this.defaultNormalMap } this.setTexture2D(normalTexture.glTexture, 1); this.renderer.setPipeline(gameObject.defaultPipeline) }, batchSprite: function(sprite, camera, parentTransformMatrix) { if (!this.active) { return } var normalTexture = sprite.texture.dataSource[sprite.frame.sourceIndex]; if (normalTexture) { this.renderer.setPipeline(this); this.setTexture2D(normalTexture.glTexture, 1); TextureTintPipeline.prototype.batchSprite.call(this, sprite, camera, parentTransformMatrix) } } }); ForwardDiffuseLightPipeline.LIGHT_COUNT = LIGHT_COUNT; module.exports = ForwardDiffuseLightPipeline }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var CONST = __webpack_require__(312); var EventEmitter = __webpack_require__(11); var Mouse = __webpack_require__(313); var Pointer = __webpack_require__(314); var Rectangle = __webpack_require__(9); var Touch = __webpack_require__(316); var TransformMatrix = __webpack_require__(48); var TransformXY = __webpack_require__(317); var InputManager = new Class({ initialize: function InputManager(game, config) { this.game = game; this.canvas; this.config = config; this.enabled = true; this.events = new EventEmitter; this.queue = []; this.domCallbacks = { up: [], down: [], move: [], upOnce: [], downOnce: [], moveOnce: [] }; this._hasUpCallback = false; this._hasDownCallback = false; this._hasMoveCallback = false; this._customCursor = ""; this._setCursor = 0; this.defaultCursor = ""; this.mouse = config.inputMouse ? new Mouse(this) : null; this.touch = config.inputTouch ? new Touch(this) : null; this.pointers = []; this.pointersTotal = config.inputActivePointers; if (config.inputTouch && this.pointersTotal === 1) { this.pointersTotal = 2 } for (var i = 0; i <= this.pointersTotal; i++) { this.pointers.push(new Pointer(this, i)) } this.mousePointer = config.inputMouse ? this.pointers[0] : null; this.activePointer = this.pointers[0]; this.dirty = false; this.scale = { x: 1, y: 1 }; this.globalTopOnly = true; this.ignoreEvents = false; this.bounds = new Rectangle; this._tempPoint = { x: 0, y: 0 }; this._tempHitTest = []; this._tempMatrix = new TransformMatrix; this._tempMatrix2 = new TransformMatrix; game.events.once("boot", this.boot, this) }, boot: function() { this.canvas = this.game.canvas; this.updateBounds(); this.events.emit("boot"); this.game.events.on("prestep", this.update, this); this.game.events.on("poststep", this.postUpdate, this); this.game.events.once("destroy", this.destroy, this) }, updateBounds: function() { var bounds = this.bounds; var clientRect = this.canvas.getBoundingClientRect(); bounds.x = clientRect.left + window.pageXOffset - document.documentElement.clientLeft; bounds.y = clientRect.top + window.pageYOffset - document.documentElement.clientTop; bounds.width = clientRect.width; bounds.height = clientRect.height }, resize: function() { this.updateBounds(); var gw = this.game.config.width; var gh = this.game.config.height; var bw = this.bounds.width; var bh = this.bounds.height; this.scale.x = gw / bw; this.scale.y = gh / bh }, update: function(time) { var i; this._setCursor = 0; this.events.emit("update"); this.ignoreEvents = false; this.dirty = false; var len = this.queue.length; var pointers = this.pointers; for (i = 0; i < this.pointersTotal; i++) { pointers[i].reset() } if (!this.enabled || len === 0) { return } this.dirty = true; this.updateBounds(); this.scale.x = this.game.config.width / this.bounds.width; this.scale.y = this.game.config.height / this.bounds.height; var queue = this.queue.splice(0, len); var mouse = this.mousePointer; for (i = 0; i < len; i += 2) { var type = queue[i]; var event = queue[i + 1]; switch (type) { case CONST.MOUSE_DOWN: mouse.down(event, time); break; case CONST.MOUSE_MOVE: mouse.move(event, time); break; case CONST.MOUSE_UP: mouse.up(event, time); break; case CONST.TOUCH_START: this.startPointer(event, time); break; case CONST.TOUCH_MOVE: this.updatePointer(event, time); break; case CONST.TOUCH_END: this.stopPointer(event, time); break; case CONST.TOUCH_CANCEL: this.cancelPointer(event, time); break; case CONST.POINTER_LOCK_CHANGE: this.events.emit("pointerlockchange", event, this.mouse.locked); break } } }, postUpdate: function() { if (this._setCursor === 1) { this.canvas.style.cursor = this._customCursor } else if (this._setCursor === 2) { this.canvas.style.cursor = this.defaultCursor } }, setDefaultCursor: function(cursor) { this.defaultCursor = cursor; if (this.canvas.style.cursor !== cursor) { this.canvas.style.cursor = cursor } }, setCursor: function(interactiveObject) { if (interactiveObject.cursor) { this._setCursor = 1; this._customCursor = interactiveObject.cursor } }, resetCursor: function(interactiveObject) { if (interactiveObject.cursor) { this._setCursor = 2 } }, startPointer: function(event, time) { var pointers = this.pointers; for (var c = 0; c < event.changedTouches.length; c++) { var changedTouch = event.changedTouches[c]; for (var i = 1; i < this.pointersTotal; i++) { var pointer = pointers[i]; if (!pointer.active) { pointer.touchstart(changedTouch, time); this.activePointer = pointer; break } } } }, updatePointer: function(event, time) { var pointers = this.pointers; for (var c = 0; c < event.changedTouches.length; c++) { var changedTouch = event.changedTouches[c]; for (var i = 1; i < this.pointersTotal; i++) { var pointer = pointers[i]; if (pointer.active && pointer.identifier === changedTouch.identifier) { pointer.touchmove(changedTouch, time); this.activePointer = pointer; break } } } }, stopPointer: function(event, time) { var pointers = this.pointers; for (var c = 0; c < event.changedTouches.length; c++) { var changedTouch = event.changedTouches[c]; for (var i = 1; i < this.pointersTotal; i++) { var pointer = pointers[i]; if (pointer.active && pointer.identifier === changedTouch.identifier) { pointer.touchend(changedTouch, time); break } } } }, cancelPointer: function(event, time) { var pointers = this.pointers; for (var c = 0; c < event.changedTouches.length; c++) { var changedTouch = event.changedTouches[c]; for (var i = 1; i < this.pointersTotal; i++) { var pointer = pointers[i]; if (pointer.active && pointer.identifier === changedTouch.identifier) { pointer.touchend(changedTouch, time); break } } } }, addPointer: function(quantity) { if (quantity === undefined) { quantity = 1 } var output = []; if (this.pointersTotal + quantity > 10) { quantity = 10 - this.pointersTotal } for (var i = 0; i < quantity; i++) { var id = this.pointers.length; var pointer = new Pointer(this, id); this.pointers.push(pointer); this.pointersTotal++; output.push(pointer) } return output }, processDomCallbacks: function(once, every, event) { var i = 0; for (i = 0; i < once.length; i++) { once[i](event) } for (i = 0; i < every.length; i++) { every[i](event) } once = []; return every.length > 0 }, queueTouchStart: function(event) { this.queue.push(CONST.TOUCH_START, event); if (this._hasDownCallback) { var callbacks = this.domCallbacks; this._hasDownCallback = this.processDomCallbacks(callbacks.downOnce, callbacks.down, event) } }, queueTouchMove: function(event) { this.queue.push(CONST.TOUCH_MOVE, event); if (this._hasMoveCallback) { var callbacks = this.domCallbacks; this._hasMoveCallback = this.processDomCallbacks(callbacks.moveOnce, callbacks.move, event) } }, queueTouchEnd: function(event) { this.queue.push(CONST.TOUCH_END, event); if (this._hasUpCallback) { var callbacks = this.domCallbacks; this._hasUpCallback = this.processDomCallbacks(callbacks.upOnce, callbacks.up, event) } }, queueTouchCancel: function(event) { this.queue.push(CONST.TOUCH_CANCEL, event) }, queueMouseDown: function(event) { this.queue.push(CONST.MOUSE_DOWN, event); if (this._hasDownCallback) { var callbacks = this.domCallbacks; this._hasDownCallback = this.processDomCallbacks(callbacks.downOnce, callbacks.down, event) } }, queueMouseMove: function(event) { this.queue.push(CONST.MOUSE_MOVE, event); if (this._hasMoveCallback) { var callbacks = this.domCallbacks; this._hasMoveCallback = this.processDomCallbacks(callbacks.moveOnce, callbacks.move, event) } }, queueMouseUp: function(event) { this.queue.push(CONST.MOUSE_UP, event); if (this._hasUpCallback) { var callbacks = this.domCallbacks; this._hasUpCallback = this.processDomCallbacks(callbacks.upOnce, callbacks.up, event) } }, addUpCallback: function(callback, isOnce) { if (isOnce === undefined) { isOnce = true } if (isOnce) { this.domCallbacks.upOnce.push(callback) } else { this.domCallbacks.up.push(callback) } this._hasUpCallback = true; return this }, addDownCallback: function(callback, isOnce) { if (isOnce === undefined) { isOnce = true } if (isOnce) { this.domCallbacks.downOnce.push(callback) } else { this.domCallbacks.down.push(callback) } this._hasDownCallback = true; return this }, addMoveCallback: function(callback, isOnce) { if (isOnce === undefined) { isOnce = false } if (isOnce) { this.domCallbacks.moveOnce.push(callback) } else { this.domCallbacks.move.push(callback) } this._hasMoveCallback = true; return this }, inputCandidate: function(gameObject, camera) { var input = gameObject.input; if (!input || !input.enabled || !gameObject.willRender(camera)) { return false } var visible = true; var parent = gameObject.parentContainer; if (parent) { do { if (!parent.willRender(camera)) { visible = false; break } parent = parent.parentContainer } while (parent) } return visible }, hitTest: function(pointer, gameObjects, camera, output) { if (output === undefined) { output = this._tempHitTest } var tempPoint = this._tempPoint; var csx = camera.scrollX; var csy = camera.scrollY; output.length = 0; var x = pointer.x; var y = pointer.y; if (camera.resolution !== 1) { x += camera._x; y += camera._y } camera.getWorldPoint(x, y, tempPoint); pointer.worldX = tempPoint.x; pointer.worldY = tempPoint.y; var point = { x: 0, y: 0 }; var matrix = this._tempMatrix; var parentMatrix = this._tempMatrix2; for (var i = 0; i < gameObjects.length; i++) { var gameObject = gameObjects[i]; if (!this.inputCandidate(gameObject, camera)) { continue } var px = tempPoint.x + csx * gameObject.scrollFactorX - csx; var py = tempPoint.y + csy * gameObject.scrollFactorY - csy; if (gameObject.parentContainer) { gameObject.getWorldTransformMatrix(matrix, parentMatrix); matrix.applyInverse(px, py, point) } else { TransformXY(px, py, gameObject.x, gameObject.y, gameObject.rotation, gameObject.scaleX, gameObject.scaleY, point) } if (this.pointWithinHitArea(gameObject, point.x, point.y)) { output.push(gameObject) } } return output }, pointWithinHitArea: function(gameObject, x, y) { x += gameObject.displayOriginX; y += gameObject.displayOriginY; var input = gameObject.input; if (input && input.hitAreaCallback(input.hitArea, x, y, gameObject)) { input.localX = x; input.localY = y; return true } else { return false } }, pointWithinInteractiveObject: function(object, x, y) { if (!object.hitArea) { return false } x += object.gameObject.displayOriginX; y += object.gameObject.displayOriginY; object.localX = x; object.localY = y; return object.hitAreaCallback(object.hitArea, x, y, object) }, transformPointer: function(pointer, pageX, pageY) { pointer.prevPosition.x = pointer.x; pointer.prevPosition.y = pointer.y; pointer.x = (pageX - this.bounds.left) * this.scale.x; pointer.y = (pageY - this.bounds.top) * this.scale.y }, transformX: function(pageX) { return (pageX - this.bounds.left) * this.scale.x }, transformY: function(pageY) { return (pageY - this.bounds.top) * this.scale.y }, getOffsetX: function() { return this.bounds.left }, getOffsetY: function() { return this.bounds.top }, getScaleX: function() { return this.game.config.width / this.bounds.width }, getScaleY: function() { return this.game.config.height / this.bounds.height }, destroy: function() { this.events.removeAllListeners(); if (this.mouse) { this.mouse.destroy() } if (this.touch) { this.touch.destroy() } for (var i = 0; i < this.pointers.length; i++) { this.pointers[i].destroy() } this.domCallbacks = {}; this.pointers = []; this.queue = []; this._tempHitTest = []; this._tempMatrix.destroy(); this.canvas = null; this.game = null } }); module.exports = InputManager }, function(module, exports) { var INPUT_CONST = { MOUSE_DOWN: 0, MOUSE_MOVE: 1, MOUSE_UP: 2, TOUCH_START: 3, TOUCH_MOVE: 4, TOUCH_END: 5, TOUCH_CANCEL: 7, POINTER_LOCK_CHANGE: 6 }; module.exports = INPUT_CONST }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Features = __webpack_require__(169); var MouseManager = new Class({ initialize: function MouseManager(inputManager) { this.manager = inputManager; this.capture = true; this.enabled = false; this.target; this.locked = false; inputManager.events.once("boot", this.boot, this) }, boot: function() { var config = this.manager.config; this.enabled = config.inputMouse; this.target = config.inputMouseEventTarget; this.capture = config.inputMouseCapture; if (!this.target) { this.target = this.manager.game.canvas } if (config.disableContextMenu) { this.disableContextMenu() } if (this.enabled) { this.startListeners() } }, disableContextMenu: function() { document.body.addEventListener("contextmenu", function(event) { event.preventDefault(); return false }); return this }, requestPointerLock: function() { if (Features.pointerLock) { var element = this.target; element.requestPointerLock = element.requestPointerLock || element.mozRequestPointerLock || element.webkitRequestPointerLock; element.requestPointerLock() } }, releasePointerLock: function() { if (Features.pointerLock) { document.exitPointerLock = document.exitPointerLock || document.mozExitPointerLock || document.webkitExitPointerLock; document.exitPointerLock() } }, startListeners: function() { var _this = this; var onMouseMove = function(event) { if (event.defaultPrevented || !_this.enabled || !_this.manager) { return } _this.manager.queueMouseMove(event); if (_this.capture) { event.preventDefault() } }; var onMouseDown = function(event) { if (event.defaultPrevented || !_this.enabled || !_this.manager) { return } _this.manager.queueMouseDown(event); if (_this.capture) { event.preventDefault() } }; var onMouseUp = function(event) { if (event.defaultPrevented || !_this.enabled || !_this.manager) { return } _this.manager.queueMouseUp(event); if (_this.capture) { event.preventDefault() } }; this.onMouseMove = onMouseMove; this.onMouseDown = onMouseDown; this.onMouseUp = onMouseUp; var target = this.target; var passive = { passive: true }; var nonPassive = { passive: false }; target.addEventListener("mousemove", onMouseMove, this.capture ? nonPassive : passive); target.addEventListener("mousedown", onMouseDown, this.capture ? nonPassive : passive); target.addEventListener("mouseup", onMouseUp, this.capture ? nonPassive : passive); if (Features.pointerLock) { var onPointerLockChange = function(event) { var element = _this.target; _this.locked = document.pointerLockElement === element || document.mozPointerLockElement === element || document.webkitPointerLockElement === element ? true : false; _this.manager.queue.push(event) }; this.pointerLockChange = onPointerLockChange; document.addEventListener("pointerlockchange", onPointerLockChange, true); document.addEventListener("mozpointerlockchange", onPointerLockChange, true); document.addEventListener("webkitpointerlockchange", onPointerLockChange, true) } }, stopListeners: function() { var target = this.target; target.removeEventListener("mousemove", this.onMouseMove); target.removeEventListener("mousedown", this.onMouseDown); target.removeEventListener("mouseup", this.onMouseUp); if (Features.pointerLock) { document.removeEventListener("pointerlockchange", this.pointerLockChange, true); document.removeEventListener("mozpointerlockchange", this.pointerLockChange, true); document.removeEventListener("webkitpointerlockchange", this.pointerLockChange, true) } }, destroy: function() { this.stopListeners(); this.target = null; this.manager = null } }); module.exports = MouseManager }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Distance = __webpack_require__(56); var SmoothStepInterpolation = __webpack_require__(315); var Vector2 = __webpack_require__(3); var Pointer = new Class({ initialize: function Pointer(manager, id) { this.manager = manager; this.id = id; this.event; this.camera = null; this.buttons = 0; this.position = new Vector2; this.prevPosition = new Vector2; this.worldX = 0; this.worldY = 0; this.downX = 0; this.downY = 0; this.downTime = 0; this.upX = 0; this.upY = 0; this.upTime = 0; this.primaryDown = false; this.dragState = 0; this.isDown = false; this.dirty = false; this.justDown = false; this.justUp = false; this.justMoved = false; this.wasTouch = false; this.wasCanceled = false; this.movementX = 0; this.movementY = 0; this.identifier = 0; this.pointerId = null; this.active = id === 0 ? true : false }, positionToCamera: function(camera, output) { return camera.getWorldPoint(this.x, this.y, output) }, reset: function() { this.dirty = false; this.justDown = false; this.justUp = false; this.justMoved = false; this.movementX = 0; this.movementY = 0 }, up: function(event, time) { if (event.buttons) { this.buttons = event.buttons } this.event = event; this.manager.transformPointer(this, event.pageX, event.pageY); if (event.button === 0) { this.primaryDown = false; this.upX = this.x; this.upY = this.y; this.upTime = time } this.justUp = true; this.isDown = false; this.dirty = true; this.wasTouch = false }, down: function(event, time) { if (event.buttons) { this.buttons = event.buttons } this.event = event; this.manager.transformPointer(this, event.pageX, event.pageY); if (event.button === 0) { this.primaryDown = true; this.downX = this.x; this.downY = this.y; this.downTime = time } this.justDown = true; this.isDown = true; this.dirty = true; this.wasTouch = false }, move: function(event) { if (event.buttons) { this.buttons = event.buttons } this.event = event; this.manager.transformPointer(this, event.pageX, event.pageY); if (this.manager.mouse.locked) { this.movementX += event.movementX || event.mozMovementX || event.webkitMovementX || 0; this.movementY += event.movementY || event.mozMovementY || event.webkitMovementY || 0 } this.justMoved = true; this.dirty = true; this.wasTouch = false }, touchstart: function(event, time) { if (event["pointerId"]) { this.pointerId = event.pointerId } this.identifier = event.identifier; this.target = event.target; this.active = true; this.buttons = 1; this.event = event; this.manager.transformPointer(this, event.pageX, event.pageY); this.primaryDown = true; this.downX = this.x; this.downY = this.y; this.downTime = time; this.justDown = true; this.isDown = true; this.dirty = true; this.wasTouch = true; this.wasCanceled = false }, touchmove: function(event) { this.event = event; this.manager.transformPointer(this, event.pageX, event.pageY); this.justMoved = true; this.dirty = true; this.wasTouch = true }, touchend: function(event, time) { this.buttons = 0; this.event = event; this.manager.transformPointer(this, event.pageX, event.pageY); this.primaryDown = false; this.upX = this.x; this.upY = this.y; this.upTime = time; this.justUp = true; this.isDown = false; this.dirty = true; this.wasTouch = true; this.wasCanceled = false; this.active = false }, touchcancel: function(event) { this.buttons = 0; this.event = event; this.primaryDown = false; this.justUp = false; this.isDown = false; this.dirty = true; this.wasTouch = true; this.wasCanceled = true; this.active = false }, noButtonDown: function() { return this.buttons === 0 }, leftButtonDown: function() { return this.buttons & 1 }, rightButtonDown: function() { return this.buttons & 2 }, middleButtonDown: function() { return this.buttons & 4 }, backButtonDown: function() { return this.buttons & 8 }, forwardButtonDown: function() { return this.buttons & 16 }, getDistance: function() { return Distance(this.downX, this.downY, this.x, this.y) }, getInterpolatedPosition: function(steps, out) { if (steps === undefined) { steps = 10 } if (out === undefined) { out = [] } var prevX = this.prevPosition.x; var prevY = this.prevPosition.y; var curX = this.position.x; var curY = this.position.y; for (var i = 0; i < steps; i++) { var t = 1 / steps * i; out[i] = { x: SmoothStepInterpolation(t, prevX, curX), y: SmoothStepInterpolation(t, prevY, curY) } } return out }, destroy: function() { this.camera = null; this.manager = null; this.position = null }, x: { get: function() { return this.position.x }, set: function(value) { this.position.x = value } }, y: { get: function() { return this.position.y }, set: function(value) { this.position.y = value } } }); module.exports = Pointer }, function(module, exports, __webpack_require__) { var SmoothStep = __webpack_require__(156); var SmoothStepInterpolation = function(t, min, max) { return min + (max - min) * SmoothStep(t, 0, 1) }; module.exports = SmoothStepInterpolation }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var NOOP = __webpack_require__(2); var TouchManager = new Class({ initialize: function TouchManager(inputManager) { this.manager = inputManager; this.capture = true; this.enabled = false; this.target; this.onTouchStart = NOOP; this.onTouchMove = NOOP; this.onTouchEnd = NOOP; this.onTouchCancel = NOOP; inputManager.events.once("boot", this.boot, this) }, boot: function() { var config = this.manager.config; this.enabled = config.inputTouch; this.target = config.inputTouchEventTarget; this.capture = config.inputTouchCapture; if (!this.target) { this.target = this.manager.game.canvas } if (this.enabled && this.target) { this.startListeners() } }, startListeners: function() { var _this = this; this.onTouchStart = function(event) { if (event.defaultPrevented || !_this.enabled || !_this.manager) { return } _this.manager.queueTouchStart(event); if (_this.capture) { event.preventDefault() } }; this.onTouchMove = function(event) { if (event.defaultPrevented || !_this.enabled || !_this.manager) { return } _this.manager.queueTouchMove(event); if (_this.capture) { event.preventDefault() } }; this.onTouchEnd = function(event) { if (event.defaultPrevented || !_this.enabled || !_this.manager) { return } _this.manager.queueTouchEnd(event); if (_this.capture) { event.preventDefault() } }; this.onTouchCancel = function(event) { if (event.defaultPrevented || !_this.enabled || !_this.manager) { return } _this.manager.queueTouchCancel(event); if (_this.capture) { event.preventDefault() } }; var target = this.target; if (!target) { return } var passive = { passive: true }; var nonPassive = { passive: false }; if (this.capture) { target.addEventListener("touchstart", this.onTouchStart, nonPassive); target.addEventListener("touchmove", this.onTouchMove, nonPassive); target.addEventListener("touchend", this.onTouchEnd, nonPassive); target.addEventListener("touchcancel", this.onTouchCancel, nonPassive) } else { target.addEventListener("touchstart", this.onTouchStart, passive); target.addEventListener("touchmove", this.onTouchMove, passive); target.addEventListener("touchend", this.onTouchEnd, passive) } this.enabled = true }, stopListeners: function() { var target = this.target; target.removeEventListener("touchstart", this.onTouchStart); target.removeEventListener("touchmove", this.onTouchMove); target.removeEventListener("touchend", this.onTouchEnd); target.removeEventListener("touchcancel", this.onTouchCancel) }, destroy: function() { this.stopListeners(); this.target = null; this.enabled = false; this.manager = null } }); module.exports = TouchManager }, function(module, exports, __webpack_require__) { var Vector2 = __webpack_require__(3); var TransformXY = function(x, y, positionX, positionY, rotation, scaleX, scaleY, output) { if (output === undefined) { output = new Vector2 } var radianSin = Math.sin(rotation); var radianCos = Math.cos(rotation); var a = radianCos * scaleX; var b = radianSin * scaleX; var c = -radianSin * scaleY; var d = radianCos * scaleY; var id = 1 / (a * d + c * -b); output.x = d * id * x + -c * id * y + (positionY * c - positionX * d) * id; output.y = a * id * y + -b * id * x + (-positionY * a + positionX * b) * id; return output }; module.exports = TransformXY }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var EventEmitter = __webpack_require__(11); var FileTypesManager = __webpack_require__(8); var GameObjectCreator = __webpack_require__(16); var GameObjectFactory = __webpack_require__(5); var GetFastValue = __webpack_require__(1); var PluginCache = __webpack_require__(15); var Remove = __webpack_require__(319); var PluginManager = new Class({ Extends: EventEmitter, initialize: function PluginManager(game) { EventEmitter.call(this); this.game = game; this.plugins = []; this.scenePlugins = []; this._pendingGlobal = []; this._pendingScene = []; if (game.isBooted) { this.boot() } else { game.events.once("boot", this.boot, this) } }, boot: function() { var i; var entry; var key; var plugin; var start; var mapping; var data; var config = this.game.config; var list = config.installGlobalPlugins; list = list.concat(this._pendingGlobal); for (i = 0; i < list.length; i++) { entry = list[i]; key = GetFastValue(entry, "key", null); plugin = GetFastValue(entry, "plugin", null); start = GetFastValue(entry, "start", false); mapping = GetFastValue(entry, "mapping", null); data = GetFastValue(entry, "data", null); if (key && plugin) { this.install(key, plugin, start, mapping, data) } } list = config.installScenePlugins; list = list.concat(this._pendingScene); for (i = 0; i < list.length; i++) { entry = list[i]; key = GetFastValue(entry, "key", null); plugin = GetFastValue(entry, "plugin", null); mapping = GetFastValue(entry, "mapping", null); if (key && plugin) { this.installScenePlugin(key, plugin, mapping) } } this._pendingGlobal = []; this._pendingScene = []; this.game.events.once("destroy", this.destroy, this) }, addToScene: function(sys, globalPlugins, scenePlugins) { var i; var pluginKey; var pluginList; var game = this.game; var scene = sys.scene; var map = sys.settings.map; var isBooted = sys.settings.isBooted; for (i = 0; i < globalPlugins.length; i++) { pluginKey = globalPlugins[i]; if (game[pluginKey]) { sys[pluginKey] = game[pluginKey]; if (map.hasOwnProperty(pluginKey)) { scene[map[pluginKey]] = sys[pluginKey] } } else if (pluginKey === "game" && map.hasOwnProperty(pluginKey)) { scene[map[pluginKey]] = game } } for (var s = 0; s < scenePlugins.length; s++) { pluginList = scenePlugins[s]; for (i = 0; i < pluginList.length; i++) { pluginKey = pluginList[i]; if (!PluginCache.hasCore(pluginKey)) { continue } var source = PluginCache.getCore(pluginKey); var plugin = new source.plugin(scene, this); sys[source.mapping] = plugin; if (source.custom) { scene[source.mapping] = plugin } else if (map.hasOwnProperty(source.mapping)) { scene[map[source.mapping]] = plugin } if (isBooted) { plugin.boot() } } } pluginList = this.plugins; for (i = 0; i < pluginList.length; i++) { var entry = pluginList[i]; if (entry.mapping) { scene[entry.mapping] = entry.plugin } } }, getDefaultScenePlugins: function() { var list = this.game.config.defaultPlugins; list = list.concat(this.scenePlugins); return list }, installScenePlugin: function(key, plugin, mapping, addToScene) { if (typeof plugin !== "function") { console.warn("Invalid Scene Plugin: " + key); return } if (PluginCache.hasCore(key)) { console.warn("Scene Plugin key in use: " + key); return } PluginCache.register(key, plugin, mapping, true); this.scenePlugins.push(key); if (addToScene) { var instance = new plugin(addToScene, this); addToScene.sys[key] = instance; if (mapping && mapping !== "") { addToScene[mapping] = instance } instance.boot() } }, install: function(key, plugin, start, mapping, data) { if (start === undefined) { start = false } if (mapping === undefined) { mapping = null } if (data === undefined) { data = null } if (typeof plugin !== "function") { console.warn("Invalid Plugin: " + key); return } if (PluginCache.hasCustom(key)) { console.warn("Plugin key in use: " + key); return } if (mapping !== null) { start = true } if (!this.game.isBooted) { this._pendingGlobal.push({ key: key, plugin: plugin, start: start, mapping: mapping, data: data }) } else { PluginCache.registerCustom(key, plugin, mapping, data); if (start) { return this.start(key) } } }, getIndex: function(key) { var list = this.plugins; for (var i = 0; i < list.length; i++) { var entry = list[i]; if (entry.key === key) { return i } } return -1 }, getEntry: function(key) { var idx = this.getIndex(key); if (idx !== -1) { return this.plugins[idx] } }, isActive: function(key) { var entry = this.getEntry(key); return entry && entry.active }, start: function(key, runAs) { if (runAs === undefined) { runAs = key } var entry = this.getEntry(runAs); if (entry && !entry.active) { entry.active = true; entry.plugin.start() } else if (!entry) { entry = this.createEntry(key, runAs) } return entry ? entry.plugin : null }, createEntry: function(key, runAs) { var entry = PluginCache.getCustom(key); if (entry) { var instance = new entry.plugin(this); entry = { key: runAs, plugin: instance, active: true, mapping: entry.mapping, data: entry.data }; this.plugins.push(entry); instance.init(entry.data); instance.start() } return entry }, stop: function(key) { var entry = this.getEntry(key); if (entry && entry.active) { entry.active = false; entry.plugin.stop() } return this }, get: function(key, autoStart) { if (autoStart === undefined) { autoStart = true } var entry = this.getEntry(key); if (entry) { return entry.plugin } else { var plugin = this.getClass(key); if (plugin && autoStart) { entry = this.createEntry(key, key); return entry ? entry.plugin : null } else if (plugin) { return plugin } } return null }, getClass: function(key) { return PluginCache.getCustomClass(key) }, removeGlobalPlugin: function(key) { var entry = this.getEntry(key); if (entry) { Remove(this.plugins, entry) } PluginCache.removeCustom(key) }, removeScenePlugin: function(key) { Remove(this.scenePlugins, key); PluginCache.remove(key) }, registerGameObject: function(key, factoryCallback, creatorCallback) { if (factoryCallback) { GameObjectFactory.register(key, factoryCallback) } if (creatorCallback) { GameObjectCreator.register(key, creatorCallback) } return this }, registerFileType: function(key, callback, addToScene) { FileTypesManager.register(key, callback); if (addToScene && addToScene.sys.load) { addToScene.sys.load[key] = callback } }, destroy: function() { for (var i = 0; i < this.plugins.length; i++) { this.plugins[i].plugin.destroy() } PluginCache.destroyCustomPlugins(); if (this.game.noReturn) { PluginCache.destroyCorePlugins() } this.game = null; this.plugins = []; this.scenePlugins = [] } }); module.exports = PluginManager }, function(module, exports, __webpack_require__) { var SpliceOne = __webpack_require__(93); var Remove = function(array, item, callback, context) { if (context === undefined) { context = array } var index; if (!Array.isArray(item)) { index = array.indexOf(item); if (index !== -1) { SpliceOne(array, index); if (callback) { callback.call(context, item) } return item } else { return null } } var itemLength = item.length - 1; while (itemLength >= 0) { var entry = item[itemLength]; index = array.indexOf(entry); if (index !== -1) { SpliceOne(array, index); if (callback) { callback.call(context, entry) } } else { item.pop() } itemLength-- } return item }; module.exports = Remove }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var CONST = __webpack_require__(117); var GetValue = __webpack_require__(4); var NOOP = __webpack_require__(2); var Scene = __webpack_require__(321); var Systems = __webpack_require__(173); var SceneManager = new Class({ initialize: function SceneManager(game, sceneConfig) { this.game = game; this.keys = {}; this.scenes = []; this._pending = []; this._start = []; this._queue = []; this._data = {}; this.isProcessing = false; this.isBooted = false; this.customViewports = 0; if (sceneConfig) { if (!Array.isArray(sceneConfig)) { sceneConfig = [sceneConfig] } for (var i = 0; i < sceneConfig.length; i++) { this._pending.push({ key: "default", scene: sceneConfig[i], autoStart: i === 0, data: {} }) } } game.events.once("ready", this.bootQueue, this) }, bootQueue: function() { if (this.isBooted) { return } var i; var entry; var key; var sceneConfig; for (i = 0; i < this._pending.length; i++) { entry = this._pending[i]; key = entry.key; sceneConfig = entry.scene; var newScene; if (sceneConfig instanceof Scene) { newScene = this.createSceneFromInstance(key, sceneConfig) } else if (typeof sceneConfig === "object") { newScene = this.createSceneFromObject(key, sceneConfig) } else if (typeof sceneConfig === "function") { newScene = this.createSceneFromFunction(key, sceneConfig) } key = newScene.sys.settings.key; this.keys[key] = newScene; this.scenes.push(newScene); if (this._data[key]) { newScene.sys.settings.data = this._data[key].data; if (this._data[key].autoStart) { entry.autoStart = true } } if (entry.autoStart || newScene.sys.settings.active) { this._start.push(key) } } this._pending.length = 0; this._data = {}; this.isBooted = true; for (i = 0; i < this._start.length; i++) { entry = this._start[i]; this.start(entry) } this._start.length = 0 }, processQueue: function() { var pendingLength = this._pending.length; var queueLength = this._queue.length; if (pendingLength === 0 && queueLength === 0) { return } var i; var entry; if (pendingLength) { for (i = 0; i < pendingLength; i++) { entry = this._pending[i]; this.add(entry.key, entry.scene, entry.autoStart, entry.data) } for (i = 0; i < this._start.length; i++) { entry = this._start[i]; this.start(entry) } this._start.length = 0; this._pending.length = 0; return } for (i = 0; i < this._queue.length; i++) { entry = this._queue[i]; this[entry.op](entry.keyA, entry.keyB) } this._queue.length = 0 }, add: function(key, sceneConfig, autoStart, data) { if (autoStart === undefined) { autoStart = false } if (data === undefined) { data = {} } if (this.isProcessing || !this.isBooted) { this._pending.push({ key: key, scene: sceneConfig, autoStart: autoStart, data: data }); if (!this.isBooted) { this._data[key] = { data: data } } return null } key = this.getKey(key, sceneConfig); var newScene; if (sceneConfig instanceof Scene) { newScene = this.createSceneFromInstance(key, sceneConfig) } else if (typeof sceneConfig === "object") { sceneConfig.key = key; newScene = this.createSceneFromObject(key, sceneConfig) } else if (typeof sceneConfig === "function") { newScene = this.createSceneFromFunction(key, sceneConfig) } newScene.sys.settings.data = data; key = newScene.sys.settings.key; this.keys[key] = newScene; this.scenes.push(newScene); if (autoStart || newScene.sys.settings.active) { if (this._pending.length) { this._start.push(key) } else { this.start(key) } } return newScene }, remove: function(key) { if (this.isProcessing) { this._queue.push({ op: "remove", keyA: key, keyB: null }) } else { var sceneToRemove = this.getScene(key); if (!sceneToRemove || sceneToRemove.sys.isTransitioning()) { return this } var index = this.scenes.indexOf(sceneToRemove); var sceneKey = sceneToRemove.sys.settings.key; if (index > -1) { delete this.keys[sceneKey]; this.scenes.splice(index, 1); if (this._start.indexOf(sceneKey) > -1) { index = this._start.indexOf(sceneKey); this._start.splice(index, 1) } sceneToRemove.sys.destroy() } } return this }, bootScene: function(scene) { var sys = scene.sys; var settings = sys.settings; if (scene.init) { scene.init.call(scene, settings.data); settings.status = CONST.INIT; if (settings.isTransition) { sys.events.emit("transitioninit", settings.transitionFrom, settings.transitionDuration) } } var loader; if (sys.load) { loader = sys.load; loader.reset() } if (loader && scene.preload) { scene.preload.call(scene); if (loader.list.size === 0) { this.create(scene) } else { settings.status = CONST.LOADING; loader.once("complete", this.loadComplete, this); loader.start() } } else { this.create(scene) } }, loadComplete: function(loader) { var scene = loader.scene; if (this.game.sound.onBlurPausedSounds) { this.game.sound.unlock() } this.create(scene) }, payloadComplete: function(loader) { this.bootScene(loader.scene) }, update: function(time, delta) { this.processQueue(); this.isProcessing = true; for (var i = this.scenes.length - 1; i >= 0; i--) { var sys = this.scenes[i].sys; if (sys.settings.status > CONST.START && sys.settings.status <= CONST.RUNNING) { sys.step(time, delta) } } }, resize: function(width, height) { for (var i = 0; i < this.scenes.length; i++) { var sys = this.scenes[i].sys; sys.resize(width, height) } }, render: function(renderer) { for (var i = 0; i < this.scenes.length; i++) { var sys = this.scenes[i].sys; if (sys.settings.visible && sys.settings.status >= CONST.LOADING && sys.settings.status < CONST.SLEEPING) { sys.render(renderer) } } this.isProcessing = false }, create: function(scene) { var sys = scene.sys; var settings = sys.settings; if (scene.create) { settings.status = CONST.CREATING; scene.create.call(scene, settings.data); if (settings.isTransition) { sys.events.emit("transitionstart", settings.transitionFrom, settings.transitionDuration) } } if (scene.update) { sys.sceneUpdate = scene.update } settings.status = CONST.RUNNING }, createSceneFromFunction: function(key, scene) { var newScene = new scene; if (newScene instanceof Scene) { var configKey = newScene.sys.settings.key; if (configKey !== "") { key = configKey } if (this.keys.hasOwnProperty(key)) { throw new Error("Cannot add a Scene with duplicate key: " + key) } return this.createSceneFromInstance(key, newScene) } else { newScene.sys = new Systems(newScene); newScene.sys.settings.key = key; newScene.sys.init(this.game); return newScene } }, createSceneFromInstance: function(key, newScene) { var configKey = newScene.sys.settings.key; if (configKey !== "") { key = configKey } else { newScene.sys.settings.key = key } newScene.sys.init(this.game); return newScene }, createSceneFromObject: function(key, sceneConfig) { var newScene = new Scene(sceneConfig); var configKey = newScene.sys.settings.key; if (configKey !== "") { key = configKey } else { newScene.sys.settings.key = key } newScene.sys.init(this.game); var defaults = ["init", "preload", "create", "update", "render"]; for (var i = 0; i < defaults.length; i++) { var sceneCallback = GetValue(sceneConfig, defaults[i], null); if (sceneCallback) { newScene[defaults[i]] = sceneCallback } } if (sceneConfig.hasOwnProperty("extend")) { for (var propertyKey in sceneConfig.extend) { var value = sceneConfig.extend[propertyKey]; if (propertyKey === "data" && newScene.hasOwnProperty("data") && typeof value === "object") { newScene.data.merge(value) } else if (propertyKey !== "sys") { newScene[propertyKey] = value } } } return newScene }, getKey: function(key, sceneConfig) { if (!key) { key = "default" } if (typeof sceneConfig === "function") { return key } else if (sceneConfig instanceof Scene) { key = sceneConfig.sys.settings.key } else if (typeof sceneConfig === "object" && sceneConfig.hasOwnProperty("key")) { key = sceneConfig.key } if (this.keys.hasOwnProperty(key)) { throw new Error("Cannot add a Scene with duplicate key: " + key) } else { return key } }, getScene: function(key) { if (typeof key === "string") { if (this.keys[key]) { return this.keys[key] } } else { for (var i = 0; i < this.scenes.length; i++) { if (key === this.scenes[i]) { return key } } } return null }, isActive: function(key) { var scene = this.getScene(key); if (scene) { return scene.sys.isActive() } return null }, isVisible: function(key) { var scene = this.getScene(key); if (scene) { return scene.sys.isVisible() } return null }, isSleeping: function(key) { var scene = this.getScene(key); if (scene) { return scene.sys.isSleeping() } return null }, pause: function(key, data) { var scene = this.getScene(key); if (scene) { scene.sys.pause(data) } return this }, resume: function(key, data) { var scene = this.getScene(key); if (scene) { scene.sys.resume(data) } return this }, sleep: function(key, data) { var scene = this.getScene(key); if (scene && !scene.sys.isTransitioning()) { scene.sys.sleep(data) } return this }, wake: function(key, data) { var scene = this.getScene(key); if (scene) { scene.sys.wake(data) } return this }, run: function(key, data) { var scene = this.getScene(key); if (!scene) { for (var i = 0; i < this._pending.length; i++) { if (this._pending[i].key === key) { this.queueOp("start", key, data); break } } return this } if (scene.sys.isSleeping()) { scene.sys.wake(data) } else if (scene.sys.isBooted && !scene.sys.isActive()) { scene.sys.resume(data) } else { this.start(key, data) } }, start: function(key, data) { if (!this.isBooted) { this._data[key] = { autoStart: true, data: data }; return this } var scene = this.getScene(key); if (scene) { if (scene.sys.isActive() || scene.sys.isPaused()) { scene.sys.shutdown(); scene.sys.start(data) } else { scene.sys.start(data); var loader; if (scene.sys.load) { loader = scene.sys.load } if (loader && scene.sys.settings.hasOwnProperty("pack")) { loader.reset(); if (loader.addPack({ payload: scene.sys.settings.pack })) { scene.sys.settings.status = CONST.LOADING; loader.once("complete", this.payloadComplete, this); loader.start(); return this } } } this.bootScene(scene) } return this }, stop: function(key) { var scene = this.getScene(key); if (scene && !scene.sys.isTransitioning()) { scene.sys.shutdown() } return this }, switch: function(from, to) { var sceneA = this.getScene(from); var sceneB = this.getScene(to); if (sceneA && sceneB && sceneA !== sceneB) { this.sleep(from); if (this.isSleeping(to)) { this.wake(to) } else { this.start(to) } } return this }, getAt: function(index) { return this.scenes[index] }, getIndex: function(key) { var scene = this.getScene(key); return this.scenes.indexOf(scene) }, bringToTop: function(key) { if (this.isProcessing) { this._queue.push({ op: "bringToTop", keyA: key, keyB: null }) } else { var index = this.getIndex(key); if (index !== -1 && index < this.scenes.length) { var scene = this.getScene(key); this.scenes.splice(index, 1); this.scenes.push(scene) } } return this }, sendToBack: function(key) { if (this.isProcessing) { this._queue.push({ op: "sendToBack", keyA: key, keyB: null }) } else { var index = this.getIndex(key); if (index !== -1 && index > 0) { var scene = this.getScene(key); this.scenes.splice(index, 1); this.scenes.unshift(scene) } } return this }, moveDown: function(key) { if (this.isProcessing) { this._queue.push({ op: "moveDown", keyA: key, keyB: null }) } else { var indexA = this.getIndex(key); if (indexA > 0) { var indexB = indexA - 1; var sceneA = this.getScene(key); var sceneB = this.getAt(indexB); this.scenes[indexA] = sceneB; this.scenes[indexB] = sceneA } } return this }, moveUp: function(key) { if (this.isProcessing) { this._queue.push({ op: "moveUp", keyA: key, keyB: null }) } else { var indexA = this.getIndex(key); if (indexA < this.scenes.length - 1) { var indexB = indexA + 1; var sceneA = this.getScene(key); var sceneB = this.getAt(indexB); this.scenes[indexA] = sceneB; this.scenes[indexB] = sceneA } } return this }, moveAbove: function(keyA, keyB) { if (keyA === keyB) { return this } if (this.isProcessing) { this._queue.push({ op: "moveAbove", keyA: keyA, keyB: keyB }) } else { var indexA = this.getIndex(keyA); var indexB = this.getIndex(keyB); if (indexA !== -1 && indexB !== -1) { var tempScene = this.getAt(indexB); this.scenes.splice(indexB, 1); this.scenes.splice(indexA + 1, 0, tempScene) } } return this }, moveBelow: function(keyA, keyB) { if (keyA === keyB) { return this } if (this.isProcessing) { this._queue.push({ op: "moveBelow", keyA: keyA, keyB: keyB }) } else { var indexA = this.getIndex(keyA); var indexB = this.getIndex(keyB); if (indexA !== -1 && indexB !== -1) { var tempScene = this.getAt(indexB); this.scenes.splice(indexB, 1); if (indexA === 0) { this.scenes.unshift(tempScene) } else { this.scenes.splice(indexA, 0, tempScene) } } } return this }, queueOp: function(op, keyA, keyB) { this._queue.push({ op: op, keyA: keyA, keyB: keyB }); return this }, swapPosition: function(keyA, keyB) { if (keyA === keyB) { return this } if (this.isProcessing) { this._queue.push({ op: "swapPosition", keyA: keyA, keyB: keyB }) } else { var indexA = this.getIndex(keyA); var indexB = this.getIndex(keyB); if (indexA !== indexB && indexA !== -1 && indexB !== -1) { var tempScene = this.getAt(indexA); this.scenes[indexA] = this.scenes[indexB]; this.scenes[indexB] = tempScene } } return this }, dump: function() { var out = []; var map = ["pending", "init", "start", "loading", "creating", "running", "paused", "sleeping", "shutdown", "destroyed"]; for (var i = 0; i < this.scenes.length; i++) { var sys = this.scenes[i].sys; var key = sys.settings.visible && (sys.settings.status === CONST.RUNNING || sys.settings.status === CONST.PAUSED) ? "[*] " : "[-] "; key += sys.settings.key + " (" + map[sys.settings.status] + ")"; out.push(key) } console.log(out.join("\n")) }, destroy: function() { for (var i = 0; i < this.scenes.length; i++) { var sys = this.scenes[i].sys; sys.destroy() } this.update = NOOP; this.scenes = []; this._pending = []; this._start = []; this._queue = []; this.game = null } }); module.exports = SceneManager }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Systems = __webpack_require__(173); var Scene = new Class({ initialize: function Scene(config) { this.sys = new Systems(this, config); this.game; this.anims; this.cache; this.registry; this.sound; this.textures; this.events; this.cameras; this.add; this.make; this.scene; this.children; this.lights; this.data; this.input; this.load; this.time; this.tweens; this.physics; this.impact; this.matter }, update: function() {} }); module.exports = Scene }, function(module, exports) { var UppercaseFirst = function(str) { return str && str[0].toUpperCase() + str.slice(1) }; module.exports = UppercaseFirst }, function(module, exports, __webpack_require__) { var CONST = __webpack_require__(117); var GetValue = __webpack_require__(4); var Merge = __webpack_require__(80); var InjectionMap = __webpack_require__(646); var Settings = { create: function(config) { if (typeof config === "string") { config = { key: config } } else if (config === undefined) { config = {} } return { status: CONST.PENDING, key: GetValue(config, "key", ""), active: GetValue(config, "active", false), visible: GetValue(config, "visible", true), isBooted: false, isTransition: false, transitionFrom: null, transitionDuration: 0, transitionAllowInput: true, data: {}, pack: GetValue(config, "pack", false), cameras: GetValue(config, "cameras", null), map: GetValue(config, "map", Merge(InjectionMap, GetValue(config, "mapAdd", {}))), physics: GetValue(config, "physics", {}), loader: GetValue(config, "loader", {}), plugins: GetValue(config, "plugins", false), input: GetValue(config, "input", {}) } } }; module.exports = Settings }, function(module, exports, __webpack_require__) { var HTML5AudioSoundManager = __webpack_require__(325); var NoAudioSoundManager = __webpack_require__(327); var WebAudioSoundManager = __webpack_require__(329); var SoundManagerCreator = { create: function(game) { var audioConfig = game.config.audio; var deviceAudio = game.device.audio; if (audioConfig && audioConfig.noAudio || !deviceAudio.webAudio && !deviceAudio.audioData) { return new NoAudioSoundManager(game) } if (deviceAudio.webAudio && !(audioConfig && audioConfig.disableWebAudio)) { return new WebAudioSoundManager(game) } return new HTML5AudioSoundManager(game) } }; module.exports = SoundManagerCreator }, function(module, exports, __webpack_require__) { var BaseSoundManager = __webpack_require__(118); var Class = __webpack_require__(0); var HTML5AudioSound = __webpack_require__(326); var HTML5AudioSoundManager = new Class({ Extends: BaseSoundManager, initialize: function HTML5AudioSoundManager(game) { this.override = true; this.audioPlayDelay = .1; this.loopEndOffset = .05; this.onBlurPausedSounds = []; this.locked = "ontouchstart" in window; this.lockedActionsQueue = this.locked ? [] : null; this._mute = false; this._volume = 1; BaseSoundManager.call(this, game) }, add: function(key, config) { var sound = new HTML5AudioSound(this, key, config); this.sounds.push(sound); return sound }, unlock: function() { this.locked = false; var _this = this; this.game.cache.audio.entries.each(function(key, tags) { for (var i = 0; i < tags.length; i++) { if (tags[i].dataset.locked === "true") { _this.locked = true; return false } } return true }); if (!this.locked) { return } var moved = false; var detectMove = function() { moved = true }; var unlock = function() { if (moved) { moved = false; return } document.body.removeEventListener("touchmove", detectMove); document.body.removeEventListener("touchend", unlock); var lockedTags = []; _this.game.cache.audio.entries.each(function(key, tags) { for (var i = 0; i < tags.length; i++) { var tag = tags[i]; if (tag.dataset.locked === "true") { lockedTags.push(tag) } } return true }); if (lockedTags.length === 0) { return } var lastTag = lockedTags[lockedTags.length - 1]; lastTag.oncanplaythrough = function() { lastTag.oncanplaythrough = null; lockedTags.forEach(function(tag) { tag.dataset.locked = "false" }); _this.unlocked = true }; lockedTags.forEach(function(tag) { tag.load() }) }; this.once("unlocked", function() { this.forEachActiveSound(function(sound) { if (sound.currentMarker === null && sound.duration === 0) { sound.duration = sound.tags[0].duration } sound.totalDuration = sound.tags[0].duration }); while (this.lockedActionsQueue.length) { var lockedAction = this.lockedActionsQueue.shift(); if (lockedAction.sound[lockedAction.prop].apply) { lockedAction.sound[lockedAction.prop].apply(lockedAction.sound, lockedAction.value || []) } else { lockedAction.sound[lockedAction.prop] = lockedAction.value } } }, this); document.body.addEventListener("touchmove", detectMove, false); document.body.addEventListener("touchend", unlock, false) }, onBlur: function() { this.forEachActiveSound(function(sound) { if (sound.isPlaying) { this.onBlurPausedSounds.push(sound); sound.onBlur() } }) }, onFocus: function() { this.onBlurPausedSounds.forEach(function(sound) { sound.onFocus() }); this.onBlurPausedSounds.length = 0 }, destroy: function() { BaseSoundManager.prototype.destroy.call(this); this.onBlurPausedSounds.length = 0; this.onBlurPausedSounds = null }, isLocked: function(sound, prop, value) { if (sound.tags[0].dataset.locked === "true") { this.lockedActionsQueue.push({ sound: sound, prop: prop, value: value }); return true } return false }, setMute: function(value) { this.mute = value; return this }, mute: { get: function() { return this._mute }, set: function(value) { this._mute = value; this.forEachActiveSound(function(sound) { sound.updateMute() }); this.emit("mute", this, value) } }, setVolume: function(value) { this.volume = value; return this }, volume: { get: function() { return this._volume }, set: function(value) { this._volume = value; this.forEachActiveSound(function(sound) { sound.updateVolume() }); this.emit("volume", this, value) } } }); module.exports = HTML5AudioSoundManager }, function(module, exports, __webpack_require__) { var BaseSound = __webpack_require__(119); var Class = __webpack_require__(0); var HTML5AudioSound = new Class({ Extends: BaseSound, initialize: function HTML5AudioSound(manager, key, config) { if (config === undefined) { config = {} } this.tags = manager.game.cache.audio.get(key); if (!this.tags) { console.warn("Audio cache entry missing: " + key); return } this.audio = null; this.startTime = 0; this.previousTime = 0; this.duration = this.tags[0].duration; this.totalDuration = this.tags[0].duration; BaseSound.call(this, manager, key, config) }, play: function(markerName, config) { if (this.manager.isLocked(this, "play", [markerName, config])) { return false } if (!BaseSound.prototype.play.call(this, markerName, config)) { return false } if (!this.pickAndPlayAudioTag()) { return false } this.emit("play", this); return true }, pause: function() { if (this.manager.isLocked(this, "pause")) { return false } if (this.startTime > 0) { return false } if (!BaseSound.prototype.pause.call(this)) { return false } this.currentConfig.seek = this.audio.currentTime - (this.currentMarker ? this.currentMarker.start : 0); this.stopAndReleaseAudioTag(); this.emit("pause", this); return true }, resume: function() { if (this.manager.isLocked(this, "resume")) { return false } if (this.startTime > 0) { return false } if (!BaseSound.prototype.resume.call(this)) { return false } if (!this.pickAndPlayAudioTag()) { return false } this.emit("resume", this); return true }, stop: function() { if (this.manager.isLocked(this, "stop")) { return false } if (!BaseSound.prototype.stop.call(this)) { return false } this.stopAndReleaseAudioTag(); this.emit("stop", this); return true }, pickAndPlayAudioTag: function() { if (!this.pickAudioTag()) { this.reset(); return false } var seek = this.currentConfig.seek; var delay = this.currentConfig.delay; var offset = (this.currentMarker ? this.currentMarker.start : 0) + seek; this.previousTime = offset; this.audio.currentTime = offset; this.applyConfig(); if (delay === 0) { this.startTime = 0; if (this.audio.paused) { this.playCatchPromise() } } else { this.startTime = window.performance.now() + delay * 1e3; if (!this.audio.paused) { this.audio.pause() } } this.resetConfig(); return true }, pickAudioTag: function() { if (this.audio) { return true } for (var i = 0; i < this.tags.length; i++) { var audio = this.tags[i]; if (audio.dataset.used === "false") { audio.dataset.used = "true"; this.audio = audio; return true } } if (!this.manager.override) { return false } var otherSounds = []; this.manager.forEachActiveSound(function(sound) { if (sound.key === this.key && sound.audio) { otherSounds.push(sound) } }, this); otherSounds.sort(function(a1, a2) { if (a1.loop === a2.loop) { return a2.seek / a2.duration - a1.seek / a1.duration } return a1.loop ? 1 : -1 }); var selectedSound = otherSounds[0]; this.audio = selectedSound.audio; selectedSound.reset(); selectedSound.audio = null; selectedSound.startTime = 0; selectedSound.previousTime = 0; return true }, playCatchPromise: function() { var playPromise = this.audio.play(); if (playPromise) { playPromise.catch(function(reason) { console.warn(reason) }) } }, stopAndReleaseAudioTag: function() { this.audio.pause(); this.audio.dataset.used = "false"; this.audio = null; this.startTime = 0; this.previousTime = 0 }, reset: function() { BaseSound.prototype.stop.call(this) }, onBlur: function() { this.isPlaying = false; this.isPaused = true; this.currentConfig.seek = this.audio.currentTime - (this.currentMarker ? this.currentMarker.start : 0); this.currentConfig.delay = Math.max(0, (this.startTime - window.performance.now()) / 1e3); this.stopAndReleaseAudioTag() }, onFocus: function() { this.isPlaying = true; this.isPaused = false; this.pickAndPlayAudioTag() }, update: function(time, delta) { if (!this.isPlaying) { return } if (this.startTime > 0) { if (this.startTime < time - this.manager.audioPlayDelay) { this.audio.currentTime += Math.max(0, time - this.startTime) / 1e3; this.startTime = 0; this.previousTime = this.audio.currentTime; this.playCatchPromise() } return } var startTime = this.currentMarker ? this.currentMarker.start : 0; var endTime = startTime + this.duration; var currentTime = this.audio.currentTime; if (this.currentConfig.loop) { if (currentTime >= endTime - this.manager.loopEndOffset) { this.audio.currentTime = startTime + Math.max(0, currentTime - endTime); currentTime = this.audio.currentTime } else if (currentTime < startTime) { this.audio.currentTime += startTime; currentTime = this.audio.currentTime } if (currentTime < this.previousTime) { this.emit("looped", this) } } else if (currentTime >= endTime) { this.reset(); this.stopAndReleaseAudioTag(); this.emit("ended", this); return } this.previousTime = currentTime }, destroy: function() { BaseSound.prototype.destroy.call(this); this.tags = null; if (this.audio) { this.stopAndReleaseAudioTag() } }, updateMute: function() { if (this.audio) { this.audio.muted = this.currentConfig.mute || this.manager.mute } }, updateVolume: function() { if (this.audio) { this.audio.volume = this.currentConfig.volume * this.manager.volume } }, calculateRate: function() { BaseSound.prototype.calculateRate.call(this); if (this.audio) { this.audio.playbackRate = this.totalRate } }, mute: { get: function() { return this.currentConfig.mute }, set: function(value) { this.currentConfig.mute = value; if (this.manager.isLocked(this, "mute", value)) { return } this.emit("mute", this, value) } }, setMute: function(value) { this.mute = value; return this }, volume: { get: function() { return this.currentConfig.volume }, set: function(value) { this.currentConfig.volume = value; if (this.manager.isLocked(this, "volume", value)) { return } this.emit("volume", this, value) } }, setVolume: function(value) { this.volume = value; return this }, rate: { get: function() { return this.currentConfig.rate }, set: function(value) { this.currentConfig.rate = value; if (this.manager.isLocked(this, "rate", value)) { return } else { this.calculateRate(); this.emit("rate", this, value) } } }, setRate: function(value) { this.rate = value; return this }, detune: { get: function() { return this.currentConfig.detune }, set: function(value) { this.currentConfig.detune = value; if (this.manager.isLocked(this, "detune", value)) { return } else { this.calculateRate(); this.emit("detune", this, value) } } }, setDetune: function(value) { this.detune = value; return this }, seek: { get: function() { if (this.isPlaying) { return this.audio.currentTime - (this.currentMarker ? this.currentMarker.start : 0) } else if (this.isPaused) { return this.currentConfig.seek } else { return 0 } }, set: function(value) { if (this.manager.isLocked(this, "seek", value)) { return } if (this.startTime > 0) { return } if (this.isPlaying || this.isPaused) { value = Math.min(Math.max(0, value), this.duration); if (this.isPlaying) { this.previousTime = value; this.audio.currentTime = value } else if (this.isPaused) { this.currentConfig.seek = value } this.emit("seek", this, value) } } }, setSeek: function(value) { this.seek = value; return this }, loop: { get: function() { return this.currentConfig.loop }, set: function(value) { this.currentConfig.loop = value; if (this.manager.isLocked(this, "loop", value)) { return } if (this.audio) { this.audio.loop = value } this.emit("loop", this, value) } }, setLoop: function(value) { this.loop = value; return this } }); module.exports = HTML5AudioSound }, function(module, exports, __webpack_require__) { var BaseSoundManager = __webpack_require__(118); var Class = __webpack_require__(0); var EventEmitter = __webpack_require__(11); var NoAudioSound = __webpack_require__(328); var NOOP = __webpack_require__(2); var NoAudioSoundManager = new Class({ Extends: EventEmitter, initialize: function NoAudioSoundManager(game) { EventEmitter.call(this); this.game = game; this.sounds = []; this.mute = false; this.volume = 1; this.rate = 1; this.detune = 0; this.pauseOnBlur = true; this.locked = false }, add: function(key, config) { var sound = new NoAudioSound(this, key, config); this.sounds.push(sound); return sound }, addAudioSprite: function(key, config) { var sound = this.add(key, config); sound.spritemap = {}; return sound }, play: function(key, extra) { return false }, playAudioSprite: function(key, spriteName, config) { return false }, remove: function(sound) { return BaseSoundManager.prototype.remove.call(this, sound) }, removeByKey: function(key) { return BaseSoundManager.prototype.removeByKey.call(this, key) }, pauseAll: NOOP, resumeAll: NOOP, stopAll: NOOP, update: NOOP, setRate: NOOP, setDetune: NOOP, setMute: NOOP, setVolume: NOOP, forEachActiveSound: function(callbackfn, scope) { BaseSoundManager.prototype.forEachActiveSound.call(this, callbackfn, scope) }, destroy: function() { BaseSoundManager.prototype.destroy.call(this) } }); module.exports = NoAudioSoundManager }, function(module, exports, __webpack_require__) { var BaseSound = __webpack_require__(119); var Class = __webpack_require__(0); var EventEmitter = __webpack_require__(11); var Extend = __webpack_require__(19); var NoAudioSound = new Class({ Extends: EventEmitter, initialize: function NoAudioSound(manager, key, config) { if (config === void 0) { config = {} } EventEmitter.call(this); this.manager = manager; this.key = key; this.isPlaying = false; this.isPaused = false; this.totalRate = 1; this.duration = 0; this.totalDuration = 0; this.config = Extend({ mute: false, volume: 1, rate: 1, detune: 0, seek: 0, loop: false, delay: 0 }, config); this.currentConfig = this.config; this.mute = false; this.volume = 1; this.rate = 1; this.detune = 0; this.seek = 0; this.loop = false; this.markers = {}; this.currentMarker = null; this.pendingRemove = false }, addMarker: function(marker) { return false }, updateMarker: function(marker) { return false }, removeMarker: function(markerName) { return null }, play: function(markerName, config) { return false }, pause: function() { return false }, resume: function() { return false }, stop: function() { return false }, destroy: function() { this.manager.remove(this); BaseSound.prototype.destroy.call(this) } }); module.exports = NoAudioSound }, function(module, exports, __webpack_require__) { var BaseSoundManager = __webpack_require__(118); var Class = __webpack_require__(0); var WebAudioSound = __webpack_require__(330); var WebAudioSoundManager = new Class({ Extends: BaseSoundManager, initialize: function WebAudioSoundManager(game) { this.context = this.createAudioContext(game); this.masterMuteNode = this.context.createGain(); this.masterVolumeNode = this.context.createGain(); this.masterMuteNode.connect(this.masterVolumeNode); this.masterVolumeNode.connect(this.context.destination); this.destination = this.masterMuteNode; this.locked = this.context.state === "suspended" && ("ontouchstart" in window || "onclick" in window); BaseSoundManager.call(this, game); if (this.locked) { this.unlock() } }, createAudioContext: function(game) { var audioConfig = game.config.audio; if (audioConfig && audioConfig.context) { audioConfig.context.resume(); return audioConfig.context } return new AudioContext }, add: function(key, config) { var sound = new WebAudioSound(this, key, config); this.sounds.push(sound); return sound }, unlock: function() { var _this = this; var unlock = function() { _this.context.resume().then(function() { document.body.removeEventListener("touchstart", unlock); document.body.removeEventListener("touchend", unlock); document.body.removeEventListener("click", unlock); _this.unlocked = true }) }; if (document.body) { document.body.addEventListener("touchstart", unlock, false); document.body.addEventListener("touchend", unlock, false); document.body.addEventListener("click", unlock, false) } }, onBlur: function() { this.context.suspend() }, onFocus: function() { this.context.resume() }, destroy: function() { this.destination = null; this.masterVolumeNode.disconnect(); this.masterVolumeNode = null; this.masterMuteNode.disconnect(); this.masterMuteNode = null; if (this.game.config.audio && this.game.config.audio.context) { this.context.suspend() } else { var _this = this; this.context.close().then(function() { _this.context = null }) } BaseSoundManager.prototype.destroy.call(this) }, setMute: function(value) { this.mute = value; return this }, mute: { get: function() { return this.masterMuteNode.gain.value === 0 }, set: function(value) { this.masterMuteNode.gain.setValueAtTime(value ? 0 : 1, 0); this.emit("mute", this, value) } }, setVolume: function(value) { this.volume = value; return this }, volume: { get: function() { return this.masterVolumeNode.gain.value }, set: function(value) { this.masterVolumeNode.gain.setValueAtTime(value, 0); this.emit("volume", this, value) } } }); module.exports = WebAudioSoundManager }, function(module, exports, __webpack_require__) { var BaseSound = __webpack_require__(119); var Class = __webpack_require__(0); var WebAudioSound = new Class({ Extends: BaseSound, initialize: function WebAudioSound(manager, key, config) { if (config === undefined) { config = {} } this.audioBuffer = manager.game.cache.audio.get(key); if (!this.audioBuffer) { console.warn("Audio cache entry missing: " + key); return } this.source = null; this.loopSource = null; this.muteNode = manager.context.createGain(); this.volumeNode = manager.context.createGain(); this.playTime = 0; this.startTime = 0; this.loopTime = 0; this.rateUpdates = []; this.hasEnded = false; this.hasLooped = false; this.muteNode.connect(this.volumeNode); this.volumeNode.connect(manager.destination); this.duration = this.audioBuffer.duration; this.totalDuration = this.audioBuffer.duration; BaseSound.call(this, manager, key, config) }, play: function(markerName, config) { if (!BaseSound.prototype.play.call(this, markerName, config)) { return false } this.stopAndRemoveBufferSource(); this.createAndStartBufferSource(); this.emit("play", this); return true }, pause: function() { if (this.manager.context.currentTime < this.startTime) { return false } if (!BaseSound.prototype.pause.call(this)) { return false } this.currentConfig.seek = this.getCurrentTime(); this.stopAndRemoveBufferSource(); this.emit("pause", this); return true }, resume: function() { if (this.manager.context.currentTime < this.startTime) { return false } if (!BaseSound.prototype.resume.call(this)) { return false } this.createAndStartBufferSource(); this.emit("resume", this); return true }, stop: function() { if (!BaseSound.prototype.stop.call(this)) { return false } this.stopAndRemoveBufferSource(); this.emit("stop", this); return true }, createAndStartBufferSource: function() { var seek = this.currentConfig.seek; var delay = this.currentConfig.delay; var when = this.manager.context.currentTime + delay; var offset = (this.currentMarker ? this.currentMarker.start : 0) + seek; var duration = this.duration - seek; this.playTime = when - seek; this.startTime = when; this.source = this.createBufferSource(); this.applyConfig(); this.source.start(Math.max(0, when), Math.max(0, offset), Math.max(0, duration)); this.resetConfig() }, createAndStartLoopBufferSource: function() { var when = this.getLoopTime(); var offset = this.currentMarker ? this.currentMarker.start : 0; var duration = this.duration; this.loopTime = when; this.loopSource = this.createBufferSource(); this.loopSource.playbackRate.setValueAtTime(this.totalRate, 0); this.loopSource.start(Math.max(0, when), Math.max(0, offset), Math.max(0, duration)) }, createBufferSource: function() { var _this = this; var source = this.manager.context.createBufferSource(); source.buffer = this.audioBuffer; source.connect(this.muteNode); source.onended = function(ev) { if (ev.target === _this.source) { if (_this.currentConfig.loop) { _this.hasLooped = true } else { _this.hasEnded = true } } }; return source }, stopAndRemoveBufferSource: function() { if (this.source) { this.source.stop(); this.source.disconnect(); this.source = null } this.playTime = 0; this.startTime = 0; this.stopAndRemoveLoopBufferSource() }, stopAndRemoveLoopBufferSource: function() { if (this.loopSource) { this.loopSource.stop(); this.loopSource.disconnect(); this.loopSource = null } this.loopTime = 0 }, applyConfig: function() { this.rateUpdates.length = 0; this.rateUpdates.push({ time: 0, rate: 1 }); BaseSound.prototype.applyConfig.call(this) }, update: function(time, delta) { if (this.hasEnded) { this.hasEnded = false; BaseSound.prototype.stop.call(this); this.stopAndRemoveBufferSource(); this.emit("ended", this) } else if (this.hasLooped) { this.hasLooped = false; this.source = this.loopSource; this.loopSource = null; this.playTime = this.startTime = this.loopTime; this.rateUpdates.length = 0; this.rateUpdates.push({ time: 0, rate: this.totalRate }); this.createAndStartLoopBufferSource(); this.emit("looped", this) } }, destroy: function() { BaseSound.prototype.destroy.call(this); this.audioBuffer = null; this.stopAndRemoveBufferSource(); this.muteNode.disconnect(); this.muteNode = null; this.volumeNode.disconnect(); this.volumeNode = null; this.rateUpdates.length = 0; this.rateUpdates = null }, calculateRate: function() { BaseSound.prototype.calculateRate.call(this); var now = this.manager.context.currentTime; if (this.source && typeof this.totalRate === "number") { this.source.playbackRate.setValueAtTime(this.totalRate, now) } if (this.isPlaying) { this.rateUpdates.push({ time: Math.max(this.startTime, now) - this.playTime, rate: this.totalRate }); if (this.loopSource) { this.stopAndRemoveLoopBufferSource(); this.createAndStartLoopBufferSource() } } }, getCurrentTime: function() { var currentTime = 0; for (var i = 0; i < this.rateUpdates.length; i++) { var nextTime = 0; if (i < this.rateUpdates.length - 1) { nextTime = this.rateUpdates[i + 1].time } else { nextTime = this.manager.context.currentTime - this.playTime } currentTime += (nextTime - this.rateUpdates[i].time) * this.rateUpdates[i].rate } return currentTime }, getLoopTime: function() { var lastRateUpdateCurrentTime = 0; for (var i = 0; i < this.rateUpdates.length - 1; i++) { lastRateUpdateCurrentTime += (this.rateUpdates[i + 1].time - this.rateUpdates[i].time) * this.rateUpdates[i].rate } var lastRateUpdate = this.rateUpdates[this.rateUpdates.length - 1]; return this.playTime + lastRateUpdate.time + (this.duration - lastRateUpdateCurrentTime) / lastRateUpdate.rate }, rate: { get: function() { return this.currentConfig.rate }, set: function(value) { this.currentConfig.rate = value; this.calculateRate(); this.emit("rate", this, value) } }, setRate: function(value) { this.rate = value; return this }, detune: { get: function() { return this.currentConfig.detune }, set: function(value) { this.currentConfig.detune = value; this.calculateRate(); this.emit("detune", this, value) } }, setDetune: function(value) { this.detune = value; return this }, mute: { get: function() { return this.muteNode.gain.value === 0 }, set: function(value) { this.currentConfig.mute = value; this.muteNode.gain.setValueAtTime(value ? 0 : 1, 0); this.emit("mute", this, value) } }, setMute: function(value) { this.mute = value; return this }, volume: { get: function() { return this.volumeNode.gain.value }, set: function(value) { this.currentConfig.volume = value; this.volumeNode.gain.setValueAtTime(value, 0); this.emit("volume", this, value) } }, setVolume: function(value) { this.volume = value; return this }, seek: { get: function() { if (this.isPlaying) { if (this.manager.context.currentTime < this.startTime) { return this.startTime - this.playTime } return this.getCurrentTime() } else if (this.isPaused) { return this.currentConfig.seek } else { return 0 } }, set: function(value) { if (this.manager.context.currentTime < this.startTime) { return } if (this.isPlaying || this.isPaused) { value = Math.min(Math.max(0, value), this.duration); this.currentConfig.seek = value; if (this.isPlaying) { this.stopAndRemoveBufferSource(); this.createAndStartBufferSource() } this.emit("seek", this, value) } } }, setSeek: function(value) { this.seek = value; return this }, loop: { get: function() { return this.currentConfig.loop }, set: function(value) { this.currentConfig.loop = value; if (this.isPlaying) { this.stopAndRemoveLoopBufferSource(); if (value) { this.createAndStartLoopBufferSource() } } this.emit("loop", this, value) } }, setLoop: function(value) { this.loop = value; return this } }); module.exports = WebAudioSound }, function(module, exports, __webpack_require__) { var CanvasPool = __webpack_require__(28); var CanvasTexture = __webpack_require__(647); var Class = __webpack_require__(0); var Color = __webpack_require__(49); var CONST = __webpack_require__(26); var EventEmitter = __webpack_require__(11); var GenerateTexture = __webpack_require__(286); var GetValue = __webpack_require__(4); var Parser = __webpack_require__(333); var Texture = __webpack_require__(174); var TextureManager = new Class({ Extends: EventEmitter, initialize: function TextureManager(game) { EventEmitter.call(this); this.game = game; this.name = "TextureManager"; this.list = {}; this._tempCanvas = CanvasPool.create2D(this, 1, 1); this._tempContext = this._tempCanvas.getContext("2d"); this._pending = 0; game.events.once("boot", this.boot, this) }, boot: function() { this._pending = 2; this.on("onload", this.updatePending, this); this.on("onerror", this.updatePending, this); this.addBase64("__DEFAULT", this.game.config.defaultImage); this.addBase64("__MISSING", this.game.config.missingImage); this.game.events.once("destroy", this.destroy, this) }, updatePending: function() { this._pending--; if (this._pending === 0) { this.off("onload"); this.off("onerror"); this.game.events.emit("texturesready") } }, checkKey: function(key) { if (this.exists(key)) { console.error("Texture key already in use: " + key); return false } return true }, remove: function(key) { if (typeof key === "string") { if (this.exists(key)) { key = this.get(key) } else { console.warn("No texture found matching key: " + key); return this } } if (this.list.hasOwnProperty(key.key)) { delete this.list[key.key]; key.destroy(); this.emit("removetexture", key.key) } return this }, addBase64: function(key, data) { if (this.checkKey(key)) { var _this = this; var image = new Image; image.onerror = function() { _this.emit("onerror", key) }; image.onload = function() { var texture = _this.create(key, image); Parser.Image(texture, 0); _this.emit("addtexture", key, texture); _this.emit("onload", key, texture) }; image.src = data } return this }, getBase64: function(key, frame, type, encoderOptions) { if (type === undefined) { type = "image/png" } if (encoderOptions === undefined) { encoderOptions = .92 } var data = ""; var textureFrame = this.getFrame(key, frame); if (textureFrame) { var cd = textureFrame.canvasData; var canvas = CanvasPool.create2D(this, cd.width, cd.height); var ctx = canvas.getContext("2d"); ctx.drawImage(textureFrame.source.image, cd.x, cd.y, cd.width, cd.height, 0, 0, cd.width, cd.height); data = canvas.toDataURL(type, encoderOptions); CanvasPool.remove(canvas) } return data }, addImage: function(key, source, dataSource) { var texture = null; if (this.checkKey(key)) { texture = this.create(key, source); Parser.Image(texture, 0); if (dataSource) { texture.setDataSource(dataSource) } this.emit("addtexture", key, texture) } return texture }, addRenderTexture: function(key, renderTexture) { var texture = null; if (this.checkKey(key)) { texture = this.create(key, renderTexture); texture.add("__BASE", 0, 0, 0, renderTexture.width, renderTexture.height); this.emit("addtexture", key, texture) } return texture }, generate: function(key, config) { if (this.checkKey(key)) { var canvas = CanvasPool.create(this, 1, 1); config.canvas = canvas; GenerateTexture(config); return this.addCanvas(key, canvas) } else { return null } }, createCanvas: function(key, width, height) { if (width === undefined) { width = 256 } if (height === undefined) { height = 256 } if (this.checkKey(key)) { var canvas = CanvasPool.create(this, width, height, CONST.CANVAS, true); return this.addCanvas(key, canvas) } return null }, addCanvas: function(key, source, skipCache) { if (skipCache === undefined) { skipCache = false } var texture = null; if (skipCache) { texture = new CanvasTexture(this, key, source, source.width, source.height) } else if (this.checkKey(key)) { texture = new CanvasTexture(this, key, source, source.width, source.height); this.list[key] = texture; this.emit("addtexture", key, texture) } return texture }, addAtlas: function(key, source, data, dataSource) { if (Array.isArray(data.textures) || Array.isArray(data.frames)) { return this.addAtlasJSONArray(key, source, data, dataSource) } else { return this.addAtlasJSONHash(key, source, data, dataSource) } }, addAtlasJSONArray: function(key, source, data, dataSource) { var texture = null; if (this.checkKey(key)) { texture = this.create(key, source); if (Array.isArray(data)) { var singleAtlasFile = data.length === 1; for (var i = 0; i < texture.source.length; i++) { var atlasData = singleAtlasFile ? data[0] : data[i]; Parser.JSONArray(texture, i, atlasData) } } else { Parser.JSONArray(texture, 0, data) } if (dataSource) { texture.setDataSource(dataSource) } this.emit("addtexture", key, texture) } return texture }, addAtlasJSONHash: function(key, source, data, dataSource) { var texture = null; if (this.checkKey(key)) { texture = this.create(key, source); if (Array.isArray(data)) { for (var i = 0; i < data.length; i++) { Parser.JSONHash(texture, i, data[i]) } } else { Parser.JSONHash(texture, 0, data) } if (dataSource) { texture.setDataSource(dataSource) } this.emit("addtexture", key, texture) } return texture }, addAtlasXML: function(key, source, data, dataSource) { var texture = null; if (this.checkKey(key)) { texture = this.create(key, source); Parser.AtlasXML(texture, 0, data); if (dataSource) { texture.setDataSource(dataSource) } this.emit("addtexture", key, texture) } return texture }, addUnityAtlas: function(key, source, data, dataSource) { var texture = null; if (this.checkKey(key)) { texture = this.create(key, source); Parser.UnityYAML(texture, 0, data); if (dataSource) { texture.setDataSource(dataSource) } this.emit("addtexture", key, texture) } return texture }, addSpriteSheet: function(key, source, config) { var texture = null; if (this.checkKey(key)) { texture = this.create(key, source); var width = texture.source[0].width; var height = texture.source[0].height; Parser.SpriteSheet(texture, 0, 0, 0, width, height, config); this.emit("addtexture", key, texture) } return texture }, addSpriteSheetFromAtlas: function(key, config) { if (!this.checkKey(key)) { return null } var atlasKey = GetValue(config, "atlas", null); var atlasFrame = GetValue(config, "frame", null); if (!atlasKey || !atlasFrame) { return } var atlas = this.get(atlasKey); var sheet = atlas.get(atlasFrame); if (sheet) { var texture = this.create(key, sheet.source.image); if (sheet.trimmed) { Parser.SpriteSheetFromAtlas(texture, sheet, config) } else { Parser.SpriteSheet(texture, 0, sheet.cutX, sheet.cutY, sheet.cutWidth, sheet.cutHeight, config) } this.emit("addtexture", key, texture); return texture } }, create: function(key, source, width, height) { var texture = null; if (this.checkKey(key)) { texture = new Texture(this, key, source, width, height); this.list[key] = texture } return texture }, exists: function(key) { return this.list.hasOwnProperty(key) }, get: function(key) { if (key === undefined) { key = "__DEFAULT" } if (this.list[key]) { return this.list[key] } else { return this.list["__MISSING"] } }, cloneFrame: function(key, frame) { if (this.list[key]) { return this.list[key].get(frame).clone() } }, getFrame: function(key, frame) { if (this.list[key]) { return this.list[key].get(frame) } }, getTextureKeys: function() { var output = []; for (var key in this.list) { if (key !== "__DEFAULT" && key !== "__MISSING") { output.push(key) } } return output }, getPixel: function(x, y, key, frame) { var textureFrame = this.getFrame(key, frame); if (textureFrame) { x -= textureFrame.x; y -= textureFrame.y; var data = textureFrame.data.cut; x += data.x; y += data.y; if (x >= data.x && x < data.r && y >= data.y && y < data.b) { var ctx = this._tempContext; ctx.clearRect(0, 0, 1, 1); ctx.drawImage(textureFrame.source.image, x, y, 1, 1, 0, 0, 1, 1); var rgb = ctx.getImageData(0, 0, 1, 1); return new Color(rgb.data[0], rgb.data[1], rgb.data[2], rgb.data[3]) } } return null }, getPixelAlpha: function(x, y, key, frame) { var textureFrame = this.getFrame(key, frame); if (textureFrame) { x -= textureFrame.x; y -= textureFrame.y; var data = textureFrame.data.cut; x += data.x; y += data.y; if (x >= data.x && x < data.r && y >= data.y && y < data.b) { var ctx = this._tempContext; ctx.clearRect(0, 0, 1, 1); ctx.drawImage(textureFrame.source.image, x, y, 1, 1, 0, 0, 1, 1); var rgb = ctx.getImageData(0, 0, 1, 1); return rgb.data[3] } } return null }, setTexture: function(gameObject, key, frame) { if (this.list[key]) { gameObject.texture = this.list[key]; gameObject.frame = gameObject.texture.get(frame) } return gameObject }, renameTexture: function(currentKey, newKey) { var texture = this.get(currentKey); if (texture && currentKey !== newKey) { texture.key = newKey; this.list[newKey] = texture; delete this.list[currentKey]; return true } return false }, each: function(callback, scope) { var args = [null]; for (var i = 1; i < arguments.length; i++) { args.push(arguments[i]) } for (var texture in this.list) { args[0] = this.list[texture]; callback.apply(scope, args) } }, destroy: function() { for (var texture in this.list) { this.list[texture].destroy() } this.list = {}; this.game = null; CanvasPool.remove(this._tempCanvas) } }); module.exports = TextureManager }, function(module, exports, __webpack_require__) { var CanvasPool = __webpack_require__(28); var Class = __webpack_require__(0); var IsSizePowerOfTwo = __webpack_require__(116); var ScaleModes = __webpack_require__(89); var TextureSource = new Class({ initialize: function TextureSource(texture, source, width, height) { var game = texture.manager.game; this.renderer = game.renderer; this.texture = texture; this.source = source; this.image = source; this.compressionAlgorithm = null; this.resolution = 1; this.width = width || source.naturalWidth || source.width || 0; this.height = height || source.naturalHeight || source.height || 0; this.scaleMode = ScaleModes.DEFAULT; this.isCanvas = source instanceof HTMLCanvasElement; this.isRenderTexture = source.type === "RenderTexture"; this.isPowerOf2 = IsSizePowerOfTwo(this.width, this.height); this.glTexture = null; this.init(game) }, init: function(game) { if (this.renderer) { if (this.renderer.gl) { if (this.isCanvas) { this.glTexture = this.renderer.canvasToTexture(this.image) } else if (this.isRenderTexture) { this.image = this.source.canvas; this.glTexture = this.renderer.createTextureFromSource(null, this.width, this.height, this.scaleMode) } else { this.glTexture = this.renderer.createTextureFromSource(this.image, this.width, this.height, this.scaleMode) } } else if (this.isRenderTexture) { this.image = this.source.canvas } } if (!game.config.antialias) { this.setFilter(1) } }, setFilter: function(filterMode) { if (this.renderer.gl) { this.renderer.setTextureFilter(this.glTexture, filterMode) } }, update: function() { if (this.renderer.gl && this.isCanvas) { this.glTexture = this.renderer.canvasToTexture(this.image, this.glTexture) } }, destroy: function() { if (this.glTexture) { this.renderer.deleteTexture(this.glTexture) } if (this.isCanvas) { CanvasPool.remove(this.image) } this.renderer = null; this.texture = null; this.source = null; this.image = null; this.glTexture = null } }); module.exports = TextureSource }, function(module, exports, __webpack_require__) { module.exports = { AtlasXML: __webpack_require__(648), Canvas: __webpack_require__(649), Image: __webpack_require__(650), JSONArray: __webpack_require__(651), JSONHash: __webpack_require__(652), SpriteSheet: __webpack_require__(653), SpriteSheetFromAtlas: __webpack_require__(654), UnityYAML: __webpack_require__(655) } }, function(module, exports, __webpack_require__) { var AdInstance = __webpack_require__(659); var Class = __webpack_require__(0); var DataManager = __webpack_require__(91); var EventEmitter = __webpack_require__(11); var Leaderboard = __webpack_require__(660); var Product = __webpack_require__(662); var Purchase = __webpack_require__(663); var FacebookInstantGamesPlugin = new Class({ Extends: EventEmitter, initialize: function FacebookInstantGamesPlugin(game) { EventEmitter.call(this); this.game = game; this.data = new DataManager(this); this.on("setdata", this.setDataHandler, this); this.on("changedata", this.changeDataHandler, this); this.hasLoaded = false; this.dataLocked = false; this.supportedAPIs = []; this.entryPoint = ""; this.entryPointData = null; this.contextID = null; this.contextType = null; this.locale = null; this.platform = null; this.version = null; this.playerID = null; this.playerName = null; this.playerPhotoURL = null; this.playerCanSubscribeBot = false; this.paymentsReady = false; this.catalog = []; this.purchases = []; this.leaderboards = {}; this.ads = [] }, setDataHandler: function(parent, key, value) { if (this.dataLocked) { return } var data = {}; data[key] = value; var _this = this; FBInstant.player.setDataAsync(data).then(function() { _this.emit("savedata", data) }) }, changeDataHandler: function(parent, key, value) { if (this.dataLocked) { return } var data = {}; data[key] = value; var _this = this; FBInstant.player.setDataAsync(data).then(function() { _this.emit("savedata", data) }) }, showLoadProgress: function(scene) { scene.load.on("progress", function(value) { if (!this.hasLoaded) { FBInstant.setLoadingProgress(value * 100) } }, this); scene.load.on("complete", function() { if (!this.hasLoaded) { this.hasLoaded = true; FBInstant.startGameAsync().then(this.gameStarted.bind(this)) } }, this); return this }, gameStarted: function() { var APIs = FBInstant.getSupportedAPIs(); var supported = {}; var dotToUpper = function(match) { return match[1].toUpperCase() }; APIs.forEach(function(api) { api = api.replace(/\../g, dotToUpper); supported[api] = true }); this.supportedAPIs = supported; this.getID(); this.getType(); this.getLocale(); this.getPlatform(); this.getSDKVersion(); this.getPlayerID(); this.getPlayerName(); this.getPlayerPhotoURL(); var _this = this; FBInstant.onPause(function() { _this.emit("pause") }); FBInstant.getEntryPointAsync().then(function(entrypoint) { _this.entryPoint = entrypoint; _this.entryPointData = FBInstant.getEntryPointData(); _this.emit("startgame") }).catch(function(e) { console.warn(e) }); if (this.supportedAPIs.paymentsPurchaseAsync) { FBInstant.payments.onReady(function() { _this.paymentsReady = true }).catch(function(e) { console.warn(e) }) } }, checkAPI: function(api) { if (!this.supportedAPIs[api]) { return false } else { return true } }, getID: function() { if (!this.contextID && this.supportedAPIs.contextGetID) { this.contextID = FBInstant.context.getID() } return this.contextID }, getType: function() { if (!this.contextType && this.supportedAPIs.contextGetType) { this.contextType = FBInstant.context.getType() } return this.contextType }, getLocale: function() { if (!this.locale && this.supportedAPIs.getLocale) { this.locale = FBInstant.getLocale() } return this.locale }, getPlatform: function() { if (!this.platform && this.supportedAPIs.getPlatform) { this.platform = FBInstant.getPlatform() } return this.platform }, getSDKVersion: function() { if (!this.version && this.supportedAPIs.getSDKVersion) { this.version = FBInstant.getSDKVersion() } return this.version }, getPlayerID: function() { if (!this.playerID && this.supportedAPIs.playerGetID) { this.playerID = FBInstant.player.getID() } return this.playerID }, getPlayerName: function() { if (!this.playerName && this.supportedAPIs.playerGetName) { this.playerName = FBInstant.player.getName() } return this.playerName }, getPlayerPhotoURL: function() { if (!this.playerPhotoURL && this.supportedAPIs.playerGetPhoto) { this.playerPhotoURL = FBInstant.player.getPhoto() } return this.playerPhotoURL }, loadPlayerPhoto: function(scene, key) { if (this.playerPhotoURL) { scene.load.setCORS("anonymous"); scene.load.image(key, this.playerPhotoURL); scene.load.once("filecomplete_image_" + key, function() { this.emit("photocomplete", key) }, this); scene.load.start() } return this }, canSubscribeBot: function() { if (this.supportedAPIs.playerCanSubscribeBotAsync) { var _this = this; FBInstant.player.canSubscribeBotAsync().then(function() { _this.playerCanSubscribeBot = true; _this.emit("cansubscribebot") }).catch(function(e) { _this.emit("cansubscribebotfail", e) }) } else { this.emit("cansubscribebotfail") } return this }, subscribeBot: function() { if (this.playerCanSubscribeBot) { var _this = this; FBInstant.player.subscribeBotAsync().then(function() { _this.emit("subscribebot") }).catch(function(e) { _this.emit("subscribebotfail", e) }) } else { this.emit("subscribebotfail") } return this }, getData: function(keys) { if (!this.checkAPI("playerGetDataAsync")) { return this } if (!Array.isArray(keys)) { keys = [keys] } var _this = this; FBInstant.player.getDataAsync(keys).then(function(data) { _this.dataLocked = true; for (var key in data) { _this.data.set(key, data[key]) } _this.dataLocked = false; _this.emit("getdata", data) }); return this }, saveData: function(data) { if (!this.checkAPI("playerSetDataAsync")) { return this } var _this = this; FBInstant.player.setDataAsync(data).then(function() { _this.emit("savedata", data) }).catch(function(e) { _this.emit("savedatafail", e) }); return this }, flushData: function() { if (!this.checkAPI("playerFlushDataAsync")) { return this } var _this = this; FBInstant.player.flushDataAsync().then(function() { _this.emit("flushdata") }).catch(function(e) { _this.emit("flushdatafail", e) }); return this }, getStats: function(keys) { if (!this.checkAPI("playerGetStatsAsync")) { return this } var _this = this; FBInstant.player.getStatsAsync(keys).then(function(data) { _this.emit("getstats", data) }).catch(function(e) { _this.emit("getstatsfail", e) }); return this }, saveStats: function(data) { if (!this.checkAPI("playerSetStatsAsync")) { return this } var output = {}; for (var key in data) { if (typeof data[key] === "number") { output[key] = data[key] } } var _this = this; FBInstant.player.setStatsAsync(output).then(function() { _this.emit("savestats", output) }).catch(function(e) { _this.emit("savestatsfail", e) }); return this }, incStats: function(data) { if (!this.checkAPI("playerIncrementStatsAsync")) { return this } var output = {}; for (var key in data) { if (typeof data[key] === "number") { output[key] = data[key] } } var _this = this; FBInstant.player.incrementStatsAsync(output).then(function(stats) { _this.emit("incstats", stats) }).catch(function(e) { _this.emit("incstatsfail", e) }); return this }, saveSession: function(data) { if (!this.checkAPI("setSessionData")) { return this } var test = JSON.stringify(data); if (test.length <= 1e3) { FBInstant.setSessionData(data) } else { console.warn("Session data too long. Max 1000 chars.") } return this }, openShare: function(text, key, frame, sessionData) { return this._share("SHARE", text, key, frame, sessionData) }, openInvite: function(text, key, frame, sessionData) { return this._share("INVITE", text, key, frame, sessionData) }, openRequest: function(text, key, frame, sessionData) { return this._share("REQUEST", text, key, frame, sessionData) }, openChallenge: function(text, key, frame, sessionData) { return this._share("CHALLENGE", text, key, frame, sessionData) }, _share: function(intent, text, key, frame, sessionData) { if (!this.checkAPI("shareAsync")) { return this } if (sessionData === undefined) { sessionData = {} } if (key) { var imageData = this.game.textures.getBase64(key, frame) } var payload = { intent: intent, image: imageData, text: text, data: sessionData }; var _this = this; FBInstant.shareAsync(payload).then(function() { _this.emit("resume") }); return this }, isSizeBetween: function(min, max) { if (!this.checkAPI("contextIsSizeBetween")) { return this } return FBInstant.context.isSizeBetween(min, max) }, switchContext: function(contextID) { if (!this.checkAPI("contextSwitchAsync")) { return this } if (contextID !== this.contextID) { var _this = this; FBInstant.context.switchAsync(contextID).then(function() { _this.contextID = FBInstant.context.getID(); _this.emit("switch", _this.contextID) }).catch(function(e) { _this.emit("switchfail", e) }) } return this }, chooseContext: function(options) { if (!this.checkAPI("contextChoseAsync")) { return this } var _this = this; FBInstant.context.chooseAsync(options).then(function() { _this.contextID = FBInstant.context.getID(); _this.emit("choose", _this.contextID) }).catch(function(e) { _this.emit("choosefail", e) }); return this }, createContext: function(playerID) { if (!this.checkAPI("contextCreateAsync")) { return this } var _this = this; FBInstant.context.createAsync(playerID).then(function() { _this.contextID = FBInstant.context.getID(); _this.emit("create", _this.contextID) }).catch(function(e) { _this.emit("createfail", e) }); return this }, getPlayers: function() { if (!this.checkAPI("playerGetConnectedPlayersAsync")) { return this } var _this = this; FBInstant.player.getConnectedPlayersAsync().then(function(players) { _this.emit("players", players) }).catch(function(e) { _this.emit("playersfail", e) }); return this }, getCatalog: function() { if (!this.paymentsReady) { return this } var _this = this; var catalog = this.catalog; FBInstant.payments.getCatalogAsync().then(function(data) { catalog = []; data.forEach(function(item) { catalog.push(Product(item)) }); _this.emit("getcatalog", catalog) }).catch(function(e) { _this.emit("getcatalogfail", e) }); return this }, purchase: function(productID, developerPayload) { if (!this.paymentsReady) { return this } var config = { productID: productID }; if (developerPayload) { config.developerPayload = developerPayload } var _this = this; FBInstant.payments.purchaseAsync(config).then(function(data) { var purchase = Purchase(data); _this.emit("purchase", purchase) }).catch(function(e) { _this.emit("purchasefail", e) }); return this }, getPurchases: function() { if (!this.paymentsReady) { return this } var _this = this; var purchases = this.purchases; FBInstant.payments.getPurchasesAsync().then(function(data) { purchases = []; data.forEach(function(item) { purchases.push(Purchase(item)) }); _this.emit("getpurchases", purchases) }).catch(function(e) { _this.emit("getpurchasesfail", e) }); return this }, consumePurchases: function(purchaseToken) { if (!this.paymentsReady) { return this } var _this = this; FBInstant.payments.consumePurchaseAsync(purchaseToken).then(function() { _this.emit("consumepurchase", purchaseToken) }).catch(function(e) { _this.emit("consumepurchasefail", e) }); return this }, update: function(cta, text, key, frame, template, updateData) { return this._update("CUSTOM", cta, text, key, frame, template, updateData) }, updateLeaderboard: function(cta, text, key, frame, template, updateData) { return this._update("LEADERBOARD", cta, text, key, frame, template, updateData) }, _update: function(action, cta, text, key, frame, template, updateData) { if (!this.checkAPI("shareAsync")) { return this } if (cta === undefined) { cta = "" } if (typeof text === "string") { text = { default: text } } if (updateData === undefined) { updateData = {} } if (key) { var imageData = this.game.textures.getBase64(key, frame) } var payload = { action: action, cta: cta, image: imageData, text: text, template: template, data: updateData, strategy: "IMMEDIATE", notification: "NO_PUSH" }; var _this = this; FBInstant.updateAsync(payload).then(function() { _this.emit("update") }).catch(function(e) { _this.emit("updatefail", e) }); return this }, switchGame: function(appID, data) { if (!this.checkAPI("switchGameAsync")) { return this } if (data) { var test = JSON.stringify(data); if (test.length > 1e3) { console.warn("Switch Game data too long. Max 1000 chars."); return this } } var _this = this; FBInstant.switchGameAsync(appID, data).then(function() { _this.emit("switchgame", appID) }).catch(function(e) { _this.emit("switchgamefail", e) }); return this }, createShortcut: function() { var _this = this; FBInstant.canCreateShortcutAsync().then(function(canCreateShortcut) { if (canCreateShortcut) { FBInstant.createShortcutAsync().then(function() { _this.emit("shortcutcreated") }).catch(function(e) { _this.emit("shortcutfailed", e) }) } }); return this }, quit: function() { FBInstant.quit() }, log: function(name, value, params) { if (!this.checkAPI("logEvent")) { return this } if (params === undefined) { params = {} } if (name.length >= 2 && name.length <= 40) { FBInstant.logEvent(name, parseFloat(value), params) } return this }, preloadAds: function(placementID) { if (!this.checkAPI("getInterstitialAdAsync")) { return this } if (!Array.isArray(placementID)) { placementID = [placementID] } var i; var _this = this; var total = 0; for (i = 0; i < this.ads.length; i++) { if (!this.ads[i].shown) { total++ } } if (total + placementID.length >= 3) { console.warn("Too many AdInstances. Show an ad before loading more"); return this } for (i = 0; i < placementID.length; i++) { var id = placementID[i]; FBInstant.getInterstitialAdAsync(id).then(function(data) { var ad = AdInstance(data, true); _this.ads.push(ad); return ad.loadAsync() }).catch(function(e) { console.warn(e) }) } return this }, preloadVideoAds: function(placementID) { if (!this.checkAPI("getRewardedVideoAsync")) { return this } if (!Array.isArray(placementID)) { placementID = [placementID] } var i; var _this = this; var total = 0; for (i = 0; i < this.ads.length; i++) { if (!this.ads[i].shown) { total++ } } if (total + placementID.length >= 3) { console.warn("Too many AdInstances. Show an ad before loading more"); return this } for (i = 0; i < placementID.length; i++) { var id = placementID[i]; FBInstant.getRewardedVideoAsync(id).then(function(data) { var ad = AdInstance(data, true); _this.ads.push(ad); return ad.loadAsync() }).catch(function(e) { console.warn(e) }) } return this }, showAd: function(placementID) { var _this = this; for (var i = 0; i < this.ads.length; i++) { var ad = this.ads[i]; if (ad.placementID === placementID) { ad.instance.showAsync().then(function() { ad.shown = true; _this.emit("showad", ad) }).catch(function(e) { if (e.code === "ADS_NO_FILL") { _this.emit("adsnofill") } else { console.warn(e) } }) } } return this }, showVideo: function(placementID) { var _this = this; for (var i = 0; i < this.ads.length; i++) { var ad = this.ads[i]; if (ad.placementID === placementID && ad.video) { ad.instance.showAsync().then(function() { ad.shown = true; _this.emit("showad", ad) }).catch(function(e) { if (e.code === "ADS_NO_FILL") { _this.emit("adsnofill") } else { console.warn(e) } }) } } return this }, matchPlayer: function(matchTag, switchImmediately) { if (matchTag === undefined) { matchTag = null } if (switchImmediately === undefined) { switchImmediately = false } if (!this.checkAPI("matchPlayerAsync")) { return this } var _this = this; FBInstant.matchPlayerAsync(matchTag, switchImmediately).then(function() { _this.getID(); _this.getType(); _this.emit("matchplayer", _this.contextID, _this.contextType) }); return this }, getLeaderboard: function(name) { if (!this.checkAPI("getLeaderboardAsync")) { return this } var _this = this; FBInstant.getLeaderboardAsync(name).then(function(data) { var leaderboard = new Leaderboard(_this, data); _this.leaderboards[name] = leaderboard; _this.emit("getleaderboard", leaderboard) }).catch(function(e) { console.warn(e) }); return this }, destroy: function() { FBInstant.quit(); this.data.destroy(); this.removeAllListeners(); this.catalog = []; this.purchases = []; this.leaderboards = []; this.ads = []; this.game = null } }); module.exports = FacebookInstantGamesPlugin }, function(module, exports) { var TransposeMatrix = function(array) { var sourceRowCount = array.length; var sourceColCount = array[0].length; var result = new Array(sourceColCount); for (var i = 0; i < sourceColCount; i++) { result[i] = new Array(sourceRowCount); for (var j = sourceRowCount - 1; j > -1; j--) { result[i][j] = array[j][i] } } return result }; module.exports = TransposeMatrix }, function(module, exports) { var RoundAwayFromZero = function(value) { return value > 0 ? Math.ceil(value) : Math.floor(value) }; module.exports = RoundAwayFromZero }, function(module, exports) { var QuickSelect = function(arr, k, left, right, compare) { left = left || 0; right = right || arr.length - 1; compare = compare || defaultCompare; while (right > left) { if (right - left > 600) { var n = right - left + 1; var m = k - left + 1; var z = Math.log(n); var s = .5 * Math.exp(2 * z / 3); var sd = .5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1); var newLeft = Math.max(left, Math.floor(k - m * s / n + sd)); var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd)); QuickSelect(arr, k, newLeft, newRight, compare) } var t = arr[k]; var i = left; var j = right; swap(arr, left, k); if (compare(arr[right], t) > 0) { swap(arr, left, right) } while (i < j) { swap(arr, i, j); i++; j--; while (compare(arr[i], t) < 0) { i++ } while (compare(arr[j], t) > 0) { j-- } } if (compare(arr[left], t) === 0) { swap(arr, left, j) } else { j++; swap(arr, j, right) } if (j <= k) { left = j + 1 } if (k <= j) { right = j - 1 } } }; function swap(arr, i, j) { var tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp } function defaultCompare(a, b) { return a < b ? -1 : a > b ? 1 : 0 } module.exports = QuickSelect }, function(module, exports, __webpack_require__) { var GetValue = __webpack_require__(4); var Shuffle = __webpack_require__(110); var BuildChunk = function(a, b, qty) { var out = []; for (var aIndex = 0; aIndex < a.length; aIndex++) { for (var bIndex = 0; bIndex < b.length; bIndex++) { for (var i = 0; i < qty; i++) { out.push({ a: a[aIndex], b: b[bIndex] }) } } } return out }; var Range = function(a, b, options) { var max = GetValue(options, "max", 0); var qty = GetValue(options, "qty", 1); var random = GetValue(options, "random", false); var randomB = GetValue(options, "randomB", false); var repeat = GetValue(options, "repeat", 0); var yoyo = GetValue(options, "yoyo", false); var out = []; if (randomB) { Shuffle(b) } if (repeat === -1) { if (max === 0) { repeat = 0 } else { var total = a.length * b.length * qty; if (yoyo) { total *= 2 } repeat = Math.ceil(max / total) } } for (var i = 0; i <= repeat; i++) { var chunk = BuildChunk(a, b, qty); if (random) { Shuffle(chunk) } out = out.concat(chunk); if (yoyo) { chunk.reverse(); out = out.concat(chunk) } } if (max) { out.splice(max) } return out }; module.exports = Range }, function(module, exports) { function getValue(node, attribute) { return parseInt(node.getAttribute(attribute), 10) } var ParseXMLBitmapFont = function(xml, xSpacing, ySpacing, frame) { if (xSpacing === undefined) { xSpacing = 0 } if (ySpacing === undefined) { ySpacing = 0 } var data = {}; var info = xml.getElementsByTagName("info")[0]; var common = xml.getElementsByTagName("common")[0]; data.font = info.getAttribute("face"); data.size = getValue(info, "size"); data.lineHeight = getValue(common, "lineHeight") + ySpacing; data.chars = {}; var letters = xml.getElementsByTagName("char"); var adjustForTrim = frame !== undefined && frame.trimmed; if (adjustForTrim) { var top = frame.height; var left = frame.width } for (var i = 0; i < letters.length; i++) { var node = letters[i]; var charCode = getValue(node, "id"); var gx = getValue(node, "x"); var gy = getValue(node, "y"); var gw = getValue(node, "width"); var gh = getValue(node, "height"); if (adjustForTrim) { if (gx < left) { left = gx } if (gy < top) { top = gy } } data.chars[charCode] = { x: gx, y: gy, width: gw, height: gh, centerX: Math.floor(gw / 2), centerY: Math.floor(gh / 2), xOffset: getValue(node, "xoffset"), yOffset: getValue(node, "yoffset"), xAdvance: getValue(node, "xadvance") + xSpacing, data: {}, kerning: {} } } if (adjustForTrim && top !== 0 && left !== 0) { for (var code in data.chars) { var glyph = data.chars[code]; glyph.x -= frame.x; glyph.y -= frame.y } } var kernings = xml.getElementsByTagName("kerning"); for (i = 0; i < kernings.length; i++) { var kern = kernings[i]; var first = getValue(kern, "first"); var second = getValue(kern, "second"); var amount = getValue(kern, "amount"); data.chars[second].kerning[first] = amount } return data }; module.exports = ParseXMLBitmapFont }, function(module, exports, __webpack_require__) { var Rectangle = __webpack_require__(9); var Union = function(rectA, rectB, out) { if (out === undefined) { out = new Rectangle } var x = Math.min(rectA.x, rectB.x); var y = Math.min(rectA.y, rectB.y); var w = Math.max(rectA.right, rectB.right) - x; var h = Math.max(rectA.bottom, rectB.bottom) - y; return out.setTo(x, y, w, h) }; module.exports = Union }, function(module, exports, __webpack_require__) { var CircumferencePoint = __webpack_require__(184); var FromPercent = __webpack_require__(90); var MATH_CONST = __webpack_require__(18); var Point = __webpack_require__(6); var GetPoint = function(ellipse, position, out) { if (out === undefined) { out = new Point } var angle = FromPercent(position, 0, MATH_CONST.PI2); return CircumferencePoint(ellipse, angle, out) }; module.exports = GetPoint }, function(module, exports, __webpack_require__) { var Circumference = __webpack_require__(343); var CircumferencePoint = __webpack_require__(184); var FromPercent = __webpack_require__(90); var MATH_CONST = __webpack_require__(18); var GetPoints = function(ellipse, quantity, stepRate, out) { if (out === undefined) { out = [] } if (!quantity) { quantity = Circumference(ellipse) / stepRate } for (var i = 0; i < quantity; i++) { var angle = FromPercent(i / quantity, 0, MATH_CONST.PI2); out.push(CircumferencePoint(ellipse, angle)) } return out }; module.exports = GetPoints }, function(module, exports) { var Circumference = function(ellipse) { var rx = ellipse.width / 2; var ry = ellipse.height / 2; var h = Math.pow(rx - ry, 2) / Math.pow(rx + ry, 2); return Math.PI * (rx + ry) * (1 + 3 * h / (10 + Math.sqrt(4 - 3 * h))) }; module.exports = Circumference }, function(module, exports, __webpack_require__) { var Commands = __webpack_require__(183); var SetTransform = __webpack_require__(24); var GraphicsCanvasRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix, renderTargetCtx, allowClip) { var commandBuffer = src.commandBuffer; var commandBufferLength = commandBuffer.length; var ctx = renderTargetCtx || renderer.currentContext; if (commandBufferLength === 0 || !SetTransform(renderer, ctx, src, camera, parentMatrix)) { return } var lineAlpha = 1; var fillAlpha = 1; var lineColor = 0; var fillColor = 0; var lineWidth = 1; var red = 0; var green = 0; var blue = 0; ctx.save(); ctx.beginPath(); for (var index = 0; index < commandBufferLength; ++index) { var commandID = commandBuffer[index]; switch (commandID) { case Commands.ARC: ctx.arc(commandBuffer[index + 1], commandBuffer[index + 2], commandBuffer[index + 3], commandBuffer[index + 4], commandBuffer[index + 5], commandBuffer[index + 6]); index += 7; break; case Commands.LINE_STYLE: lineWidth = commandBuffer[index + 1]; lineColor = commandBuffer[index + 2]; lineAlpha = commandBuffer[index + 3]; red = (lineColor & 16711680) >>> 16; green = (lineColor & 65280) >>> 8; blue = lineColor & 255; ctx.strokeStyle = "rgba(" + red + "," + green + "," + blue + "," + lineAlpha + ")"; ctx.lineWidth = lineWidth; index += 3; break; case Commands.FILL_STYLE: fillColor = commandBuffer[index + 1]; fillAlpha = commandBuffer[index + 2]; red = (fillColor & 16711680) >>> 16; green = (fillColor & 65280) >>> 8; blue = fillColor & 255; ctx.fillStyle = "rgba(" + red + "," + green + "," + blue + "," + fillAlpha + ")"; index += 2; break; case Commands.BEGIN_PATH: ctx.beginPath(); break; case Commands.CLOSE_PATH: ctx.closePath(); break; case Commands.FILL_PATH: if (!allowClip) { ctx.fill() } break; case Commands.STROKE_PATH: if (!allowClip) { ctx.stroke() } break; case Commands.FILL_RECT: if (!allowClip) { ctx.fillRect(commandBuffer[index + 1], commandBuffer[index + 2], commandBuffer[index + 3], commandBuffer[index + 4]) } else { ctx.rect(commandBuffer[index + 1], commandBuffer[index + 2], commandBuffer[index + 3], commandBuffer[index + 4]) } index += 4; break; case Commands.FILL_TRIANGLE: ctx.beginPath(); ctx.moveTo(commandBuffer[index + 1], commandBuffer[index + 2]); ctx.lineTo(commandBuffer[index + 3], commandBuffer[index + 4]); ctx.lineTo(commandBuffer[index + 5], commandBuffer[index + 6]); ctx.closePath(); if (!allowClip) { ctx.fill() } index += 6; break; case Commands.STROKE_TRIANGLE: ctx.beginPath(); ctx.moveTo(commandBuffer[index + 1], commandBuffer[index + 2]); ctx.lineTo(commandBuffer[index + 3], commandBuffer[index + 4]); ctx.lineTo(commandBuffer[index + 5], commandBuffer[index + 6]); ctx.closePath(); if (!allowClip) { ctx.stroke() } index += 6; break; case Commands.LINE_TO: ctx.lineTo(commandBuffer[index + 1], commandBuffer[index + 2]); index += 2; break; case Commands.MOVE_TO: ctx.moveTo(commandBuffer[index + 1], commandBuffer[index + 2]); index += 2; break; case Commands.LINE_FX_TO: ctx.lineTo(commandBuffer[index + 1], commandBuffer[index + 2]); index += 5; break; case Commands.MOVE_FX_TO: ctx.moveTo(commandBuffer[index + 1], commandBuffer[index + 2]); index += 5; break; case Commands.SAVE: ctx.save(); break; case Commands.RESTORE: ctx.restore(); break; case Commands.TRANSLATE: ctx.translate(commandBuffer[index + 1], commandBuffer[index + 2]); index += 2; break; case Commands.SCALE: ctx.scale(commandBuffer[index + 1], commandBuffer[index + 2]); index += 2; break; case Commands.ROTATE: ctx.rotate(commandBuffer[index + 1]); index += 1; break; case Commands.GRADIENT_FILL_STYLE: index += 5; break; case Commands.GRADIENT_LINE_STYLE: index += 6; break; case Commands.SET_TEXTURE: index += 2; break } } ctx.restore() }; module.exports = GraphicsCanvasRenderer }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var GetFastValue = __webpack_require__(1); var GravityWell = new Class({ initialize: function GravityWell(x, y, power, epsilon, gravity) { if (typeof x === "object") { var config = x; x = GetFastValue(config, "x", 0); y = GetFastValue(config, "y", 0); power = GetFastValue(config, "power", 0); epsilon = GetFastValue(config, "epsilon", 100); gravity = GetFastValue(config, "gravity", 50) } else { if (x === undefined) { x = 0 } if (y === undefined) { y = 0 } if (power === undefined) { power = 0 } if (epsilon === undefined) { epsilon = 100 } if (gravity === undefined) { gravity = 50 } } this.x = x; this.y = y; this.active = true; this._gravity = gravity; this._power = 0; this._epsilon = 0; this.power = power; this.epsilon = epsilon }, update: function(particle, delta) { var x = this.x - particle.x; var y = this.y - particle.y; var dSq = x * x + y * y; if (dSq === 0) { return } var d = Math.sqrt(dSq); if (dSq < this._epsilon) { dSq = this._epsilon } var factor = this._power * delta / (dSq * d) * 100; particle.velocityX += x * factor; particle.velocityY += y * factor }, epsilon: { get: function() { return Math.sqrt(this._epsilon) }, set: function(value) { this._epsilon = value * value } }, power: { get: function() { return this._power / this._gravity }, set: function(value) { this._power = value * this._gravity } }, gravity: { get: function() { return this._gravity }, set: function(value) { var pwr = this.power; this._gravity = value; this.power = pwr } } }); module.exports = GravityWell }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var DegToRad = __webpack_require__(36); var DistanceBetween = __webpack_require__(56); var Particle = new Class({ initialize: function Particle(emitter) { this.emitter = emitter; this.frame = null; this.index = 0; this.x = 0; this.y = 0; this.velocityX = 0; this.velocityY = 0; this.accelerationX = 0; this.accelerationY = 0; this.maxVelocityX = 1e4; this.maxVelocityY = 1e4; this.bounce = 0; this.scaleX = 1; this.scaleY = 1; this.alpha = 1; this.angle = 0; this.rotation = 0; this.tint = 16777215; this.life = 1e3; this.lifeCurrent = 1e3; this.delayCurrent = 0; this.lifeT = 0; this.data = { tint: { min: 16777215, max: 16777215, current: 16777215 }, alpha: { min: 1, max: 1 }, rotate: { min: 0, max: 0 }, scaleX: { min: 1, max: 1 }, scaleY: { min: 1, max: 1 } } }, isAlive: function() { return this.lifeCurrent > 0 }, fire: function(x, y) { var emitter = this.emitter; this.frame = emitter.getFrame(); if (emitter.emitZone) { emitter.emitZone.getPoint(this) } if (x === undefined) { if (emitter.follow) { this.x += emitter.follow.x + emitter.followOffset.x } this.x += emitter.x.onEmit(this, "x") } else { this.x += x } if (y === undefined) { if (emitter.follow) { this.y += emitter.follow.y + emitter.followOffset.y } this.y += emitter.y.onEmit(this, "y") } else { this.y += y } this.life = emitter.lifespan.onEmit(this, "lifespan"); this.lifeCurrent = this.life; this.lifeT = 0; var sx = emitter.speedX.onEmit(this, "speedX"); var sy = emitter.speedY ? emitter.speedY.onEmit(this, "speedY") : sx; if (emitter.radial) { var rad = DegToRad(emitter.angle.onEmit(this, "angle")); this.velocityX = Math.cos(rad) * Math.abs(sx); this.velocityY = Math.sin(rad) * Math.abs(sy) } else if (emitter.moveTo) { var mx = emitter.moveToX.onEmit(this, "moveToX"); var my = emitter.moveToY ? emitter.moveToY.onEmit(this, "moveToY") : mx; var angle = Math.atan2(my - this.y, mx - this.x); var speed = DistanceBetween(this.x, this.y, mx, my) / (this.life / 1e3); this.velocityX = Math.cos(angle) * speed; this.velocityY = Math.sin(angle) * speed } else { this.velocityX = sx; this.velocityY = sy } if (emitter.acceleration) { this.accelerationX = emitter.accelerationX.onEmit(this, "accelerationX"); this.accelerationY = emitter.accelerationY.onEmit(this, "accelerationY") } this.maxVelocityX = emitter.maxVelocityX.onEmit(this, "maxVelocityX"); this.maxVelocityY = emitter.maxVelocityY.onEmit(this, "maxVelocityY"); this.delayCurrent = emitter.delay.onEmit(this, "delay"); this.scaleX = emitter.scaleX.onEmit(this, "scaleX"); this.scaleY = emitter.scaleY ? emitter.scaleY.onEmit(this, "scaleY") : this.scaleX; this.angle = emitter.rotate.onEmit(this, "rotate"); this.rotation = DegToRad(this.angle); this.bounce = emitter.bounce.onEmit(this, "bounce"); this.alpha = emitter.alpha.onEmit(this, "alpha"); this.tint = emitter.tint.onEmit(this, "tint"); this.index = emitter.alive.length }, computeVelocity: function(emitter, delta, step, processors) { var vx = this.velocityX; var vy = this.velocityY; var ax = this.accelerationX; var ay = this.accelerationY; var mx = this.maxVelocityX; var my = this.maxVelocityY; vx += emitter.gravityX * step; vy += emitter.gravityY * step; if (ax) { vx += ax * step } if (ay) { vy += ay * step } if (vx > mx) { vx = mx } else if (vx < -mx) { vx = -mx } if (vy > my) { vy = my } else if (vy < -my) { vy = -my } this.velocityX = vx; this.velocityY = vy; for (var i = 0; i < processors.length; i++) { processors[i].update(this, delta, step) } }, checkBounds: function(emitter) { var bounds = emitter.bounds; var bounce = -this.bounce; if (this.x < bounds.x && emitter.collideLeft) { this.x = bounds.x; this.velocityX *= bounce } else if (this.x > bounds.right && emitter.collideRight) { this.x = bounds.right; this.velocityX *= bounce } if (this.y < bounds.y && emitter.collideTop) { this.y = bounds.y; this.velocityY *= bounce } else if (this.y > bounds.bottom && emitter.collideBottom) { this.y = bounds.bottom; this.velocityY *= bounce } }, update: function(delta, step, processors) { if (this.delayCurrent > 0) { this.delayCurrent -= delta; return false } var emitter = this.emitter; var t = 1 - this.lifeCurrent / this.life; this.lifeT = t; this.computeVelocity(emitter, delta, step, processors); this.x += this.velocityX * step; this.y += this.velocityY * step; if (emitter.bounds) { this.checkBounds(emitter) } if (emitter.deathZone && emitter.deathZone.willKill(this)) { this.lifeCurrent = 0; return true } this.scaleX = emitter.scaleX.onUpdate(this, "scaleX", t, this.scaleX); if (emitter.scaleY) { this.scaleY = emitter.scaleY.onUpdate(this, "scaleY", t, this.scaleY) } else { this.scaleY = this.scaleX } this.angle = emitter.rotate.onUpdate(this, "rotate", t, this.angle); this.rotation = DegToRad(this.angle); this.alpha = emitter.alpha.onUpdate(this, "alpha", t, this.alpha); this.tint = emitter.tint.onUpdate(this, "tint", t, this.tint); this.lifeCurrent -= delta; return this.lifeCurrent <= 0 } }); module.exports = Particle }, function(module, exports, __webpack_require__) { var BlendModes = __webpack_require__(61); var Class = __webpack_require__(0); var Components = __webpack_require__(14); var DeathZone = __webpack_require__(348); var EdgeZone = __webpack_require__(349); var EmitterOp = __webpack_require__(718); var GetFastValue = __webpack_require__(1); var GetRandom = __webpack_require__(177); var HasAny = __webpack_require__(351); var HasValue = __webpack_require__(83); var Particle = __webpack_require__(346); var RandomZone = __webpack_require__(352); var Rectangle = __webpack_require__(9); var StableSort = __webpack_require__(123); var Vector2 = __webpack_require__(3); var Wrap = __webpack_require__(55); var ParticleEmitter = new Class({ Mixins: [Components.BlendMode, Components.Mask, Components.ScrollFactor, Components.Visible], initialize: function ParticleEmitter(manager, config) { this.manager = manager; this.texture = manager.texture; this.frames = [manager.defaultFrame]; this.defaultFrame = manager.defaultFrame; this.configFastMap = ["active", "blendMode", "collideBottom", "collideLeft", "collideRight", "collideTop", "deathCallback", "deathCallbackScope", "emitCallback", "emitCallbackScope", "follow", "frequency", "gravityX", "gravityY", "maxParticles", "name", "on", "particleBringToTop", "particleClass", "radial", "timeScale", "trackVisible", "visible"]; this.configOpMap = ["accelerationX", "accelerationY", "angle", "alpha", "bounce", "delay", "lifespan", "maxVelocityX", "maxVelocityY", "moveToX", "moveToY", "quantity", "rotate", "scaleX", "scaleY", "speedX", "speedY", "tint", "x", "y"]; this.name = ""; this.particleClass = Particle; this.x = new EmitterOp(config, "x", 0); this.y = new EmitterOp(config, "y", 0); this.radial = true; this.gravityX = 0; this.gravityY = 0; this.acceleration = false; this.accelerationX = new EmitterOp(config, "accelerationX", 0, true); this.accelerationY = new EmitterOp(config, "accelerationY", 0, true); this.maxVelocityX = new EmitterOp(config, "maxVelocityX", 1e4, true); this.maxVelocityY = new EmitterOp(config, "maxVelocityY", 1e4, true); this.speedX = new EmitterOp(config, "speedX", 0, true); this.speedY = new EmitterOp(config, "speedY", 0, true); this.moveTo = false; this.moveToX = new EmitterOp(config, "moveToX", 0, true); this.moveToY = new EmitterOp(config, "moveToY", 0, true); this.bounce = new EmitterOp(config, "bounce", 0, true); this.scaleX = new EmitterOp(config, "scaleX", 1); this.scaleY = new EmitterOp(config, "scaleY", 1); this.tint = new EmitterOp(config, "tint", 4294967295); this.alpha = new EmitterOp(config, "alpha", 1); this.lifespan = new EmitterOp(config, "lifespan", 1e3); this.angle = new EmitterOp(config, "angle", { min: 0, max: 360 }); this.rotate = new EmitterOp(config, "rotate", 0); this.emitCallback = null; this.emitCallbackScope = null; this.deathCallback = null; this.deathCallbackScope = null; this.maxParticles = 0; this.quantity = new EmitterOp(config, "quantity", 1, true); this.delay = new EmitterOp(config, "delay", 0, true); this.frequency = 0; this.on = true; this.particleBringToTop = true; this.timeScale = 1; this.emitZone = null; this.deathZone = null; this.bounds = null; this.collideLeft = true; this.collideRight = true; this.collideTop = true; this.collideBottom = true; this.active = true; this.visible = true; this.blendMode = BlendModes.NORMAL; this.follow = null; this.followOffset = new Vector2; this.trackVisible = false; this.currentFrame = 0; this.randomFrame = true; this.frameQuantity = 1; this.dead = []; this.alive = []; this._counter = 0; this._frameCounter = 0; if (config) { this.fromJSON(config) } }, fromJSON: function(config) { if (!config) { return this } var i = 0; var key = ""; for (i = 0; i < this.configFastMap.length; i++) { key = this.configFastMap[i]; if (HasValue(config, key)) { this[key] = GetFastValue(config, key) } } for (i = 0; i < this.configOpMap.length; i++) { key = this.configOpMap[i]; if (HasValue(config, key)) { this[key].loadConfig(config) } } this.acceleration = this.accelerationX.propertyValue !== 0 || this.accelerationY.propertyValue !== 0; this.moveTo = this.moveToX.propertyValue !== 0 || this.moveToY.propertyValue !== 0; if (HasValue(config, "speed")) { this.speedX.loadConfig(config, "speed"); this.speedY = null } if (HasAny(config, ["speedX", "speedY"]) || this.moveTo) { this.radial = false } if (HasValue(config, "scale")) { this.scaleX.loadConfig(config, "scale"); this.scaleY = null } if (HasValue(config, "callbackScope")) { var callbackScope = GetFastValue(config, "callbackScope", null); this.emitCallbackScope = callbackScope; this.deathCallbackScope = callbackScope } if (HasValue(config, "emitZone")) { this.setEmitZone(config.emitZone) } if (HasValue(config, "deathZone")) { this.setDeathZone(config.deathZone) } if (HasValue(config, "bounds")) { this.setBounds(config.bounds) } if (HasValue(config, "followOffset")) { this.followOffset.setFromObject(GetFastValue(config, "followOffset", 0)) } if (HasValue(config, "frame")) { this.setFrame(config.frame) } return this }, toJSON: function(output) { if (output === undefined) { output = {} } var i = 0; var key = ""; for (i = 0; i < this.configFastMap.length; i++) { key = this.configFastMap[i]; output[key] = this[key] } for (i = 0; i < this.configOpMap.length; i++) { key = this.configOpMap[i]; if (this[key]) { output[key] = this[key].toJSON() } } if (!this.speedY) { delete output.speedX; output.speed = this.speedX.toJSON() } if (!this.scaleY) { delete output.scaleX; output.scale = this.scaleX.toJSON() } return output }, startFollow: function(target, offsetX, offsetY, trackVisible) { if (offsetX === undefined) { offsetX = 0 } if (offsetY === undefined) { offsetY = 0 } if (trackVisible === undefined) { trackVisible = false } this.follow = target; this.followOffset.set(offsetX, offsetY); this.trackVisible = trackVisible; return this }, stopFollow: function() { this.follow = null; this.followOffset.set(0, 0); this.trackVisible = false; return this }, getFrame: function() { if (this.frames.length === 1) { return this.defaultFrame } else if (this.randomFrame) { return GetRandom(this.frames) } else { var frame = this.frames[this.currentFrame]; this._frameCounter++; if (this._frameCounter === this.frameQuantity) { this._frameCounter = 0; this.currentFrame = Wrap(this.currentFrame + 1, 0, this._frameLength) } return frame } }, setFrame: function(frames, pickRandom, quantity) { if (pickRandom === undefined) { pickRandom = true } if (quantity === undefined) { quantity = 1 } this.randomFrame = pickRandom; this.frameQuantity = quantity; this.currentFrame = 0; this._frameCounter = 0; var t = typeof frames; if (Array.isArray(frames) || t === "string" || t === "number") { this.manager.setEmitterFrames(frames, this) } else if (t === "object") { var frameConfig = frames; frames = GetFastValue(frameConfig, "frames", null); if (frames) { this.manager.setEmitterFrames(frames, this) } var isCycle = GetFastValue(frameConfig, "cycle", false); this.randomFrame = isCycle ? false : true; this.frameQuantity = GetFastValue(frameConfig, "quantity", quantity) } this._frameLength = this.frames.length; if (this._frameLength === 1) { this.frameQuantity = 1; this.randomFrame = false } return this }, setRadial: function(value) { if (value === undefined) { value = true } this.radial = value; return this }, setPosition: function(x, y) { this.x.onChange(x); this.y.onChange(y); return this }, setBounds: function(x, y, width, height) { if (typeof x === "object") { var obj = x; x = obj.x; y = obj.y; width = HasValue(obj, "w") ? obj.w : obj.width; height = HasValue(obj, "h") ? obj.h : obj.height } if (this.bounds) { this.bounds.setTo(x, y, width, height) } else { this.bounds = new Rectangle(x, y, width, height) } return this }, setSpeedX: function(value) { this.speedX.onChange(value); this.radial = false; return this }, setSpeedY: function(value) { if (this.speedY) { this.speedY.onChange(value); this.radial = false } return this }, setSpeed: function(value) { this.speedX.onChange(value); this.speedY = null; this.radial = true; return this }, setScaleX: function(value) { this.scaleX.onChange(value); return this }, setScaleY: function(value) { this.scaleY.onChange(value); return this }, setScale: function(value) { this.scaleX.onChange(value); this.scaleY = null; return this }, setGravityX: function(value) { this.gravityX = value; return this }, setGravityY: function(value) { this.gravityY = value; return this }, setGravity: function(x, y) { this.gravityX = x; this.gravityY = y; return this }, setAlpha: function(value) { this.alpha.onChange(value); return this }, setEmitterAngle: function(value) { this.angle.onChange(value); return this }, setAngle: function(value) { this.angle.onChange(value); return this }, setLifespan: function(value) { this.lifespan.onChange(value); return this }, setQuantity: function(quantity) { this.quantity.onChange(quantity); return this }, setFrequency: function(frequency, quantity) { this.frequency = frequency; this._counter = 0; if (quantity) { this.quantity.onChange(quantity) } return this }, setEmitZone: function(zoneConfig) { if (zoneConfig === undefined) { this.emitZone = null } else { var type = GetFastValue(zoneConfig, "type", "random"); var source = GetFastValue(zoneConfig, "source", null); switch (type) { case "random": this.emitZone = new RandomZone(source); break; case "edge": var quantity = GetFastValue(zoneConfig, "quantity", 1); var stepRate = GetFastValue(zoneConfig, "stepRate", 0); var yoyo = GetFastValue(zoneConfig, "yoyo", false); var seamless = GetFastValue(zoneConfig, "seamless", true); this.emitZone = new EdgeZone(source, quantity, stepRate, yoyo, seamless); break } } return this }, setDeathZone: function(zoneConfig) { if (zoneConfig === undefined) { this.deathZone = null } else { var type = GetFastValue(zoneConfig, "type", "onEnter"); var source = GetFastValue(zoneConfig, "source", null); if (source && typeof source.contains === "function") { var killOnEnter = type === "onEnter" ? true : false; this.deathZone = new DeathZone(source, killOnEnter) } } return this }, reserve: function(particleCount) { var dead = this.dead; for (var i = 0; i < particleCount; i++) { dead.push(new this.particleClass(this)) } return this }, getAliveParticleCount: function() { return this.alive.length }, getDeadParticleCount: function() { return this.dead.length }, getParticleCount: function() { return this.getAliveParticleCount() + this.getDeadParticleCount() }, atLimit: function() { return this.maxParticles > 0 && this.getParticleCount() === this.maxParticles }, onParticleEmit: function(callback, context) { if (callback === undefined) { this.emitCallback = null; this.emitCallbackScope = null } else if (typeof callback === "function") { this.emitCallback = callback; if (context) { this.emitCallbackScope = context } } return this }, onParticleDeath: function(callback, context) { if (callback === undefined) { this.deathCallback = null; this.deathCallbackScope = null } else if (typeof callback === "function") { this.deathCallback = callback; if (context) { this.deathCallbackScope = context } } return this }, killAll: function() { var dead = this.dead; var alive = this.alive; while (alive.length > 0) { dead.push(alive.pop()) } return this }, forEachAlive: function(callback, context) { var alive = this.alive; var length = alive.length; for (var index = 0; index < length; ++index) { callback.call(context, alive[index], this) } return this }, forEachDead: function(callback, context) { var dead = this.dead; var length = dead.length; for (var index = 0; index < length; ++index) { callback.call(context, dead[index], this) } return this }, start: function() { this.on = true; this._counter = 0; return this }, stop: function() { this.on = false; return this }, pause: function() { this.active = false; return this }, resume: function() { this.active = true; return this }, depthSort: function() { StableSort.inplace(this.alive, this.depthSortCallback); return this }, flow: function(frequency, count) { if (count === undefined) { count = 1 } this.frequency = frequency; this.quantity.onChange(count); return this.start() }, explode: function(count, x, y) { this.frequency = -1; return this.emitParticle(count, x, y) }, emitParticleAt: function(x, y, count) { return this.emitParticle(count, x, y) }, emitParticle: function(count, x, y) { if (this.atLimit()) { return } if (count === undefined) { count = this.quantity.onEmit() } var dead = this.dead; for (var i = 0; i < count; i++) { var particle; if (dead.length > 0) { particle = dead.pop() } else { particle = new this.particleClass(this) } particle.fire(x, y); if (this.particleBringToTop) { this.alive.push(particle) } else { this.alive.unshift(particle) } if (this.emitCallback) { this.emitCallback.call(this.emitCallbackScope, particle, this) } if (this.atLimit()) { break } } return particle }, preUpdate: function(time, delta) { delta *= this.timeScale; var step = delta / 1e3; if (this.trackVisible) { this.visible = this.follow.visible } var processors = this.manager.getProcessors(); var particles = this.alive; var length = particles.length; for (var index = 0; index < length; index++) { var particle = particles[index]; if (particle.update(delta, step, processors)) { var last = particles[length - 1]; particles[length - 1] = particle; particles[index] = last; index -= 1; length -= 1 } } var deadLength = particles.length - length; if (deadLength > 0) { var rip = particles.splice(particles.length - deadLength, deadLength); var deathCallback = this.deathCallback; var deathCallbackScope = this.deathCallbackScope; if (deathCallback) { for (var i = 0; i < rip.length; i++) { deathCallback.call(deathCallbackScope, rip[i]) } } this.dead.concat(rip); StableSort.inplace(particles, this.indexSortCallback) } if (!this.on) { return } if (this.frequency === 0) { this.emitParticle() } else if (this.frequency > 0) { this._counter -= delta; if (this._counter <= 0) { this.emitParticle(); this._counter = this.frequency - Math.abs(this._counter) } } }, depthSortCallback: function(a, b) { return a.y - b.y }, indexSortCallback: function(a, b) { return a.index - b.index } }); module.exports = ParticleEmitter }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var DeathZone = new Class({ initialize: function DeathZone(source, killOnEnter) { this.source = source; this.killOnEnter = killOnEnter }, willKill: function(particle) { var withinZone = this.source.contains(particle.x, particle.y); return withinZone && this.killOnEnter || !withinZone && !this.killOnEnter } }); module.exports = DeathZone }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var EdgeZone = new Class({ initialize: function EdgeZone(source, quantity, stepRate, yoyo, seamless) { if (yoyo === undefined) { yoyo = false } if (seamless === undefined) { seamless = true } this.source = source; this.points = []; this.quantity = quantity; this.stepRate = stepRate; this.yoyo = yoyo; this.counter = -1; this.seamless = seamless; this._length = 0; this._direction = 0; this.updateSource() }, updateSource: function() { this.points = this.source.getPoints(this.quantity, this.stepRate); if (this.seamless) { var a = this.points[0]; var b = this.points[this.points.length - 1]; if (a.x === b.x && a.y === b.y) { this.points.pop() } } var oldLength = this._length; this._length = this.points.length; if (this._length < oldLength && this.counter > this._length) { this.counter = this._length - 1 } return this }, changeSource: function(source) { this.source = source; return this.updateSource() }, getPoint: function(particle) { if (this._direction === 0) { this.counter++; if (this.counter >= this._length) { if (this.yoyo) { this._direction = 1; this.counter = this._length - 1 } else { this.counter = 0 } } } else { this.counter--; if (this.counter === -1) { if (this.yoyo) { this._direction = 0; this.counter = 0 } else { this.counter = this._length - 1 } } } var point = this.points[this.counter]; if (point) { particle.x = point.x; particle.y = point.y } } }); module.exports = EdgeZone }, function(module, exports) { var FloatBetween = function(min, max) { return Math.random() * (max - min) + min }; module.exports = FloatBetween }, function(module, exports) { var HasAny = function(source, keys) { for (var i = 0; i < keys.length; i++) { if (source.hasOwnProperty(keys[i])) { return true } } return false }; module.exports = HasAny }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Vector2 = __webpack_require__(3); var RandomZone = new Class({ initialize: function RandomZone(source) { this.source = source; this._tempVec = new Vector2 }, getPoint: function(particle) { var vec = this._tempVec; this.source.getRandomPoint(vec); particle.x = vec.x; particle.y = vec.y } }); module.exports = RandomZone }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var DegToRad = __webpack_require__(36); var GetBoolean = __webpack_require__(98); var GetValue = __webpack_require__(4); var Sprite = __webpack_require__(50); var TWEEN_CONST = __webpack_require__(99); var Vector2 = __webpack_require__(3); var PathFollower = new Class({ Extends: Sprite, initialize: function PathFollower(scene, path, x, y, texture, frame) { Sprite.call(this, scene, x, y, texture, frame); this.path = path; this.rotateToPath = false; this.pathRotationVerticalAdjust = false; this.pathRotationOffset = 0; this.pathOffset = new Vector2(x, y); this.pathVector = new Vector2; this.pathTween; this.pathConfig = null; this._prevDirection = TWEEN_CONST.PLAYING_FORWARD }, setPath: function(path, config) { if (config === undefined) { config = this.pathConfig } var tween = this.pathTween; if (tween && tween.isPlaying()) { tween.stop() } this.path = path; if (config) { this.startFollow(config) } return this }, setRotateToPath: function(value, offset, verticalAdjust) { if (offset === undefined) { offset = 0 } if (verticalAdjust === undefined) { verticalAdjust = false } this.rotateToPath = value; this.pathRotationOffset = offset; this.pathRotationVerticalAdjust = verticalAdjust; return this }, isFollowing: function() { var tween = this.pathTween; return tween && tween.isPlaying() }, startFollow: function(config, startAt) { if (config === undefined) { config = {} } if (startAt === undefined) { startAt = 0 } var tween = this.pathTween; if (tween && tween.isPlaying()) { tween.stop() } if (typeof config === "number") { config = { duration: config } } config.from = 0; config.to = 1; var positionOnPath = GetBoolean(config, "positionOnPath", false); this.rotateToPath = GetBoolean(config, "rotateToPath", false); this.pathRotationOffset = GetValue(config, "rotationOffset", 0); this.pathRotationVerticalAdjust = GetBoolean(config, "verticalAdjust", false); this.pathTween = this.scene.sys.tweens.addCounter(config); this.path.getStartPoint(this.pathOffset); if (positionOnPath) { this.x = this.pathOffset.x; this.y = this.pathOffset.y } this.pathOffset.x = this.x - this.pathOffset.x; this.pathOffset.y = this.y - this.pathOffset.y; this._prevDirection = TWEEN_CONST.PLAYING_FORWARD; if (this.rotateToPath) { var nextPoint = this.path.getPoint(.1); this.rotation = Math.atan2(nextPoint.y - this.y, nextPoint.x - this.x) + DegToRad(this.pathRotationOffset) } this.pathConfig = config; return this }, pauseFollow: function() { var tween = this.pathTween; if (tween && tween.isPlaying()) { tween.pause() } return this }, resumeFollow: function() { var tween = this.pathTween; if (tween && tween.isPaused()) { tween.resume() } return this }, stopFollow: function() { var tween = this.pathTween; if (tween && tween.isPlaying()) { tween.stop() } return this }, preUpdate: function(time, delta) { this.anims.update(time, delta); var tween = this.pathTween; if (tween) { var tweenData = tween.data[0]; if (tweenData.state !== TWEEN_CONST.PLAYING_FORWARD && tweenData.state !== TWEEN_CONST.PLAYING_BACKWARD) { return } var pathVector = this.pathVector; this.path.getPoint(tween.getValue(), pathVector); pathVector.add(this.pathOffset); var oldX = this.x; var oldY = this.y; this.setPosition(pathVector.x, pathVector.y); var speedX = this.x - oldX; var speedY = this.y - oldY; if (speedX === 0 && speedY === 0) { return } if (tweenData.state !== this._prevDirection) { this._prevDirection = tweenData.state; return } if (this.rotateToPath) { this.rotation = Math.atan2(speedY, speedX) + DegToRad(this.pathRotationOffset); if (this.pathRotationVerticalAdjust) { this.flipY = this.rotation !== 0 && tweenData.state === TWEEN_CONST.PLAYING_BACKWARD } } } } }); module.exports = PathFollower }, function(module, exports) { var UUID = function() { return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) { var r = Math.random() * 16 | 0; var v = c === "x" ? r : r & 3 | 8; return v.toString(16) }) }; module.exports = UUID }, function(module, exports) { var GetPowerOfTwo = function(value) { var index = Math.log(value) / .6931471805599453; return 1 << Math.ceil(index) }; module.exports = GetPowerOfTwo }, function(module, exports, __webpack_require__) { var ArcRender = __webpack_require__(738); var Class = __webpack_require__(0); var DegToRad = __webpack_require__(36); var Earcut = __webpack_require__(63); var GeomCircle = __webpack_require__(78); var MATH_CONST = __webpack_require__(18); var Shape = __webpack_require__(30); var Arc = new Class({ Extends: Shape, Mixins: [ArcRender], initialize: function Arc(scene, x, y, radius, startAngle, endAngle, anticlockwise, fillColor, fillAlpha) { if (x === undefined) { x = 0 } if (y === undefined) { y = 0 } if (radius === undefined) { radius = 128 } if (startAngle === undefined) { startAngle = 0 } if (endAngle === undefined) { endAngle = 360 } if (anticlockwise === undefined) { anticlockwise = false } Shape.call(this, scene, "Arc", new GeomCircle(0, 0, radius)); this._startAngle = startAngle; this._endAngle = endAngle; this._anticlockwise = anticlockwise; this._iterations = .01; this.setPosition(x, y); this.setSize(this.geom.radius, this.geom.radius); if (fillColor !== undefined) { this.setFillStyle(fillColor, fillAlpha) } this.updateDisplayOrigin(); this.updateData() }, iterations: { get: function() { return this._iterations }, set: function(value) { this._iterations = value; this.updateData() } }, radius: { get: function() { return this.geom.radius }, set: function(value) { this.geom.radius = value; this.updateData() } }, startAngle: { get: function() { return this._startAngle }, set: function(value) { this._startAngle = value; this.updateData() } }, endAngle: { get: function() { return this._endAngle }, set: function(value) { this._endAngle = value; this.updateData() } }, anticlockwise: { get: function() { return this._anticlockwise }, set: function(value) { this._anticlockwise = value; this.updateData() } }, setRadius: function(value) { this.radius = value; return this }, setIterations: function(value) { if (value === undefined) { value = .01 } this.iterations = value; return this }, setStartAngle: function(angle, anticlockwise) { this._startAngle = angle; if (anticlockwise !== undefined) { this._anticlockwise = anticlockwise } return this.updateData() }, setEndAngle: function(angle, anticlockwise) { this._endAngle = angle; if (anticlockwise !== undefined) { this._anticlockwise = anticlockwise } return this.updateData() }, updateData: function() { var step = this._iterations; var iteration = step; var radius = this.geom.radius; var startAngle = DegToRad(this._startAngle); var endAngle = DegToRad(this._endAngle); var anticlockwise = this._anticlockwise; var x = radius / 2; var y = radius / 2; endAngle -= startAngle; if (anticlockwise) { if (endAngle < -MATH_CONST.PI2) { endAngle = -MATH_CONST.PI2 } else if (endAngle > 0) { endAngle = -MATH_CONST.PI2 + endAngle % MATH_CONST.PI2 } } else if (endAngle > MATH_CONST.PI2) { endAngle = MATH_CONST.PI2 } else if (endAngle < 0) { endAngle = MATH_CONST.PI2 + endAngle % MATH_CONST.PI2 } var path = [x + Math.cos(startAngle) * radius, y + Math.sin(startAngle) * radius]; var ta; while (iteration < 1) { ta = endAngle * iteration + startAngle; path.push(x + Math.cos(ta) * radius, y + Math.sin(ta) * radius); iteration += step } ta = endAngle + startAngle; path.push(x + Math.cos(ta) * radius, y + Math.sin(ta) * radius); path.push(x + Math.cos(startAngle) * radius, y + Math.sin(startAngle) * radius); this.pathIndexes = Earcut(path); this.pathData = path; return this } }); module.exports = Arc }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var CurveRender = __webpack_require__(741); var Earcut = __webpack_require__(63); var Rectangle = __webpack_require__(9); var Shape = __webpack_require__(30); var Curve = new Class({ Extends: Shape, Mixins: [CurveRender], initialize: function Curve(scene, x, y, curve, fillColor, fillAlpha) { if (x === undefined) { x = 0 } if (y === undefined) { y = 0 } Shape.call(this, scene, "Curve", curve); this._smoothness = 32; this._curveBounds = new Rectangle; this.closePath = false; this.setPosition(x, y); if (fillColor !== undefined) { this.setFillStyle(fillColor, fillAlpha) } this.updateData() }, smoothness: { get: function() { return this._smoothness }, set: function(value) { this._smoothness = value; this.updateData() } }, setSmoothness: function(value) { this._smoothness = value; return this.updateData() }, updateData: function() { var bounds = this._curveBounds; var smoothness = this._smoothness; this.geom.getBounds(bounds, smoothness); this.setSize(bounds.width, bounds.height); this.updateDisplayOrigin(); var path = []; var points = this.geom.getPoints(smoothness); for (var i = 0; i < points.length; i++) { path.push(points[i].x, points[i].y) } path.push(points[0].x, points[0].y); this.pathIndexes = Earcut(path); this.pathData = path; return this } }); module.exports = Curve }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Earcut = __webpack_require__(63); var EllipseRender = __webpack_require__(744); var GeomEllipse = __webpack_require__(94); var Shape = __webpack_require__(30); var Ellipse = new Class({ Extends: Shape, Mixins: [EllipseRender], initialize: function Ellipse(scene, x, y, width, height, fillColor, fillAlpha) { if (x === undefined) { x = 0 } if (y === undefined) { y = 0 } if (width === undefined) { width = 128 } if (height === undefined) { height = 128 } Shape.call(this, scene, "Ellipse", new GeomEllipse(width / 2, height / 2, width, height)); this._smoothness = 64; this.setPosition(x, y); this.width = width; this.height = height; if (fillColor !== undefined) { this.setFillStyle(fillColor, fillAlpha) } this.updateDisplayOrigin(); this.updateData() }, smoothness: { get: function() { return this._smoothness }, set: function(value) { this._smoothness = value; this.updateData() } }, setSize: function(width, height) { this.geom.setSize(width, height); return this.updateData() }, setSmoothness: function(value) { this._smoothness = value; return this.updateData() }, updateData: function() { var path = []; var points = this.geom.getPoints(this._smoothness); for (var i = 0; i < points.length; i++) { path.push(points[i].x, points[i].y) } path.push(points[0].x, points[0].y); this.pathIndexes = Earcut(path); this.pathData = path; return this } }); module.exports = Ellipse }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Shape = __webpack_require__(30); var GridRender = __webpack_require__(747); var Grid = new Class({ Extends: Shape, Mixins: [GridRender], initialize: function Grid(scene, x, y, width, height, cellWidth, cellHeight, fillColor, fillAlpha, outlineFillColor, outlineFillAlpha) { if (x === undefined) { x = 0 } if (y === undefined) { y = 0 } if (width === undefined) { width = 128 } if (height === undefined) { height = 128 } if (cellWidth === undefined) { cellWidth = 32 } if (cellHeight === undefined) { cellHeight = 32 } Shape.call(this, scene, "Grid", null); this.cellWidth = cellWidth; this.cellHeight = cellHeight; this.showCells = true; this.outlineFillColor = 0; this.outlineFillAlpha = 0; this.showOutline = true; this.showAltCells = false; this.altFillColor; this.altFillAlpha; this.setPosition(x, y); this.setSize(width, height); if (fillColor !== undefined) { this.setFillStyle(fillColor, fillAlpha) } if (outlineFillColor !== undefined) { this.setOutlineStyle(outlineFillColor, outlineFillAlpha) } this.updateDisplayOrigin() }, setFillStyle: function(fillColor, fillAlpha) { if (fillAlpha === undefined) { fillAlpha = 1 } if (fillColor === undefined) { this.showCells = false } else { this.fillColor = fillColor; this.fillAlpha = fillAlpha; this.showCells = true } return this }, setAltFillStyle: function(fillColor, fillAlpha) { if (fillAlpha === undefined) { fillAlpha = 1 } if (fillColor === undefined) { this.showAltCells = false } else { this.altFillColor = fillColor; this.altFillAlpha = fillAlpha; this.showAltCells = true } return this }, setOutlineStyle: function(fillColor, fillAlpha) { if (fillAlpha === undefined) { fillAlpha = 1 } if (fillColor === undefined) { this.showOutline = false } else { this.outlineFillColor = fillColor; this.outlineFillAlpha = fillAlpha; this.showOutline = true } return this } }); module.exports = Grid }, function(module, exports, __webpack_require__) { var IsoBoxRender = __webpack_require__(750); var Class = __webpack_require__(0); var Shape = __webpack_require__(30); var IsoBox = new Class({ Extends: Shape, Mixins: [IsoBoxRender], initialize: function IsoBox(scene, x, y, size, height, fillTop, fillLeft, fillRight) { if (x === undefined) { x = 0 } if (y === undefined) { y = 0 } if (size === undefined) { size = 48 } if (height === undefined) { height = 32 } if (fillTop === undefined) { fillTop = 15658734 } if (fillLeft === undefined) { fillLeft = 10066329 } if (fillRight === undefined) { fillRight = 13421772 } Shape.call(this, scene, "IsoBox", null); this.projection = 4; this.fillTop = fillTop; this.fillLeft = fillLeft; this.fillRight = fillRight; this.showTop = true; this.showLeft = true; this.showRight = true; this.isFilled = true; this.setPosition(x, y); this.setSize(size, height); this.updateDisplayOrigin() }, setProjection: function(value) { this.projection = value; return this }, setFaces: function(showTop, showLeft, showRight) { if (showTop === undefined) { showTop = true } if (showLeft === undefined) { showLeft = true } if (showRight === undefined) { showRight = true } this.showTop = showTop; this.showLeft = showLeft; this.showRight = showRight; return this }, setFillStyle: function(fillTop, fillLeft, fillRight) { this.fillTop = fillTop; this.fillLeft = fillLeft; this.fillRight = fillRight; this.isFilled = true; return this } }); module.exports = IsoBox }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var IsoTriangleRender = __webpack_require__(753); var Shape = __webpack_require__(30); var IsoTriangle = new Class({ Extends: Shape, Mixins: [IsoTriangleRender], initialize: function IsoTriangle(scene, x, y, size, height, reversed, fillTop, fillLeft, fillRight) { if (x === undefined) { x = 0 } if (y === undefined) { y = 0 } if (size === undefined) { size = 48 } if (height === undefined) { height = 32 } if (reversed === undefined) { reversed = false } if (fillTop === undefined) { fillTop = 15658734 } if (fillLeft === undefined) { fillLeft = 10066329 } if (fillRight === undefined) { fillRight = 13421772 } Shape.call(this, scene, "IsoTriangle", null); this.projection = 4; this.fillTop = fillTop; this.fillLeft = fillLeft; this.fillRight = fillRight; this.showTop = true; this.showLeft = true; this.showRight = true; this.isReversed = reversed; this.isFilled = true; this.setPosition(x, y); this.setSize(size, height); this.updateDisplayOrigin() }, setProjection: function(value) { this.projection = value; return this }, setReversed: function(reversed) { this.isReversed = reversed; return this }, setFaces: function(showTop, showLeft, showRight) { if (showTop === undefined) { showTop = true } if (showLeft === undefined) { showLeft = true } if (showRight === undefined) { showRight = true } this.showTop = showTop; this.showLeft = showLeft; this.showRight = showRight; return this }, setFillStyle: function(fillTop, fillLeft, fillRight) { this.fillTop = fillTop; this.fillLeft = fillLeft; this.fillRight = fillRight; this.isFilled = true; return this } }); module.exports = IsoTriangle }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Shape = __webpack_require__(30); var GeomLine = __webpack_require__(54); var LineRender = __webpack_require__(756); var Line = new Class({ Extends: Shape, Mixins: [LineRender], initialize: function Line(scene, x, y, x1, y1, x2, y2, strokeColor, strokeAlpha) { if (x === undefined) { x = 0 } if (y === undefined) { y = 0 } if (x1 === undefined) { x1 = 0 } if (y1 === undefined) { y1 = 0 } if (x2 === undefined) { x2 = 128 } if (y2 === undefined) { y2 = 0 } Shape.call(this, scene, "Line", new GeomLine(x1, y1, x2, y2)); var width = this.geom.right - this.geom.left; var height = this.geom.bottom - this.geom.top; this.lineWidth = 1; this._startWidth = 1; this._endWidth = 1; this.setPosition(x, y); this.setSize(width, height); if (strokeColor !== undefined) { this.setStrokeStyle(1, strokeColor, strokeAlpha) } this.updateDisplayOrigin() }, setLineWidth: function(startWidth, endWidth) { if (endWidth === undefined) { endWidth = startWidth } this._startWidth = startWidth; this._endWidth = endWidth; this.lineWidth = startWidth; return this }, setTo: function(x1, y1, x2, y2) { this.geom.setTo(x1, y1, x2, y2); return this } }); module.exports = Line }, function(module, exports, __webpack_require__) { var PolygonRender = __webpack_require__(759); var Class = __webpack_require__(0); var Earcut = __webpack_require__(63); var GetAABB = __webpack_require__(364); var GeomPolygon = __webpack_require__(189); var Shape = __webpack_require__(30); var Smooth = __webpack_require__(367); var Polygon = new Class({ Extends: Shape, Mixins: [PolygonRender], initialize: function Polygon(scene, x, y, points, fillColor, fillAlpha) { if (x === undefined) { x = 0 } if (y === undefined) { y = 0 } Shape.call(this, scene, "Polygon", new GeomPolygon(points)); var bounds = GetAABB(this.geom); this.setPosition(x, y); this.setSize(bounds.width, bounds.height); if (fillColor !== undefined) { this.setFillStyle(fillColor, fillAlpha) } this.updateDisplayOrigin(); this.updateData() }, smooth: function(iterations) { if (iterations === undefined) { iterations = 1 } for (var i = 0; i < iterations; i++) { Smooth(this.geom) } return this.updateData() }, updateData: function() { var path = []; var points = this.geom.points; for (var i = 0; i < points.length; i++) { path.push(points[i].x, points[i].y) } path.push(points[0].x, points[0].y); this.pathIndexes = Earcut(path); this.pathData = path; return this } }); module.exports = Polygon }, function(module, exports, __webpack_require__) { var Rectangle = __webpack_require__(9); var GetAABB = function(polygon, out) { if (out === undefined) { out = new Rectangle } var minX = Infinity; var minY = Infinity; var maxX = -minX; var maxY = -minY; var p; for (var i = 0; i < polygon.points.length; i++) { p = polygon.points[i]; minX = Math.min(minX, p.x); minY = Math.min(minY, p.y); maxX = Math.max(maxX, p.x); maxY = Math.max(maxY, p.y) } out.x = minX; out.y = minY; out.width = maxX - minX; out.height = maxY - minY; return out }; module.exports = GetAABB }, function(module, exports, __webpack_require__) { var Length = __webpack_require__(62); var Line = __webpack_require__(54); var Perimeter = __webpack_require__(366); var GetPoints = function(polygon, quantity, stepRate, out) { if (out === undefined) { out = [] } var points = polygon.points; var perimeter = Perimeter(polygon); if (!quantity) { quantity = perimeter / stepRate } for (var i = 0; i < quantity; i++) { var position = perimeter * (i / quantity); var accumulatedPerimeter = 0; for (var j = 0; j < points.length; j++) { var pointA = points[j]; var pointB = points[(j + 1) % points.length]; var line = new Line(pointA.x, pointA.y, pointB.x, pointB.y); var length = Length(line); if (position < accumulatedPerimeter || position > accumulatedPerimeter + length) { accumulatedPerimeter += length; continue } var point = line.getPoint((position - accumulatedPerimeter) / length); out.push(point); break } } return out }; module.exports = GetPoints }, function(module, exports, __webpack_require__) { var Length = __webpack_require__(62); var Line = __webpack_require__(54); var Perimeter = function(polygon) { var points = polygon.points; var perimeter = 0; for (var i = 0; i < points.length; i++) { var pointA = points[i]; var pointB = points[(i + 1) % points.length]; var line = new Line(pointA.x, pointA.y, pointB.x, pointB.y); perimeter += Length(line) } return perimeter }; module.exports = Perimeter }, function(module, exports) { var copy = function(out, a) { out[0] = a[0]; out[1] = a[1]; return out }; var Smooth = function(polygon) { var i; var points = []; var data = polygon.points; for (i = 0; i < data.length; i++) { points.push([data[i].x, data[i].y]) } var output = []; if (points.length > 0) { output.push(copy([0, 0], points[0])) } for (i = 0; i < points.length - 1; i++) { var p0 = points[i]; var p1 = points[i + 1]; var p0x = p0[0]; var p0y = p0[1]; var p1x = p1[0]; var p1y = p1[1]; output.push([.85 * p0x + .15 * p1x, .85 * p0y + .15 * p1y]); output.push([.15 * p0x + .85 * p1x, .15 * p0y + .85 * p1y]) } if (points.length > 1) { output.push(copy([0, 0], points[points.length - 1])) } return polygon.setTo(output) }; module.exports = Smooth }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var GeomRectangle = __webpack_require__(9); var Shape = __webpack_require__(30); var RectangleRender = __webpack_require__(762); var Rectangle = new Class({ Extends: Shape, Mixins: [RectangleRender], initialize: function Rectangle(scene, x, y, width, height, fillColor, fillAlpha) { if (x === undefined) { x = 0 } if (y === undefined) { y = 0 } if (width === undefined) { width = 128 } if (height === undefined) { height = 128 } Shape.call(this, scene, "Rectangle", new GeomRectangle(0, 0, width, height)); this.setPosition(x, y); this.setSize(width, height); if (fillColor !== undefined) { this.setFillStyle(fillColor, fillAlpha) } this.updateDisplayOrigin(); this.updateData() }, updateData: function() { var path = []; var rect = this.geom; var line = this._tempLine; rect.getLineA(line); path.push(line.x1, line.y1, line.x2, line.y2); rect.getLineB(line); path.push(line.x2, line.y2); rect.getLineC(line); path.push(line.x2, line.y2); rect.getLineD(line); path.push(line.x2, line.y2); this.pathData = path; return this } }); module.exports = Rectangle }, function(module, exports, __webpack_require__) { var StarRender = __webpack_require__(765); var Class = __webpack_require__(0); var Earcut = __webpack_require__(63); var Shape = __webpack_require__(30); var Star = new Class({ Extends: Shape, Mixins: [StarRender], initialize: function Star(scene, x, y, points, innerRadius, outerRadius, fillColor, fillAlpha) { if (x === undefined) { x = 0 } if (y === undefined) { y = 0 } if (points === undefined) { points = 5 } if (innerRadius === undefined) { innerRadius = 32 } if (outerRadius === undefined) { outerRadius = 64 } Shape.call(this, scene, "Star", null); this._points = points; this._innerRadius = innerRadius; this._outerRadius = outerRadius; this.setPosition(x, y); this.setSize(outerRadius * 2, outerRadius * 2); if (fillColor !== undefined) { this.setFillStyle(fillColor, fillAlpha) } this.updateDisplayOrigin(); this.updateData() }, setPoints: function(value) { this._points = value; return this.updateData() }, setInnerRadius: function(value) { this._innerRadius = value; return this.updateData() }, setOuterRadius: function(value) { this._outerRadius = value; return this.updateData() }, points: { get: function() { return this._points }, set: function(value) { this._points = value; this.updateData() } }, innerRadius: { get: function() { return this._innerRadius }, set: function(value) { this._innerRadius = value; this.updateData() } }, outerRadius: { get: function() { return this._outerRadius }, set: function(value) { this._outerRadius = value; this.updateData() } }, updateData: function() { var path = []; var points = this._points; var innerRadius = this._innerRadius; var outerRadius = this._outerRadius; var rot = Math.PI / 2 * 3; var step = Math.PI / points; var x = outerRadius; var y = outerRadius; path.push(x, y + -outerRadius); for (var i = 0; i < points; i++) { path.push(x + Math.cos(rot) * outerRadius, y + Math.sin(rot) * outerRadius); rot += step; path.push(x + Math.cos(rot) * innerRadius, y + Math.sin(rot) * innerRadius); rot += step } path.push(x, y + -outerRadius); this.pathIndexes = Earcut(path); this.pathData = path; return this } }); module.exports = Star }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Shape = __webpack_require__(30); var GeomTriangle = __webpack_require__(67); var TriangleRender = __webpack_require__(768); var Triangle = new Class({ Extends: Shape, Mixins: [TriangleRender], initialize: function Triangle(scene, x, y, x1, y1, x2, y2, x3, y3, fillColor, fillAlpha) { if (x === undefined) { x = 0 } if (y === undefined) { y = 0 } if (x1 === undefined) { x1 = 0 } if (y1 === undefined) { y1 = 128 } if (x2 === undefined) { x2 = 64 } if (y2 === undefined) { y2 = 0 } if (x3 === undefined) { x3 = 128 } if (y3 === undefined) { y3 = 128 } Shape.call(this, scene, "Triangle", new GeomTriangle(x1, y1, x2, y2, x3, y3)); var width = this.geom.right - this.geom.left; var height = this.geom.bottom - this.geom.top; this.setPosition(x, y); this.setSize(width, height); if (fillColor !== undefined) { this.setFillStyle(fillColor, fillAlpha) } this.updateDisplayOrigin(); this.updateData() }, setTo: function(x1, y1, x2, y2, x3, y3) { this.geom.setTo(x1, y1, x2, y2, x3, y3); return this.updateData() }, updateData: function() { var path = []; var rect = this.geom; var line = this._tempLine; rect.getLineA(line); path.push(line.x1, line.y1, line.x2, line.y2); rect.getLineB(line); path.push(line.x2, line.y2); rect.getLineC(line); path.push(line.x2, line.y2); this.pathData = path; return this } }); module.exports = Triangle }, function(module, exports, __webpack_require__) { var Point = __webpack_require__(6); var Length = __webpack_require__(62); var GetPoint = function(triangle, position, out) { if (out === undefined) { out = new Point } var line1 = triangle.getLineA(); var line2 = triangle.getLineB(); var line3 = triangle.getLineC(); if (position <= 0 || position >= 1) { out.x = line1.x1; out.y = line1.y1; return out } var length1 = Length(line1); var length2 = Length(line2); var length3 = Length(line3); var perimeter = length1 + length2 + length3; var p = perimeter * position; var localPosition = 0; if (p < length1) { localPosition = p / length1; out.x = line1.x1 + (line1.x2 - line1.x1) * localPosition; out.y = line1.y1 + (line1.y2 - line1.y1) * localPosition } else if (p > length1 + length2) { p -= length1 + length2; localPosition = p / length3; out.x = line3.x1 + (line3.x2 - line3.x1) * localPosition; out.y = line3.y1 + (line3.y2 - line3.y1) * localPosition } else { p -= length1; localPosition = p / length2; out.x = line2.x1 + (line2.x2 - line2.x1) * localPosition; out.y = line2.y1 + (line2.y2 - line2.y1) * localPosition } return out }; module.exports = GetPoint }, function(module, exports, __webpack_require__) { var Length = __webpack_require__(62); var Point = __webpack_require__(6); var GetPoints = function(triangle, quantity, stepRate, out) { if (out === undefined) { out = [] } var line1 = triangle.getLineA(); var line2 = triangle.getLineB(); var line3 = triangle.getLineC(); var length1 = Length(line1); var length2 = Length(line2); var length3 = Length(line3); var perimeter = length1 + length2 + length3; if (!quantity) { quantity = perimeter / stepRate } for (var i = 0; i < quantity; i++) { var p = perimeter * (i / quantity); var localPosition = 0; var point = new Point; if (p < length1) { localPosition = p / length1; point.x = line1.x1 + (line1.x2 - line1.x1) * localPosition; point.y = line1.y1 + (line1.y2 - line1.y1) * localPosition } else if (p > length1 + length2) { p -= length1 + length2; localPosition = p / length3; point.x = line3.x1 + (line3.x2 - line3.x1) * localPosition; point.y = line3.y1 + (line3.y2 - line3.y1) * localPosition } else { p -= length1; localPosition = p / length2; point.x = line2.x1 + (line2.x2 - line2.x1) * localPosition; point.y = line2.y1 + (line2.y2 - line2.y1) * localPosition } out.push(point) } return out }; module.exports = GetPoints }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Components = __webpack_require__(14); var DOMElementRender = __webpack_require__(809); var GameObject = __webpack_require__(12); var RemoveFromDOM = __webpack_require__(168); var Vector4 = __webpack_require__(125); var DOMElement = new Class({ Extends: GameObject, Mixins: [Components.Alpha, Components.BlendMode, Components.ComputedSize, Components.Depth, Components.Origin, Components.ScrollFactor, Components.Transform, Components.Visible, DOMElementRender], initialize: function DOMElement(scene, x, y, element) { GameObject.call(this, scene, "DOMElement"); this.parent = scene.sys.game.domContainer; this.cache = scene.sys.cache.html; this.node; this.skewX = 0; this.skewY = 0; this.rotate3d = new Vector4; this.rotate3dAngle = "deg"; this.handler = this.dispatchNativeEvent.bind(this); this.setPosition(x, y); if (element) { this.setElement(element) } }, setSkew: function(x, y) { if (x === undefined) { x = 0 } if (y === undefined) { y = x } this.skewX = x; this.skewY = y; return this }, perspective: { get: function() { return parseFloat(this.parent.style.perspective) }, set: function(value) { this.parent.style.perspective = value + "px" } }, setPerspective: function(value) { this.parent.style.perspective = value + "px"; return this }, addListener: function(events) { if (this.node) { events = events.split(" "); for (var i = 0; i < events.length; i++) { this.node.addEventListener(events[i], this.handler, false) } } return this }, removeListener: function(events) { if (this.node) { events = events.split(" "); for (var i = 0; i < events.length; i++) { this.node.removeEventListener(events[i], this.handler) } } return this }, dispatchNativeEvent: function(event) { this.emit(event.type, event) }, setElement: function(element) { var target; if (typeof element === "string") { target = document.getElementById(element) } else if (typeof element === "object" && element.nodeType === 1) { target = element } if (!target) { return } this.node = target; target.style.zIndex = "0"; target.style.display = "inline"; target.style.position = "absolute"; target.phaser = this; if (this.parent) { this.parent.appendChild(target) } var nodeBounds = target.getBoundingClientRect(); this.setSize(nodeBounds.width || 0, nodeBounds.height || 0); return this }, createFromCache: function(key, elementType) { return this.createFromHTML(this.cache.get(key), elementType) }, createFromHTML: function(html, elementType) { if (elementType === undefined) { elementType = "div" } var element = document.createElement(elementType); this.node = element; element.style.zIndex = "0"; element.style.display = "inline"; element.style.position = "absolute"; element.phaser = this; if (this.parent) { this.parent.appendChild(element) } element.innerHTML = html; var nodeBounds = element.getBoundingClientRect(); this.setSize(nodeBounds.width || 0, nodeBounds.height || 0); return this }, getChildByProperty: function(property, value) { if (this.node) { var children = this.node.querySelectorAll("*"); for (var i = 0; i < children.length; i++) { if (children[i][property] === value) { return children[i] } } } return null }, getChildByID: function(id) { return this.getChildByProperty("id", id) }, getChildByName: function(name) { return this.getChildByProperty("name", name) }, setText: function(text) { if (this.node) { this.node.innerText = text; var nodeBounds = this.node.getBoundingClientRect(); this.setSize(nodeBounds.width, nodeBounds.height) } return this }, setHTML: function(html) { if (this.node) { this.node.innerHTML = html; var nodeBounds = this.node.getBoundingClientRect(); this.setSize(nodeBounds.width, nodeBounds.height) } return this }, willRender: function() { return true }, destroy: function() { RemoveFromDOM(this.node) } }); module.exports = DOMElement }, function(module, exports, __webpack_require__) { var CSSBlendModes = __webpack_require__(810); var GameObject = __webpack_require__(12); var DOMElementCSSRenderer = function(renderer, src, interpolationPercentage, camera) { var node = src.node; if (!node || GameObject.RENDER_MASK !== src.renderFlags || src.cameraFilter > 0 && src.cameraFilter & camera.id) { if (node) { node.style.display = "none" } return } var camMatrix = renderer._tempMatrix1; var spriteMatrix = renderer._tempMatrix2; var calcMatrix = renderer._tempMatrix3; var x = src.originX * src.width; var y = src.originY * src.height; spriteMatrix.applyITRS(src.x - x - camera.scrollX * src.scrollFactorX, src.y - y - camera.scrollY * src.scrollFactorY, src.rotation, src.scaleX, src.scaleY); camMatrix.copyFrom(camera.matrix); camMatrix.multiply(spriteMatrix, calcMatrix); node.style.display = "block"; node.style.opacity = src.alpha; node.style.zIndex = src._depth; node.style.pointerEvents = "auto"; node.style.mixBlendMode = CSSBlendModes[src._blendMode]; node.style.transform = calcMatrix.getCSSMatrix() + " skew(" + src.skewX + "rad, " + src.skewY + "rad)" + " rotate3d(" + src.rotate3d.x + "," + src.rotate3d.y + "," + src.rotate3d.z + "," + src.rotate3d.w + src.rotate3dAngle + ")"; node.style.transformOrigin = 100 * src.originX + "% " + 100 * src.originY + "%" }; module.exports = DOMElementCSSRenderer }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Utils = __webpack_require__(10); var Light = new Class({ initialize: function Light(x, y, radius, r, g, b, intensity) { this.x = x; this.y = y; this.radius = radius; this.r = r; this.g = g; this.b = b; this.intensity = intensity; this.scrollFactorX = 1; this.scrollFactorY = 1 }, set: function(x, y, radius, r, g, b, intensity) { this.x = x; this.y = y; this.radius = radius; this.r = r; this.g = g; this.b = b; this.intensity = intensity; this.scrollFactorX = 1; this.scrollFactorY = 1; return this }, setScrollFactor: function(x, y) { if (x === undefined) { x = 1 } if (y === undefined) { y = x } this.scrollFactorX = x; this.scrollFactorY = y; return this }, setColor: function(rgb) { var color = Utils.getFloatsFromUintRGB(rgb); this.r = color[0]; this.g = color[1]; this.b = color[2]; return this }, setIntensity: function(intensity) { this.intensity = intensity; return this }, setPosition: function(x, y) { this.x = x; this.y = y; return this }, setRadius: function(radius) { this.radius = radius; return this } }); module.exports = Light }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Light = __webpack_require__(375); var Utils = __webpack_require__(10); var LightsManager = new Class({ initialize: function LightsManager() { this.lightPool = []; this.lights = []; this.culledLights = []; this.ambientColor = { r: .1, g: .1, b: .1 }; this.active = false; this.maxLights = -1 }, enable: function() { if (this.maxLights === -1) { this.maxLights = this.scene.sys.game.renderer.config.maxLights } this.active = true; return this }, disable: function() { this.active = false; return this }, cull: function(camera) { var lights = this.lights; var culledLights = this.culledLights; var length = lights.length; var cameraCenterX = camera.x + camera.width / 2; var cameraCenterY = camera.y + camera.height / 2; var cameraRadius = (camera.width + camera.height) / 2; var point = { x: 0, y: 0 }; var cameraMatrix = camera.matrix; var viewportHeight = this.systems.game.config.height; culledLights.length = 0; for (var index = 0; index < length && culledLights.length < this.maxLights; index++) { var light = lights[index]; cameraMatrix.transformPoint(light.x, light.y, point); var dx = cameraCenterX - (point.x - camera.scrollX * light.scrollFactorX * camera.zoom); var dy = cameraCenterY - (viewportHeight - (point.y - camera.scrollY * light.scrollFactorY * camera.zoom)); var distance = Math.sqrt(dx * dx + dy * dy); if (distance < light.radius + cameraRadius) { culledLights.push(lights[index]) } } return culledLights }, forEachLight: function(callback) { if (!callback) { return } var lights = this.lights; var length = lights.length; for (var index = 0; index < length; ++index) { callback(lights[index]) } return this }, setAmbientColor: function(rgb) { var color = Utils.getFloatsFromUintRGB(rgb); this.ambientColor.r = color[0]; this.ambientColor.g = color[1]; this.ambientColor.b = color[2]; return this }, getMaxVisibleLights: function() { return 10 }, getLightCount: function() { return this.lights.length }, addLight: function(x, y, radius, rgb, intensity) { var color = null; var light = null; x = x === undefined ? 0 : x; y = y === undefined ? 0 : y; rgb = rgb === undefined ? 16777215 : rgb; radius = radius === undefined ? 100 : radius; intensity = intensity === undefined ? 1 : intensity; color = Utils.getFloatsFromUintRGB(rgb); light = null; if (this.lightPool.length > 0) { light = this.lightPool.pop(); light.set(x, y, radius, color[0], color[1], color[2], intensity) } else { light = new Light(x, y, radius, color[0], color[1], color[2], intensity) } this.lights.push(light); return light }, removeLight: function(light) { var index = this.lights.indexOf(light); if (index >= 0) { this.lightPool.push(light); this.lights.splice(index, 1) } return this }, shutdown: function() { while (this.lights.length > 0) { this.lightPool.push(this.lights.pop()) } this.ambientColor = { r: .1, g: .1, b: .1 }; this.culledLights.length = 0; this.lights.length = 0 }, destroy: function() { this.shutdown() } }); module.exports = LightsManager }, function(module, exports, __webpack_require__) { module.exports = { Circle: __webpack_require__(820), Ellipse: __webpack_require__(830), Intersects: __webpack_require__(378), Line: __webpack_require__(850), Point: __webpack_require__(868), Polygon: __webpack_require__(882), Rectangle: __webpack_require__(386), Triangle: __webpack_require__(912) } }, function(module, exports, __webpack_require__) { module.exports = { CircleToCircle: __webpack_require__(840), CircleToRectangle: __webpack_require__(841), GetRectangleIntersection: __webpack_require__(842), LineToCircle: __webpack_require__(379), LineToLine: __webpack_require__(127), LineToRectangle: __webpack_require__(843), PointToLine: __webpack_require__(380), PointToLineSegment: __webpack_require__(844), RectangleToRectangle: __webpack_require__(192), RectangleToTriangle: __webpack_require__(845), RectangleToValues: __webpack_require__(846), TriangleToCircle: __webpack_require__(847), TriangleToLine: __webpack_require__(848), TriangleToTriangle: __webpack_require__(849) } }, function(module, exports, __webpack_require__) { var Contains = __webpack_require__(46); var Point = __webpack_require__(6); var tmp = new Point; var LineToCircle = function(line, circle, nearest) { if (nearest === undefined) { nearest = tmp } if (Contains(circle, line.x1, line.y1)) { nearest.x = line.x1; nearest.y = line.y1; return true } if (Contains(circle, line.x2, line.y2)) { nearest.x = line.x2; nearest.y = line.y2; return true } var dx = line.x2 - line.x1; var dy = line.y2 - line.y1; var lcx = circle.x - line.x1; var lcy = circle.y - line.y1; var dLen2 = dx * dx + dy * dy; var px = dx; var py = dy; if (dLen2 > 0) { var dp = (lcx * dx + lcy * dy) / dLen2; px *= dp; py *= dp } nearest.x = line.x1 + px; nearest.y = line.y1 + py; var pLen2 = px * px + py * py; return pLen2 <= dLen2 && px * dx + py * dy >= 0 && Contains(circle, nearest.x, nearest.y) }; module.exports = LineToCircle }, function(module, exports) { var PointToLine = function(point, line) { return (point.x - line.x1) * (line.y2 - line.y1) === (line.x2 - line.x1) * (point.y - line.y1) }; module.exports = PointToLine }, function(module, exports) { var Decompose = function(rect, out) { if (out === undefined) { out = [] } out.push({ x: rect.x, y: rect.y }); out.push({ x: rect.right, y: rect.y }); out.push({ x: rect.right, y: rect.bottom }); out.push({ x: rect.x, y: rect.bottom }); return out }; module.exports = Decompose }, function(module, exports) { var Decompose = function(triangle, out) { if (out === undefined) { out = [] } out.push({ x: triangle.x1, y: triangle.y1 }); out.push({ x: triangle.x2, y: triangle.y2 }); out.push({ x: triangle.x3, y: triangle.y3 }); return out }; module.exports = Decompose }, function(module, exports, __webpack_require__) { var MATH_CONST = __webpack_require__(18); var Wrap = __webpack_require__(55); var Angle = __webpack_require__(85); var NormalAngle = function(line) { var angle = Angle(line) - MATH_CONST.TAU; return Wrap(angle, -Math.PI, Math.PI) }; module.exports = NormalAngle }, function(module, exports) { var GetMagnitude = function(point) { return Math.sqrt(point.x * point.x + point.y * point.y) }; module.exports = GetMagnitude }, function(module, exports) { var GetMagnitudeSq = function(point) { return point.x * point.x + point.y * point.y }; module.exports = GetMagnitudeSq }, function(module, exports, __webpack_require__) { var Rectangle = __webpack_require__(9); Rectangle.Area = __webpack_require__(887); Rectangle.Ceil = __webpack_require__(888); Rectangle.CeilAll = __webpack_require__(889); Rectangle.CenterOn = __webpack_require__(162); Rectangle.Clone = __webpack_require__(890); Rectangle.Contains = __webpack_require__(47); Rectangle.ContainsPoint = __webpack_require__(891); Rectangle.ContainsRect = __webpack_require__(387); Rectangle.CopyFrom = __webpack_require__(892); Rectangle.Decompose = __webpack_require__(381); Rectangle.Equals = __webpack_require__(893); Rectangle.FitInside = __webpack_require__(894); Rectangle.FitOutside = __webpack_require__(895); Rectangle.Floor = __webpack_require__(896); Rectangle.FloorAll = __webpack_require__(897); Rectangle.FromPoints = __webpack_require__(164); Rectangle.GetAspectRatio = __webpack_require__(195); Rectangle.GetCenter = __webpack_require__(898); Rectangle.GetPoint = __webpack_require__(146); Rectangle.GetPoints = __webpack_require__(245); Rectangle.GetSize = __webpack_require__(899); Rectangle.Inflate = __webpack_require__(900); Rectangle.Intersection = __webpack_require__(901); Rectangle.MarchingAnts = __webpack_require__(255); Rectangle.MergePoints = __webpack_require__(902); Rectangle.MergeRect = __webpack_require__(903); Rectangle.MergeXY = __webpack_require__(904); Rectangle.Offset = __webpack_require__(905); Rectangle.OffsetPoint = __webpack_require__(906); Rectangle.Overlaps = __webpack_require__(907); Rectangle.Perimeter = __webpack_require__(108); Rectangle.PerimeterPoint = __webpack_require__(908); Rectangle.Random = __webpack_require__(149); Rectangle.RandomOutside = __webpack_require__(909); Rectangle.SameDimensions = __webpack_require__(910); Rectangle.Scale = __webpack_require__(911); Rectangle.Union = __webpack_require__(340); module.exports = Rectangle }, function(module, exports) { var ContainsRect = function(rectA, rectB) { if (rectB.width * rectB.height > rectA.width * rectA.height) { return false } return rectB.x > rectA.x && rectB.x < rectA.right && (rectB.right > rectA.x && rectB.right < rectA.right) && (rectB.y > rectA.y && rectB.y < rectA.bottom) && (rectB.bottom > rectA.y && rectB.bottom < rectA.bottom) }; module.exports = ContainsRect }, function(module, exports, __webpack_require__) { var Point = __webpack_require__(6); var Centroid = function(triangle, out) { if (out === undefined) { out = new Point } out.x = (triangle.x1 + triangle.x2 + triangle.x3) / 3; out.y = (triangle.y1 + triangle.y2 + triangle.y3) / 3; return out }; module.exports = Centroid }, function(module, exports) { var Offset = function(triangle, x, y) { triangle.x1 += x; triangle.y1 += y; triangle.x2 += x; triangle.y2 += y; triangle.x3 += x; triangle.y3 += y; return triangle }; module.exports = Offset }, function(module, exports, __webpack_require__) { var Point = __webpack_require__(6); function getLength(x1, y1, x2, y2) { var x = x1 - x2; var y = y1 - y2; var magnitude = x * x + y * y; return Math.sqrt(magnitude) } var InCenter = function(triangle, out) { if (out === undefined) { out = new Point } var x1 = triangle.x1; var y1 = triangle.y1; var x2 = triangle.x2; var y2 = triangle.y2; var x3 = triangle.x3; var y3 = triangle.y3; var d1 = getLength(x3, y3, x2, y2); var d2 = getLength(x1, y1, x3, y3); var d3 = getLength(x2, y2, x1, y1); var p = d1 + d2 + d3; out.x = (x1 * d1 + x2 * d2 + x3 * d3) / p; out.y = (y1 * d1 + y2 * d2 + y3 * d3) / p; return out }; module.exports = InCenter }, function(module, exports) { var CreateInteractiveObject = function(gameObject, hitArea, hitAreaCallback) { return { gameObject: gameObject, enabled: true, draggable: false, dropZone: false, cursor: false, target: null, camera: null, hitArea: hitArea, hitAreaCallback: hitAreaCallback, localX: 0, localY: 0, dragState: 0, dragStartX: 0, dragStartY: 0, dragX: 0, dragY: 0 } }; module.exports = CreateInteractiveObject }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Axis = new Class({ initialize: function Axis(pad, index) { this.pad = pad; this.events = pad.events; this.index = index; this.value = 0; this.threshold = .1 }, update: function(value) { this.value = value }, getValue: function() { return Math.abs(this.value) < this.threshold ? 0 : this.value }, destroy: function() { this.pad = null; this.events = null } }); module.exports = Axis }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Button = new Class({ initialize: function Button(pad, index) { this.pad = pad; this.events = pad.manager; this.index = index; this.value = 0; this.threshold = 1; this.pressed = false }, update: function(value) { this.value = value; var pad = this.pad; var index = this.index; if (value >= this.threshold) { if (!this.pressed) { this.pressed = true; this.events.emit("down", pad, this, value); this.pad.emit("down", index, value, this) } } else if (this.pressed) { this.pressed = false; this.events.emit("up", pad, this, value); this.pad.emit("up", index, value, this) } }, destroy: function() { this.pad = null; this.events = null } }); module.exports = Button }, function(module, exports, __webpack_require__) { var Axis = __webpack_require__(392); var Button = __webpack_require__(393); var Class = __webpack_require__(0); var EventEmitter = __webpack_require__(11); var Vector2 = __webpack_require__(3); var Gamepad = new Class({ Extends: EventEmitter, initialize: function Gamepad(manager, pad) { EventEmitter.call(this); this.manager = manager; this.pad = pad; this.id = pad.id; this.index = pad.index; var buttons = []; for (var i = 0; i < pad.buttons.length; i++) { buttons.push(new Button(this, i)) } this.buttons = buttons; var axes = []; for (i = 0; i < pad.axes.length; i++) { axes.push(new Axis(this, i)) } this.axes = axes; this.vibration = pad.vibrationActuator; var _noButton = { value: 0, pressed: false }; this._LCLeft = buttons[14] ? buttons[14] : _noButton; this._LCRight = buttons[15] ? buttons[15] : _noButton; this._LCTop = buttons[12] ? buttons[12] : _noButton; this._LCBottom = buttons[13] ? buttons[13] : _noButton; this._RCLeft = buttons[2] ? buttons[2] : _noButton; this._RCRight = buttons[1] ? buttons[1] : _noButton; this._RCTop = buttons[3] ? buttons[3] : _noButton; this._RCBottom = buttons[0] ? buttons[0] : _noButton; this._FBLeftTop = buttons[4] ? buttons[4] : _noButton; this._FBLeftBottom = buttons[6] ? buttons[6] : _noButton; this._FBRightTop = buttons[5] ? buttons[5] : _noButton; this._FBRightBottom = buttons[7] ? buttons[7] : _noButton; var _noAxis = { value: 0 }; this._HAxisLeft = axes[0] ? axes[0] : _noAxis; this._VAxisLeft = axes[1] ? axes[1] : _noAxis; this._HAxisRight = axes[2] ? axes[2] : _noAxis; this._VAxisRight = axes[3] ? axes[3] : _noAxis; this.leftStick = new Vector2; this.rightStick = new Vector2 }, getAxisTotal: function() { return this.axes.length }, getAxisValue: function(index) { return this.axes[index].getValue() }, setAxisThreshold: function(value) { for (var i = 0; i < this.axes.length; i++) { this.axes[i].threshold = value } }, getButtonTotal: function() { return this.buttons.length }, getButtonValue: function(index) { return this.buttons[index].value }, isButtonDown: function(index) { return this.buttons[index].pressed }, update: function(pad) { var i; var localButtons = this.buttons; var gamepadButtons = pad.buttons; var len = localButtons.length; for (i = 0; i < len; i++) { localButtons[i].update(gamepadButtons[i].value) } var localAxes = this.axes; var gamepadAxes = pad.axes; len = localAxes.length; for (i = 0; i < len; i++) { localAxes[i].update(gamepadAxes[i]) } if (len >= 2) { this.leftStick.set(localAxes[0].getValue(), localAxes[1].getValue()); if (len >= 4) { this.rightStick.set(localAxes[2].getValue(), localAxes[3].getValue()) } } }, destroy: function() { this.removeAllListeners(); this.manager = null; this.pad = null; var i; for (i = 0; i < this.buttons.length; i++) { this.buttons[i].destroy() } for (i = 0; i < this.axes.length; i++) { this.axes[i].destroy() } this.buttons = []; this.axes = [] }, connected: { get: function() { return this.pad.connected } }, timestamp: { get: function() { return this.pad.timestamp } }, left: { get: function() { return this._LCLeft.pressed } }, right: { get: function() { return this._LCRight.pressed } }, up: { get: function() { return this._LCTop.pressed } }, down: { get: function() { return this._LCBottom.pressed } }, A: { get: function() { return this._RCBottom.pressed } }, Y: { get: function() { return this._RCTop.pressed } }, X: { get: function() { return this._RCLeft.pressed } }, B: { get: function() { return this._RCRight.pressed } }, L1: { get: function() { return this._FBLeftTop.value } }, L2: { get: function() { return this._FBLeftBottom.value } }, R1: { get: function() { return this._FBRightTop.value } }, R2: { get: function() { return this._FBRightBottom.value } } }); module.exports = Gamepad }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Key = new Class({ initialize: function Key(keyCode) { this.keyCode = keyCode; this.originalEvent = undefined; this.preventDefault = true; this.enabled = true; this.isDown = false; this.isUp = true; this.altKey = false; this.ctrlKey = false; this.shiftKey = false; this.location = 0; this.timeDown = 0; this.duration = 0; this.timeUp = 0; this.repeats = 0; this._justDown = false; this._justUp = false; this._tick = -1 }, reset: function() { this.preventDefault = true; this.enabled = true; this.isDown = false; this.isUp = true; this.altKey = false; this.ctrlKey = false; this.shiftKey = false; this.timeDown = 0; this.duration = 0; this.timeUp = 0; this.repeats = 0; this._justDown = false; this._justUp = false; this._tick = -1; return this } }); module.exports = Key }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var GetFastValue = __webpack_require__(1); var ProcessKeyCombo = __webpack_require__(938); var ResetKeyCombo = __webpack_require__(940); var KeyCombo = new Class({ initialize: function KeyCombo(keyboardPlugin, keys, config) { if (config === undefined) { config = {} } if (keys.length < 2) { return false } this.manager = keyboardPlugin; this.enabled = true; this.keyCodes = []; for (var i = 0; i < keys.length; i++) { var char = keys[i]; if (typeof char === "string") { this.keyCodes.push(char.toUpperCase().charCodeAt(0)) } else if (typeof char === "number") { this.keyCodes.push(char) } else if (char.hasOwnProperty("keyCode")) { this.keyCodes.push(char.keyCode) } } this.current = this.keyCodes[0]; this.index = 0; this.size = this.keyCodes.length; this.timeLastMatched = 0; this.matched = false; this.timeMatched = 0; this.resetOnWrongKey = GetFastValue(config, "resetOnWrongKey", true); this.maxKeyDelay = GetFastValue(config, "maxKeyDelay", 0); this.resetOnMatch = GetFastValue(config, "resetOnMatch", false); this.deleteOnMatch = GetFastValue(config, "deleteOnMatch", false); var _this = this; var onKeyDownHandler = function(event) { if (_this.matched || !_this.enabled) { return } var matched = ProcessKeyCombo(event, _this); if (matched) { _this.manager.emit("keycombomatch", _this, event); if (_this.resetOnMatch) { ResetKeyCombo(_this) } else if (_this.deleteOnMatch) { _this.destroy() } } }; this.onKeyDown = onKeyDownHandler; this.manager.on("keydown", onKeyDownHandler) }, progress: { get: function() { return this.index / this.size } }, destroy: function() { this.enabled = false; this.keyCodes = []; this.manager.off("keydown", this.onKeyDown); this.manager = null } }); module.exports = KeyCombo }, function(module, exports, __webpack_require__) { var MergeXHRSettings = __webpack_require__(200); var XHRLoader = function(file, globalXHRSettings) { var config = MergeXHRSettings(globalXHRSettings, file.xhrSettings); var xhr = new XMLHttpRequest; xhr.open("GET", file.src, config.async, config.user, config.password); xhr.responseType = file.xhrSettings.responseType; xhr.timeout = config.timeout; if (config.header && config.headerValue) { xhr.setRequestHeader(config.header, config.headerValue) } if (config.requestedWith) { xhr.setRequestHeader("X-Requested-With", config.requestedWith) } if (config.overrideMimeType) { xhr.overrideMimeType(config.overrideMimeType) } xhr.onload = file.onLoad.bind(file, xhr); xhr.onerror = file.onError.bind(file); xhr.onprogress = file.onProgress.bind(file); xhr.send(); return xhr }; module.exports = XHRLoader }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var CONST = __webpack_require__(26); var File = __webpack_require__(22); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(1); var HTML5AudioFile = __webpack_require__(399); var IsPlainObject = __webpack_require__(7); var AudioFile = new Class({ Extends: File, initialize: function AudioFile(loader, key, urlConfig, xhrSettings, audioContext) { if (IsPlainObject(key)) { var config = key; key = GetFastValue(config, "key"); xhrSettings = GetFastValue(config, "xhrSettings"); audioContext = GetFastValue(config, "context", audioContext) } var fileConfig = { type: "audio", cache: loader.cacheManager.audio, extension: urlConfig.type, responseType: "arraybuffer", key: key, url: urlConfig.url, xhrSettings: xhrSettings, config: { context: audioContext } }; File.call(this, loader, fileConfig) }, onProcess: function() { this.state = CONST.FILE_PROCESSING; var _this = this; this.config.context.decodeAudioData(this.xhrLoader.response, function(audioBuffer) { _this.data = audioBuffer; _this.onProcessComplete() }, function(e) { console.error("Error decoding audio: " + this.key + " - ", e ? e.message : null); _this.onProcessError() }); this.config.context = null } }); AudioFile.create = function(loader, key, urls, config, xhrSettings) { var game = loader.systems.game; var audioConfig = game.config.audio; var deviceAudio = game.device.audio; if (IsPlainObject(key)) { urls = GetFastValue(key, "url", []); config = GetFastValue(key, "config", {}) } var urlConfig = AudioFile.getAudioURL(game, urls); if (!urlConfig) { return null } if (deviceAudio.webAudio && !(audioConfig && audioConfig.disableWebAudio)) { return new AudioFile(loader, key, urlConfig, xhrSettings, game.sound.context) } else { return new HTML5AudioFile(loader, key, urlConfig, config) } }; AudioFile.getAudioURL = function(game, urls) { if (!Array.isArray(urls)) { urls = [urls] } for (var i = 0; i < urls.length; i++) { var url = GetFastValue(urls[i], "url", urls[i]); if (url.indexOf("blob:") === 0 || url.indexOf("data:") === 0) { return url } var audioType = url.match(/\.([a-zA-Z0-9]+)($|\?)/); audioType = GetFastValue(urls[i], "type", audioType ? audioType[1] : "").toLowerCase(); if (game.device.audio[audioType]) { return { url: url, type: audioType } } } return null }; FileTypesManager.register("audio", function(key, urls, config, xhrSettings) { var game = this.systems.game; var audioConfig = game.config.audio; var deviceAudio = game.device.audio; if (audioConfig && audioConfig.noAudio || !deviceAudio.webAudio && !deviceAudio.audioData) { return this } var audioFile; if (Array.isArray(key)) { for (var i = 0; i < key.length; i++) { audioFile = AudioFile.create(this, key[i]); if (audioFile) { this.addFile(audioFile) } } } else { audioFile = AudioFile.create(this, key, urls, config, xhrSettings); if (audioFile) { this.addFile(audioFile) } } return this }); module.exports = AudioFile }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var File = __webpack_require__(22); var GetFastValue = __webpack_require__(1); var GetURL = __webpack_require__(199); var IsPlainObject = __webpack_require__(7); var HTML5AudioFile = new Class({ Extends: File, initialize: function HTML5AudioFile(loader, key, urlConfig, audioConfig) { if (IsPlainObject(key)) { var config = key; key = GetFastValue(config, "key"); audioConfig = GetFastValue(config, "config", audioConfig) } var fileConfig = { type: "audio", cache: loader.cacheManager.audio, extension: urlConfig.type, key: key, url: urlConfig.url, config: audioConfig }; File.call(this, loader, fileConfig); this.locked = "ontouchstart" in window; this.loaded = false; this.filesLoaded = 0; this.filesTotal = 0 }, onLoad: function() { if (this.loaded) { return } this.loaded = true; this.loader.nextFile(this, true) }, onError: function() { for (var i = 0; i < this.data.length; i++) { var audio = this.data[i]; audio.oncanplaythrough = null; audio.onerror = null } this.loader.nextFile(this, false) }, onProgress: function(event) { var audio = event.target; audio.oncanplaythrough = null; audio.onerror = null; this.filesLoaded++; this.percentComplete = Math.min(this.filesLoaded / this.filesTotal, 1); this.loader.emit("fileprogress", this, this.percentComplete); if (this.filesLoaded === this.filesTotal) { this.onLoad() } }, load: function() { this.data = []; var instances = this.config && this.config.instances || 1; this.filesTotal = instances; this.filesLoaded = 0; this.percentComplete = 0; for (var i = 0; i < instances; i++) { var audio = new Audio; audio.dataset.name = this.key + ("0" + i).slice(-2); audio.dataset.used = "false"; if (this.locked) { audio.dataset.locked = "true" } else { audio.dataset.locked = "false"; audio.preload = "auto"; audio.oncanplaythrough = this.onProgress.bind(this); audio.onerror = this.onError.bind(this) } this.data.push(audio) } for (i = 0; i < this.data.length; i++) { audio = this.data[i]; audio.src = GetURL(this, this.loader.baseURL); if (!this.locked) { audio.load() } } if (this.locked) { setTimeout(this.onLoad.bind(this)) } } }); module.exports = HTML5AudioFile }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var CONST = __webpack_require__(20); var File = __webpack_require__(22); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(1); var IsPlainObject = __webpack_require__(7); var TextFile = new Class({ Extends: File, initialize: function TextFile(loader, key, url, xhrSettings) { var extension = "txt"; if (IsPlainObject(key)) { var config = key; key = GetFastValue(config, "key"); url = GetFastValue(config, "url"); xhrSettings = GetFastValue(config, "xhrSettings"); extension = GetFastValue(config, "extension", extension) } var fileConfig = { type: "text", cache: loader.cacheManager.text, extension: extension, responseType: "text", key: key, url: url, xhrSettings: xhrSettings }; File.call(this, loader, fileConfig) }, onProcess: function() { this.state = CONST.FILE_PROCESSING; this.data = this.xhrLoader.responseText; this.onProcessComplete() } }); FileTypesManager.register("text", function(key, url, xhrSettings) { if (Array.isArray(key)) { for (var i = 0; i < key.length; i++) { this.addFile(new TextFile(this, key[i])) } } else { this.addFile(new TextFile(this, key, url, xhrSettings)) } return this }); module.exports = TextFile }, function(module, exports) { var Normalize = function(angle) { angle = angle % (2 * Math.PI); if (angle >= 0) { return angle } else { return angle + 2 * Math.PI } }; module.exports = Normalize }, function(module, exports) { var DistanceSquared = function(x1, y1, x2, y2) { var dx = x1 - x2; var dy = y1 - y2; return dx * dx + dy * dy }; module.exports = DistanceSquared }, function(module, exports) { var Equal = function(a, b, epsilon) { if (epsilon === undefined) { epsilon = 1e-4 } return Math.abs(a - b) < epsilon }; module.exports = Equal }, function(module, exports) { var GreaterThan = function(a, b, epsilon) { if (epsilon === undefined) { epsilon = 1e-4 } return a > b - epsilon }; module.exports = GreaterThan }, function(module, exports) { var LessThan = function(a, b, epsilon) { if (epsilon === undefined) { epsilon = 1e-4 } return a < b + epsilon }; module.exports = LessThan }, function(module, exports, __webpack_require__) { var Factorial = __webpack_require__(407); var Bernstein = function(n, i) { return Factorial(n) / Factorial(i) / Factorial(n - i) }; module.exports = Bernstein }, function(module, exports) { var Factorial = function(value) { if (value === 0) { return 1 } var res = value; while (--value) { res *= value } return res }; module.exports = Factorial }, function(module, exports) { var SnapCeil = function(value, gap, start, divide) { if (start === undefined) { start = 0 } if (gap === 0) { return value } value -= start; value = gap * Math.ceil(value / gap); return divide ? (start + value) / gap : start + value }; module.exports = SnapCeil }, function(module, exports) { var RandomXYZ = function(vec3, radius) { if (radius === undefined) { radius = 1 } var r = Math.random() * 2 * Math.PI; var z = Math.random() * 2 - 1; var zScale = Math.sqrt(1 - z * z) * radius; vec3.x = Math.cos(r) * zScale; vec3.y = Math.sin(r) * zScale; vec3.z = z * radius; return vec3 }; module.exports = RandomXYZ }, function(module, exports) { var RandomXYZW = function(vec4, scale) { if (scale === undefined) { scale = 1 } vec4.x = (Math.random() * 2 - 1) * scale; vec4.y = (Math.random() * 2 - 1) * scale; vec4.z = (Math.random() * 2 - 1) * scale; vec4.w = (Math.random() * 2 - 1) * scale; return vec4 }; module.exports = RandomXYZW }, function(module, exports) { var Rotate = function(point, angle) { var x = point.x; var y = point.y; point.x = x * Math.cos(angle) - y * Math.sin(angle); point.y = x * Math.sin(angle) + y * Math.cos(angle); return point }; module.exports = Rotate }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Matrix3 = new Class({ initialize: function Matrix3(m) { this.val = new Float32Array(9); if (m) { this.copy(m) } else { this.identity() } }, clone: function() { return new Matrix3(this) }, set: function(src) { return this.copy(src) }, copy: function(src) { var out = this.val; var a = src.val; out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; out[3] = a[3]; out[4] = a[4]; out[5] = a[5]; out[6] = a[6]; out[7] = a[7]; out[8] = a[8]; return this }, fromMat4: function(m) { var a = m.val; var out = this.val; out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; out[3] = a[4]; out[4] = a[5]; out[5] = a[6]; out[6] = a[8]; out[7] = a[9]; out[8] = a[10]; return this }, fromArray: function(a) { var out = this.val; out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; out[3] = a[3]; out[4] = a[4]; out[5] = a[5]; out[6] = a[6]; out[7] = a[7]; out[8] = a[8]; return this }, identity: function() { var out = this.val; out[0] = 1; out[1] = 0; out[2] = 0; out[3] = 0; out[4] = 1; out[5] = 0; out[6] = 0; out[7] = 0; out[8] = 1; return this }, transpose: function() { var a = this.val; var a01 = a[1]; var a02 = a[2]; var a12 = a[5]; a[1] = a[3]; a[2] = a[6]; a[3] = a01; a[5] = a[7]; a[6] = a02; a[7] = a12; return this }, invert: function() { var a = this.val; var a00 = a[0]; var a01 = a[1]; var a02 = a[2]; var a10 = a[3]; var a11 = a[4]; var a12 = a[5]; var a20 = a[6]; var a21 = a[7]; var a22 = a[8]; var b01 = a22 * a11 - a12 * a21; var b11 = -a22 * a10 + a12 * a20; var b21 = a21 * a10 - a11 * a20; var det = a00 * b01 + a01 * b11 + a02 * b21; if (!det) { return null } det = 1 / det; a[0] = b01 * det; a[1] = (-a22 * a01 + a02 * a21) * det; a[2] = (a12 * a01 - a02 * a11) * det; a[3] = b11 * det; a[4] = (a22 * a00 - a02 * a20) * det; a[5] = (-a12 * a00 + a02 * a10) * det; a[6] = b21 * det; a[7] = (-a21 * a00 + a01 * a20) * det; a[8] = (a11 * a00 - a01 * a10) * det; return this }, adjoint: function() { var a = this.val; var a00 = a[0]; var a01 = a[1]; var a02 = a[2]; var a10 = a[3]; var a11 = a[4]; var a12 = a[5]; var a20 = a[6]; var a21 = a[7]; var a22 = a[8]; a[0] = a11 * a22 - a12 * a21; a[1] = a02 * a21 - a01 * a22; a[2] = a01 * a12 - a02 * a11; a[3] = a12 * a20 - a10 * a22; a[4] = a00 * a22 - a02 * a20; a[5] = a02 * a10 - a00 * a12; a[6] = a10 * a21 - a11 * a20; a[7] = a01 * a20 - a00 * a21; a[8] = a00 * a11 - a01 * a10; return this }, determinant: function() { var a = this.val; var a00 = a[0]; var a01 = a[1]; var a02 = a[2]; var a10 = a[3]; var a11 = a[4]; var a12 = a[5]; var a20 = a[6]; var a21 = a[7]; var a22 = a[8]; return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20) }, multiply: function(src) { var a = this.val; var a00 = a[0]; var a01 = a[1]; var a02 = a[2]; var a10 = a[3]; var a11 = a[4]; var a12 = a[5]; var a20 = a[6]; var a21 = a[7]; var a22 = a[8]; var b = src.val; var b00 = b[0]; var b01 = b[1]; var b02 = b[2]; var b10 = b[3]; var b11 = b[4]; var b12 = b[5]; var b20 = b[6]; var b21 = b[7]; var b22 = b[8]; a[0] = b00 * a00 + b01 * a10 + b02 * a20; a[1] = b00 * a01 + b01 * a11 + b02 * a21; a[2] = b00 * a02 + b01 * a12 + b02 * a22; a[3] = b10 * a00 + b11 * a10 + b12 * a20; a[4] = b10 * a01 + b11 * a11 + b12 * a21; a[5] = b10 * a02 + b11 * a12 + b12 * a22; a[6] = b20 * a00 + b21 * a10 + b22 * a20; a[7] = b20 * a01 + b21 * a11 + b22 * a21; a[8] = b20 * a02 + b21 * a12 + b22 * a22; return this }, translate: function(v) { var a = this.val; var x = v.x; var y = v.y; a[6] = x * a[0] + y * a[3] + a[6]; a[7] = x * a[1] + y * a[4] + a[7]; a[8] = x * a[2] + y * a[5] + a[8]; return this }, rotate: function(rad) { var a = this.val; var a00 = a[0]; var a01 = a[1]; var a02 = a[2]; var a10 = a[3]; var a11 = a[4]; var a12 = a[5]; var s = Math.sin(rad); var c = Math.cos(rad); a[0] = c * a00 + s * a10; a[1] = c * a01 + s * a11; a[2] = c * a02 + s * a12; a[3] = c * a10 - s * a00; a[4] = c * a11 - s * a01; a[5] = c * a12 - s * a02; return this }, scale: function(v) { var a = this.val; var x = v.x; var y = v.y; a[0] = x * a[0]; a[1] = x * a[1]; a[2] = x * a[2]; a[3] = y * a[3]; a[4] = y * a[4]; a[5] = y * a[5]; return this }, fromQuat: function(q) { var x = q.x; var y = q.y; var z = q.z; var 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 out = this.val; out[0] = 1 - (yy + zz); out[3] = xy + wz; out[6] = xz - wy; out[1] = xy - wz; out[4] = 1 - (xx + zz); out[7] = yz + wx; out[2] = xz + wy; out[5] = yz - wx; out[8] = 1 - (xx + yy); return this }, normalFromMat4: function(m) { var a = m.val; var out = this.val; var a00 = a[0]; var a01 = a[1]; var a02 = a[2]; var a03 = a[3]; var a10 = a[4]; var a11 = a[5]; var a12 = a[6]; var a13 = a[7]; var a20 = a[8]; var a21 = a[9]; var a22 = a[10]; var a23 = a[11]; var a30 = a[12]; var a31 = a[13]; var a32 = a[14]; var a33 = a[15]; var b00 = a00 * a11 - a01 * a10; var b01 = a00 * a12 - a02 * a10; var b02 = a00 * a13 - a03 * a10; var b03 = a01 * a12 - a02 * a11; var b04 = a01 * a13 - a03 * a11; var b05 = a02 * a13 - a03 * a12; var b06 = a20 * a31 - a21 * a30; var b07 = a20 * a32 - a22 * a30; var b08 = a20 * a33 - a23 * a30; var b09 = a21 * a32 - a22 * a31; var b10 = a21 * a33 - a23 * a31; var b11 = a22 * a33 - a23 * a32; var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; if (!det) { return null } det = 1 / det; out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; out[1] = (a12 * b08 - a10 * b11 - a13 * b07) * det; out[2] = (a10 * b10 - a11 * b08 + a13 * b06) * det; out[3] = (a02 * b10 - a01 * b11 - a03 * b09) * det; out[4] = (a00 * b11 - a02 * b08 + a03 * b07) * det; out[5] = (a01 * b08 - a00 * b10 - a03 * b06) * det; out[6] = (a31 * b05 - a32 * b04 + a33 * b03) * det; out[7] = (a32 * b02 - a30 * b05 - a33 * b01) * det; out[8] = (a30 * b04 - a31 * b02 + a33 * b00) * det; return this } }); module.exports = Matrix3 }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Vector3 = __webpack_require__(86); var Matrix3 = __webpack_require__(412); var EPSILON = 1e-6; var siNext = new Int8Array([1, 2, 0]); var tmp = new Float32Array([0, 0, 0]); var xUnitVec3 = new Vector3(1, 0, 0); var yUnitVec3 = new Vector3(0, 1, 0); var tmpvec = new Vector3; var tmpMat3 = new Matrix3; var Quaternion = new Class({ initialize: function Quaternion(x, y, z, w) { if (typeof x === "object") { this.x = x.x || 0; this.y = x.y || 0; this.z = x.z || 0; this.w = x.w || 0 } else { this.x = x || 0; this.y = y || 0; this.z = z || 0; this.w = w || 0 } }, copy: function(src) { this.x = src.x; this.y = src.y; this.z = src.z; this.w = src.w; return this }, set: function(x, y, z, w) { if (typeof x === "object") { this.x = x.x || 0; this.y = x.y || 0; this.z = x.z || 0; this.w = x.w || 0 } else { this.x = x || 0; this.y = y || 0; this.z = z || 0; this.w = w || 0 } return this }, add: function(v) { this.x += v.x; this.y += v.y; this.z += v.z; this.w += v.w; return this }, subtract: function(v) { this.x -= v.x; this.y -= v.y; this.z -= v.z; this.w -= v.w; return this }, scale: function(scale) { this.x *= scale; this.y *= scale; this.z *= scale; this.w *= scale; return this }, length: function() { var x = this.x; var y = this.y; var z = this.z; var w = this.w; return Math.sqrt(x * x + y * y + z * z + w * w) }, lengthSq: function() { var x = this.x; var y = this.y; var z = this.z; var w = this.w; return x * x + y * y + z * z + w * w }, normalize: function() { var x = this.x; var y = this.y; var z = this.z; var w = this.w; var len = x * x + y * y + z * z + w * w; if (len > 0) { len = 1 / Math.sqrt(len); this.x = x * len; this.y = y * len; this.z = z * len; this.w = w * len } return this }, dot: function(v) { return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w }, lerp: function(v, t) { if (t === undefined) { t = 0 } var ax = this.x; var ay = this.y; var az = this.z; var aw = this.w; this.x = ax + t * (v.x - ax); this.y = ay + t * (v.y - ay); this.z = az + t * (v.z - az); this.w = aw + t * (v.w - aw); return this }, rotationTo: function(a, b) { var dot = a.x * b.x + a.y * b.y + a.z * b.z; if (dot < -.999999) { if (tmpvec.copy(xUnitVec3).cross(a).length() < EPSILON) { tmpvec.copy(yUnitVec3).cross(a) } tmpvec.normalize(); return this.setAxisAngle(tmpvec, Math.PI) } else if (dot > .999999) { this.x = 0; this.y = 0; this.z = 0; this.w = 1; return this } else { tmpvec.copy(a).cross(b); this.x = tmpvec.x; this.y = tmpvec.y; this.z = tmpvec.z; this.w = 1 + dot; return this.normalize() } }, setAxes: function(view, right, up) { var m = tmpMat3.val; m[0] = right.x; m[3] = right.y; m[6] = right.z; m[1] = up.x; m[4] = up.y; m[7] = up.z; m[2] = -view.x; m[5] = -view.y; m[8] = -view.z; return this.fromMat3(tmpMat3).normalize() }, identity: function() { this.x = 0; this.y = 0; this.z = 0; this.w = 1; return this }, setAxisAngle: function(axis, rad) { rad = rad * .5; var s = Math.sin(rad); this.x = s * axis.x; this.y = s * axis.y; this.z = s * axis.z; this.w = Math.cos(rad); return this }, multiply: function(b) { var ax = this.x; var ay = this.y; var az = this.z; var aw = this.w; var bx = b.x; var by = b.y; var bz = b.z; var bw = b.w; this.x = ax * bw + aw * bx + ay * bz - az * by; this.y = ay * bw + aw * by + az * bx - ax * bz; this.z = az * bw + aw * bz + ax * by - ay * bx; this.w = aw * bw - ax * bx - ay * by - az * bz; return this }, slerp: function(b, t) { var ax = this.x; var ay = this.y; var az = this.z; var aw = this.w; var bx = b.x; var by = b.y; var bz = b.z; var bw = b.w; var cosom = ax * bx + ay * by + az * bz + aw * bw; if (cosom < 0) { cosom = -cosom; bx = -bx; by = -by; bz = -bz; bw = -bw } var scale0 = 1 - t; var scale1 = t; if (1 - cosom > EPSILON) { var omega = Math.acos(cosom); var sinom = Math.sin(omega); scale0 = Math.sin((1 - t) * omega) / sinom; scale1 = Math.sin(t * omega) / sinom } this.x = scale0 * ax + scale1 * bx; this.y = scale0 * ay + scale1 * by; this.z = scale0 * az + scale1 * bz; this.w = scale0 * aw + scale1 * bw; return this }, invert: function() { var a0 = this.x; var a1 = this.y; var a2 = this.z; var a3 = this.w; var dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3; var invDot = dot ? 1 / dot : 0; this.x = -a0 * invDot; this.y = -a1 * invDot; this.z = -a2 * invDot; this.w = a3 * invDot; return this }, conjugate: function() { this.x = -this.x; this.y = -this.y; this.z = -this.z; return this }, rotateX: function(rad) { rad *= .5; var ax = this.x; var ay = this.y; var az = this.z; var aw = this.w; var bx = Math.sin(rad); var bw = Math.cos(rad); this.x = ax * bw + aw * bx; this.y = ay * bw + az * bx; this.z = az * bw - ay * bx; this.w = aw * bw - ax * bx; return this }, rotateY: function(rad) { rad *= .5; var ax = this.x; var ay = this.y; var az = this.z; var aw = this.w; var by = Math.sin(rad); var bw = Math.cos(rad); this.x = ax * bw - az * by; this.y = ay * bw + aw * by; this.z = az * bw + ax * by; this.w = aw * bw - ay * by; return this }, rotateZ: function(rad) { rad *= .5; var ax = this.x; var ay = this.y; var az = this.z; var aw = this.w; var bz = Math.sin(rad); var bw = Math.cos(rad); this.x = ax * bw + ay * bz; this.y = ay * bw - ax * bz; this.z = az * bw + aw * bz; this.w = aw * bw - az * bz; return this }, calculateW: function() { var x = this.x; var y = this.y; var z = this.z; this.w = -Math.sqrt(1 - x * x - y * y - z * z); return this }, fromMat3: function(mat) { var m = mat.val; var fTrace = m[0] + m[4] + m[8]; var fRoot; if (fTrace > 0) { fRoot = Math.sqrt(fTrace + 1); this.w = .5 * fRoot; fRoot = .5 / fRoot; this.x = (m[7] - m[5]) * fRoot; this.y = (m[2] - m[6]) * fRoot; this.z = (m[3] - m[1]) * fRoot } else { var i = 0; if (m[4] > m[0]) { i = 1 } if (m[8] > m[i * 3 + i]) { i = 2 } var j = siNext[i]; var k = siNext[j]; fRoot = Math.sqrt(m[i * 3 + i] - m[j * 3 + j] - m[k * 3 + k] + 1); tmp[i] = .5 * fRoot; fRoot = .5 / fRoot; tmp[j] = (m[j * 3 + i] + m[i * 3 + j]) * fRoot; tmp[k] = (m[k * 3 + i] + m[i * 3 + k]) * fRoot; this.x = tmp[0]; this.y = tmp[1]; this.z = tmp[2]; this.w = (m[k * 3 + j] - m[j * 3 + k]) * fRoot } return this } }); module.exports = Quaternion }, function(module, exports, __webpack_require__) { var Vector3 = __webpack_require__(86); var Matrix4 = __webpack_require__(202); var Quaternion = __webpack_require__(413); var tmpMat4 = new Matrix4; var tmpQuat = new Quaternion; var tmpVec3 = new Vector3; var RotateVec3 = function(vec, axis, radians) { tmpQuat.setAxisAngle(axis, radians); tmpMat4.fromRotationTranslation(tmpQuat, tmpVec3.set(0, 0, 0)); return vec.transformMat4(tmpMat4) }; module.exports = RotateVec3 }, function(module, exports, __webpack_require__) { var ArcadeImage = __webpack_require__(416); var ArcadeSprite = __webpack_require__(130); var Class = __webpack_require__(0); var CONST = __webpack_require__(52); var PhysicsGroup = __webpack_require__(418); var StaticPhysicsGroup = __webpack_require__(419); var Factory = new Class({ initialize: function Factory(world) { this.world = world; this.scene = world.scene; this.sys = world.scene.sys }, collider: function(object1, object2, collideCallback, processCallback, callbackContext) { return this.world.addCollider(object1, object2, collideCallback, processCallback, callbackContext) }, overlap: function(object1, object2, collideCallback, processCallback, callbackContext) { return this.world.addOverlap(object1, object2, collideCallback, processCallback, callbackContext) }, existing: function(gameObject, isStatic) { var type = isStatic ? CONST.STATIC_BODY : CONST.DYNAMIC_BODY; this.world.enableBody(gameObject, type); return gameObject }, staticImage: function(x, y, key, frame) { var image = new ArcadeImage(this.scene, x, y, key, frame); this.sys.displayList.add(image); this.world.enableBody(image, CONST.STATIC_BODY); return image }, image: function(x, y, key, frame) { var image = new ArcadeImage(this.scene, x, y, key, frame); this.sys.displayList.add(image); this.world.enableBody(image, CONST.DYNAMIC_BODY); return image }, staticSprite: function(x, y, key, frame) { var sprite = new ArcadeSprite(this.scene, x, y, key, frame); this.sys.displayList.add(sprite); this.sys.updateList.add(sprite); this.world.enableBody(sprite, CONST.STATIC_BODY); return sprite }, sprite: function(x, y, key, frame) { var sprite = new ArcadeSprite(this.scene, x, y, key, frame); this.sys.displayList.add(sprite); this.sys.updateList.add(sprite); this.world.enableBody(sprite, CONST.DYNAMIC_BODY); return sprite }, staticGroup: function(children, config) { return this.sys.updateList.add(new StaticPhysicsGroup(this.world, this.world.scene, children, config)) }, group: function(children, config) { return this.sys.updateList.add(new PhysicsGroup(this.world, this.world.scene, children, config)) }, destroy: function() { this.world = null; this.scene = null; this.sys = null } }); module.exports = Factory }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Components = __webpack_require__(417); var Image = __webpack_require__(82); var ArcadeImage = new Class({ Extends: Image, Mixins: [Components.Acceleration, Components.Angular, Components.Bounce, Components.Debug, Components.Drag, Components.Enable, Components.Friction, Components.Gravity, Components.Immovable, Components.Mass, Components.Size, Components.Velocity], initialize: function ArcadeImage(scene, x, y, texture, frame) { Image.call(this, scene, x, y, texture, frame); this.body = null } }); module.exports = ArcadeImage }, function(module, exports, __webpack_require__) { module.exports = { Acceleration: __webpack_require__(1014), Angular: __webpack_require__(1015), Bounce: __webpack_require__(1016), Debug: __webpack_require__(1017), Drag: __webpack_require__(1018), Enable: __webpack_require__(1019), Friction: __webpack_require__(1020), Gravity: __webpack_require__(1021), Immovable: __webpack_require__(1022), Mass: __webpack_require__(1023), Size: __webpack_require__(1024), Velocity: __webpack_require__(1025) } }, function(module, exports, __webpack_require__) { var ArcadeSprite = __webpack_require__(130); var Class = __webpack_require__(0); var CONST = __webpack_require__(52); var GetFastValue = __webpack_require__(1); var Group = __webpack_require__(96); var IsPlainObject = __webpack_require__(7); var PhysicsGroup = new Class({ Extends: Group, initialize: function PhysicsGroup(world, scene, children, config) { if (!children && !config) { config = { createCallback: this.createCallbackHandler, removeCallback: this.removeCallbackHandler } } else if (IsPlainObject(children)) { config = children; children = null; config.createCallback = this.createCallbackHandler; config.removeCallback = this.removeCallbackHandler } else if (Array.isArray(children) && IsPlainObject(children[0])) { config = children; children = null; config.forEach(function(singleConfig) { singleConfig.createCallback = this.createCallbackHandler; singleConfig.removeCallback = this.removeCallbackHandler }) } this.world = world; config.classType = GetFastValue(config, "classType", ArcadeSprite); this.physicsType = CONST.DYNAMIC_BODY; this.defaults = { setCollideWorldBounds: GetFastValue(config, "collideWorldBounds", false), setAccelerationX: GetFastValue(config, "accelerationX", 0), setAccelerationY: GetFastValue(config, "accelerationY", 0), setAllowDrag: GetFastValue(config, "allowDrag", true), setAllowGravity: GetFastValue(config, "allowGravity", true), setAllowRotation: GetFastValue(config, "allowRotation", true), setBounceX: GetFastValue(config, "bounceX", 0), setBounceY: GetFastValue(config, "bounceY", 0), setDragX: GetFastValue(config, "dragX", 0), setDragY: GetFastValue(config, "dragY", 0), setEnable: GetFastValue(config, "enable", true), setGravityX: GetFastValue(config, "gravityX", 0), setGravityY: GetFastValue(config, "gravityY", 0), setFrictionX: GetFastValue(config, "frictionX", 0), setFrictionY: GetFastValue(config, "frictionY", 0), setVelocityX: GetFastValue(config, "velocityX", 0), setVelocityY: GetFastValue(config, "velocityY", 0), setAngularVelocity: GetFastValue(config, "angularVelocity", 0), setAngularAcceleration: GetFastValue(config, "angularAcceleration", 0), setAngularDrag: GetFastValue(config, "angularDrag", 0), setMass: GetFastValue(config, "mass", 1), setImmovable: GetFastValue(config, "immovable", false) }; Group.call(this, scene, children, config) }, createCallbackHandler: function(child) { if (!child.body) { this.world.enableBody(child, CONST.DYNAMIC_BODY) } var body = child.body; for (var key in this.defaults) { body[key](this.defaults[key]) } }, removeCallbackHandler: function(child) { if (child.body) { this.world.disableBody(child) } }, setVelocity: function(x, y, step) { if (step === undefined) { step = 0 } var items = this.getChildren(); for (var i = 0; i < items.length; i++) { items[i].body.velocity.set(x + i * step, y + i * step) } return this }, setVelocityX: function(value, step) { if (step === undefined) { step = 0 } var items = this.getChildren(); for (var i = 0; i < items.length; i++) { items[i].body.velocity.x = value + i * step } return this }, setVelocityY: function(value, step) { if (step === undefined) { step = 0 } var items = this.getChildren(); for (var i = 0; i < items.length; i++) { items[i].body.velocity.y = value + i * step } return this } }); module.exports = PhysicsGroup }, function(module, exports, __webpack_require__) { var ArcadeSprite = __webpack_require__(130); var Class = __webpack_require__(0); var CONST = __webpack_require__(52); var Group = __webpack_require__(96); var IsPlainObject = __webpack_require__(7); var StaticPhysicsGroup = new Class({ Extends: Group, initialize: function StaticPhysicsGroup(world, scene, children, config) { if (!children && !config) { config = { createCallback: this.createCallbackHandler, removeCallback: this.removeCallbackHandler, createMultipleCallback: this.createMultipleCallbackHandler, classType: ArcadeSprite } } else if (IsPlainObject(children)) { config = children; children = null; config.createCallback = this.createCallbackHandler; config.removeCallback = this.removeCallbackHandler; config.createMultipleCallback = this.createMultipleCallbackHandler; config.classType = ArcadeSprite } else if (Array.isArray(children) && IsPlainObject(children[0])) { config = children; children = null; config.forEach(function(singleConfig) { singleConfig.createCallback = this.createCallbackHandler; singleConfig.removeCallback = this.removeCallbackHandler; singleConfig.createMultipleCallback = this.createMultipleCallbackHandler; singleConfig.classType = ArcadeSprite }) } this.world = world; this.physicsType = CONST.STATIC_BODY; Group.call(this, scene, children, config) }, createCallbackHandler: function(child) { if (!child.body) { this.world.enableBody(child, CONST.STATIC_BODY) } }, removeCallbackHandler: function(child) { if (child.body) { this.world.disableBody(child) } }, createMultipleCallbackHandler: function() { this.refresh() }, refresh: function() { var children = this.children.entries; for (var i = 0; i < children.length; i++) { children[i].body.reset() } return this } }); module.exports = StaticPhysicsGroup }, function(module, exports, __webpack_require__) { var Body = __webpack_require__(421); var Clamp = __webpack_require__(23); var Class = __webpack_require__(0); var Collider = __webpack_require__(422); var CONST = __webpack_require__(52); var DistanceBetween = __webpack_require__(56); var EventEmitter = __webpack_require__(11); var FuzzyEqual = __webpack_require__(403); var FuzzyGreaterThan = __webpack_require__(404); var FuzzyLessThan = __webpack_require__(405); var GetOverlapX = __webpack_require__(423); var GetOverlapY = __webpack_require__(424); var GetValue = __webpack_require__(4); var ProcessQueue = __webpack_require__(425); var ProcessTileCallbacks = __webpack_require__(1026); var Rectangle = __webpack_require__(9); var RTree = __webpack_require__(426); var SeparateTile = __webpack_require__(1027); var SeparateX = __webpack_require__(1032); var SeparateY = __webpack_require__(1033); var Set = __webpack_require__(81); var StaticBody = __webpack_require__(428); var TileIntersectsBody = __webpack_require__(427); var TransformMatrix = __webpack_require__(48); var Vector2 = __webpack_require__(3); var Wrap = __webpack_require__(55); var World = new Class({ Extends: EventEmitter, initialize: function World(scene, config) { EventEmitter.call(this); this.scene = scene; this.bodies = new Set; this.staticBodies = new Set; this.pendingDestroy = new Set; this.colliders = new ProcessQueue; this.gravity = new Vector2(GetValue(config, "gravity.x", 0), GetValue(config, "gravity.y", 0)); this.bounds = new Rectangle(GetValue(config, "x", 0), GetValue(config, "y", 0), GetValue(config, "width", scene.sys.game.config.width), GetValue(config, "height", scene.sys.game.config.height)); this.checkCollision = { up: GetValue(config, "checkCollision.up", true), down: GetValue(config, "checkCollision.down", true), left: GetValue(config, "checkCollision.left", true), right: GetValue(config, "checkCollision.right", true) }; this.fps = GetValue(config, "fps", 60); this._elapsed = 0; this._frameTime = 1 / this.fps; this._frameTimeMS = 1e3 * this._frameTime; this.stepsLastFrame = 0; this.timeScale = GetValue(config, "timeScale", 1); this.OVERLAP_BIAS = GetValue(config, "overlapBias", 4); this.TILE_BIAS = GetValue(config, "tileBias", 16); this.forceX = GetValue(config, "forceX", false); this.isPaused = GetValue(config, "isPaused", false); this._total = 0; this.drawDebug = GetValue(config, "debug", false); this.debugGraphic; this.defaults = { debugShowBody: GetValue(config, "debugShowBody", true), debugShowStaticBody: GetValue(config, "debugShowStaticBody", true), debugShowVelocity: GetValue(config, "debugShowVelocity", true), bodyDebugColor: GetValue(config, "debugBodyColor", 16711935), staticBodyDebugColor: GetValue(config, "debugStaticBodyColor", 255), velocityDebugColor: GetValue(config, "debugVelocityColor", 65280) }; this.maxEntries = GetValue(config, "maxEntries", 16); this.useTree = GetValue(config, "useTree", true); this.tree = new RTree(this.maxEntries); this.staticTree = new RTree(this.maxEntries); this.treeMinMax = { minX: 0, minY: 0, maxX: 0, maxY: 0 }; this._tempMatrix = new TransformMatrix; this._tempMatrix2 = new TransformMatrix; if (this.drawDebug) { this.createDebugGraphic() } }, enable: function(object, bodyType) { if (bodyType === undefined) { bodyType = CONST.DYNAMIC_BODY } if (!Array.isArray(object)) { object = [object] } for (var i = 0; i < object.length; i++) { var entry = object[i]; if (entry.isParent) { var children = entry.getChildren(); for (var c = 0; c < children.length; c++) { var child = children[c]; if (child.isParent) { this.enable(child, bodyType) } else { this.enableBody(child, bodyType) } } } else { this.enableBody(entry, bodyType) } } }, enableBody: function(object, bodyType) { if (bodyType === undefined) { bodyType = CONST.DYNAMIC_BODY } if (!object.body) { if (bodyType === CONST.DYNAMIC_BODY) { object.body = new Body(this, object) } else if (bodyType === CONST.STATIC_BODY) { object.body = new StaticBody(this, object) } } this.add(object.body); return object }, add: function(body) { if (body.physicsType === CONST.DYNAMIC_BODY) { this.bodies.set(body) } else if (body.physicsType === CONST.STATIC_BODY) { this.staticBodies.set(body); this.staticTree.insert(body) } body.enable = true; return body }, disable: function(object) { if (!Array.isArray(object)) { object = [object] } for (var i = 0; i < object.length; i++) { var entry = object[i]; if (entry.isParent) { var children = entry.getChildren(); for (var c = 0; c < children.length; c++) { var child = children[c]; if (child.isParent) { this.disable(child) } else { this.disableBody(child.body) } } } else { this.disableBody(entry.body) } } }, disableBody: function(body) { this.remove(body); body.enable = false }, remove: function(body) { if (body.physicsType === CONST.DYNAMIC_BODY) { this.tree.remove(body); this.bodies.delete(body) } else if (body.physicsType === CONST.STATIC_BODY) { this.staticBodies.delete(body); this.staticTree.remove(body) } }, createDebugGraphic: function() { var graphic = this.scene.sys.add.graphics({ x: 0, y: 0 }); graphic.setDepth(Number.MAX_VALUE); this.debugGraphic = graphic; this.drawDebug = true; return graphic }, setBounds: function(x, y, width, height, checkLeft, checkRight, checkUp, checkDown) { this.bounds.setTo(x, y, width, height); if (checkLeft !== undefined) { this.setBoundsCollision(checkLeft, checkRight, checkUp, checkDown) } return this }, setBoundsCollision: function(left, right, up, down) { if (left === undefined) { left = true } if (right === undefined) { right = true } if (up === undefined) { up = true } if (down === undefined) { down = true } this.checkCollision.left = left; this.checkCollision.right = right; this.checkCollision.up = up; this.checkCollision.down = down; return this }, pause: function() { this.isPaused = true; this.emit("pause"); return this }, resume: function() { this.isPaused = false; this.emit("resume"); return this }, addCollider: function(object1, object2, collideCallback, processCallback, callbackContext) { if (collideCallback === undefined) { collideCallback = null } if (processCallback === undefined) { processCallback = null } if (callbackContext === undefined) { callbackContext = collideCallback } var collider = new Collider(this, false, object1, object2, collideCallback, processCallback, callbackContext); this.colliders.add(collider); return collider }, addOverlap: function(object1, object2, collideCallback, processCallback, callbackContext) { if (collideCallback === undefined) { collideCallback = null } if (processCallback === undefined) { processCallback = null } if (callbackContext === undefined) { callbackContext = collideCallback } var collider = new Collider(this, true, object1, object2, collideCallback, processCallback, callbackContext); this.colliders.add(collider); return collider }, removeCollider: function(collider) { this.colliders.remove(collider); return this }, setFPS: function(framerate) { this.fps = framerate; this._frameTime = 1 / this.fps; this._frameTimeMS = 1e3 * this._frameTime; return this }, update: function(time, delta) { if (this.isPaused || this.bodies.size === 0) { return } var stepsThisFrame = 0; var fixedDelta = this._frameTime; var msPerFrame = this._frameTimeMS * this.timeScale; this._elapsed += delta; while (this._elapsed >= msPerFrame) { this._elapsed -= msPerFrame; stepsThisFrame++; this.step(fixedDelta) } this.stepsLastFrame = stepsThisFrame }, step: function(delta) { var i; var body; var bodies = this.bodies.entries; var len = bodies.length; for (i = 0; i < len; i++) { body = bodies[i]; if (body.enable) { body.update(delta) } } if (this.useTree) { this.tree.clear(); this.tree.load(bodies) } var colliders = this.colliders.update(); for (i = 0; i < colliders.length; i++) { var collider = colliders[i]; if (collider.active) { collider.update() } } len = bodies.length; for (i = 0; i < len; i++) { body = bodies[i]; if (body.enable) { body.postUpdate() } } }, postUpdate: function() { var i; var body; var dynamic = this.bodies; var staticBodies = this.staticBodies; var pending = this.pendingDestroy; var bodies = dynamic.entries; var len = bodies.length; if (this.drawDebug) { var graphics = this.debugGraphic; graphics.clear(); for (i = 0; i < len; i++) { body = bodies[i]; if (body.willDrawDebug()) { body.drawDebug(graphics) } } bodies = staticBodies.entries; len = bodies.length; for (i = 0; i < len; i++) { body = bodies[i]; if (body.willDrawDebug()) { body.drawDebug(graphics) } } } if (pending.size > 0) { var dynamicTree = this.tree; var staticTree = this.staticTree; bodies = pending.entries; len = bodies.length; for (i = 0; i < len; i++) { body = bodies[i]; if (body.physicsType === CONST.DYNAMIC_BODY) { dynamicTree.remove(body); dynamic.delete(body) } else if (body.physicsType === CONST.STATIC_BODY) { staticTree.remove(body); staticBodies.delete(body) } body.world = undefined; body.gameObject = undefined } pending.clear() } }, updateMotion: function(body, delta) { if (body.allowRotation) { this.computeAngularVelocity(body, delta) } this.computeVelocity(body, delta) }, computeAngularVelocity: function(body, delta) { var velocity = body.angularVelocity; var acceleration = body.angularAcceleration; var drag = body.angularDrag; var max = body.maxAngular; if (acceleration) { velocity += acceleration * delta } else if (body.allowDrag && drag) { drag *= delta; if (FuzzyGreaterThan(velocity - drag, 0, .1)) { velocity -= drag } else if (FuzzyLessThan(velocity + drag, 0, .1)) { velocity += drag } else { velocity = 0 } } velocity = Clamp(velocity, -max, max); var velocityDelta = velocity - body.angularVelocity; body.angularVelocity += velocityDelta; body.rotation += body.angularVelocity * delta }, computeVelocity: function(body, delta) { var velocityX = body.velocity.x; var accelerationX = body.acceleration.x; var dragX = body.drag.x; var maxX = body.maxVelocity.x; var velocityY = body.velocity.y; var accelerationY = body.acceleration.y; var dragY = body.drag.y; var maxY = body.maxVelocity.y; var speed = body.speed; var allowDrag = body.allowDrag; var useDamping = body.useDamping; if (body.allowGravity) { velocityX += (this.gravity.x + body.gravity.x) * delta; velocityY += (this.gravity.y + body.gravity.y) * delta } if (accelerationX) { velocityX += accelerationX * delta } else if (allowDrag && dragX) { if (useDamping) { velocityX *= dragX; if (FuzzyEqual(speed, 0, .001)) { velocityX = 0 } } else { dragX *= delta; if (FuzzyGreaterThan(velocityX - dragX, 0, .01)) { velocityX -= dragX } else if (FuzzyLessThan(velocityX + dragX, 0, .01)) { velocityX += dragX } else { velocityX = 0 } } } if (accelerationY) { velocityY += accelerationY * delta } else if (allowDrag && dragY) { if (useDamping) { velocityY *= dragY; if (FuzzyEqual(speed, 0, .001)) { velocityY = 0 } } else { dragY *= delta; if (FuzzyGreaterThan(velocityY - dragY, 0, .01)) { velocityY -= dragY } else if (FuzzyLessThan(velocityY + dragY, 0, .01)) { velocityY += dragY } else { velocityY = 0 } } } velocityX = Clamp(velocityX, -maxX, maxX); velocityY = Clamp(velocityY, -maxY, maxY); body.velocity.set(velocityX, velocityY) }, separate: function(body1, body2, processCallback, callbackContext, overlapOnly) { if (!body1.enable || !body2.enable || body1.checkCollision.none || body2.checkCollision.none || !this.intersects(body1, body2)) { return false } if (processCallback && processCallback.call(callbackContext, body1.gameObject, body2.gameObject) === false) { return false } if (body1.isCircle && body2.isCircle) { return this.separateCircle(body1, body2, overlapOnly) } if (body1.isCircle !== body2.isCircle) { var bodyRect = body1.isCircle ? body2 : body1; var bodyCircle = body1.isCircle ? body1 : body2; var rect = { x: bodyRect.x, y: bodyRect.y, right: bodyRect.right, bottom: bodyRect.bottom }; var circle = bodyCircle.center; if (circle.y < rect.y || circle.y > rect.bottom) { if (circle.x < rect.x || circle.x > rect.right) { return this.separateCircle(body1, body2, overlapOnly) } } } var resultX = false; var resultY = false; if (this.forceX || Math.abs(this.gravity.y + body1.gravity.y) < Math.abs(this.gravity.x + body1.gravity.x)) { resultX = SeparateX(body1, body2, overlapOnly, this.OVERLAP_BIAS); if (this.intersects(body1, body2)) { resultY = SeparateY(body1, body2, overlapOnly, this.OVERLAP_BIAS) } } else { resultY = SeparateY(body1, body2, overlapOnly, this.OVERLAP_BIAS); if (this.intersects(body1, body2)) { resultX = SeparateX(body1, body2, overlapOnly, this.OVERLAP_BIAS) } } var result = resultX || resultY; if (result) { if (overlapOnly && (body1.onOverlap || body2.onOverlap)) { this.emit("overlap", body1.gameObject, body2.gameObject, body1, body2) } else { body1.postUpdate(); body2.postUpdate(); if (body1.onCollide || body2.onCollide) { this.emit("collide", body1.gameObject, body2.gameObject, body1, body2) } } } return result }, separateCircle: function(body1, body2, overlapOnly, bias) { GetOverlapX(body1, body2, false, bias); GetOverlapY(body1, body2, false, bias); var dx = body2.center.x - body1.center.x; var dy = body2.center.y - body1.center.y; var angleCollision = Math.atan2(dy, dx); var overlap = 0; if (body1.isCircle !== body2.isCircle) { var rect = { x: body2.isCircle ? body1.position.x : body2.position.x, y: body2.isCircle ? body1.position.y : body2.position.y, right: body2.isCircle ? body1.right : body2.right, bottom: body2.isCircle ? body1.bottom : body2.bottom }; var circle = { x: body1.isCircle ? body1.center.x : body2.center.x, y: body1.isCircle ? body1.center.y : body2.center.y, radius: body1.isCircle ? body1.halfWidth : body2.halfWidth }; if (circle.y < rect.y) { if (circle.x < rect.x) { overlap = DistanceBetween(circle.x, circle.y, rect.x, rect.y) - circle.radius } else if (circle.x > rect.right) { overlap = DistanceBetween(circle.x, circle.y, rect.right, rect.y) - circle.radius } } else if (circle.y > rect.bottom) { if (circle.x < rect.x) { overlap = DistanceBetween(circle.x, circle.y, rect.x, rect.bottom) - circle.radius } else if (circle.x > rect.right) { overlap = DistanceBetween(circle.x, circle.y, rect.right, rect.bottom) - circle.radius } } overlap *= -1 } else { overlap = body1.halfWidth + body2.halfWidth - DistanceBetween(body1.center.x, body1.center.y, body2.center.x, body2.center.y) } if (overlapOnly || overlap === 0 || body1.immovable && body2.immovable || body1.customSeparateX || body2.customSeparateX) { if (overlap !== 0 && (body1.onOverlap || body2.onOverlap)) { this.emit("overlap", body1.gameObject, body2.gameObject, body1, body2) } return overlap !== 0 } var b1vx = body1.velocity.x; var b1vy = body1.velocity.y; var b1mass = body1.mass; var b2vx = body2.velocity.x; var b2vy = body2.velocity.y; var b2mass = body2.mass; var v1 = { x: b1vx * Math.cos(angleCollision) + b1vy * Math.sin(angleCollision), y: b1vx * Math.sin(angleCollision) - b1vy * Math.cos(angleCollision) }; var v2 = { x: b2vx * Math.cos(angleCollision) + b2vy * Math.sin(angleCollision), y: b2vx * Math.sin(angleCollision) - b2vy * Math.cos(angleCollision) }; var tempVel1 = ((b1mass - b2mass) * v1.x + 2 * b2mass * v2.x) / (b1mass + b2mass); var tempVel2 = (2 * b1mass * v1.x + (b2mass - b1mass) * v2.x) / (b1mass + b2mass); if (!body1.immovable) { body1.velocity.x = (tempVel1 * Math.cos(angleCollision) - v1.y * Math.sin(angleCollision)) * body1.bounce.x; body1.velocity.y = (v1.y * Math.cos(angleCollision) + tempVel1 * Math.sin(angleCollision)) * body1.bounce.y; b1vx = body1.velocity.x; b1vy = body1.velocity.y } if (!body2.immovable) { body2.velocity.x = (tempVel2 * Math.cos(angleCollision) - v2.y * Math.sin(angleCollision)) * body2.bounce.x; body2.velocity.y = (v2.y * Math.cos(angleCollision) + tempVel2 * Math.sin(angleCollision)) * body2.bounce.y; b2vx = body2.velocity.x; b2vy = body2.velocity.y } if (Math.abs(angleCollision) < Math.PI / 2) { if (b1vx > 0 && !body1.immovable && b2vx > b1vx) { body1.velocity.x *= -1 } else if (b2vx < 0 && !body2.immovable && b1vx < b2vx) { body2.velocity.x *= -1 } else if (b1vy > 0 && !body1.immovable && b2vy > b1vy) { body1.velocity.y *= -1 } else if (b2vy < 0 && !body2.immovable && b1vy < b2vy) { body2.velocity.y *= -1 } } else if (Math.abs(angleCollision) > Math.PI / 2) { if (b1vx < 0 && !body1.immovable && b2vx < b1vx) { body1.velocity.x *= -1 } else if (b2vx > 0 && !body2.immovable && b1vx > b2vx) { body2.velocity.x *= -1 } else if (b1vy < 0 && !body1.immovable && b2vy < b1vy) { body1.velocity.y *= -1 } else if (b2vy > 0 && !body2.immovable && b1vx > b2vy) { body2.velocity.y *= -1 } } var delta = this._frameTime; if (!body1.immovable) { body1.x += body1.velocity.x * delta - overlap * Math.cos(angleCollision); body1.y += body1.velocity.y * delta - overlap * Math.sin(angleCollision) } if (!body2.immovable) { body2.x += body2.velocity.x * delta + overlap * Math.cos(angleCollision); body2.y += body2.velocity.y * delta + overlap * Math.sin(angleCollision) } if (body1.onCollide || body2.onCollide) { this.emit("collide", body1.gameObject, body2.gameObject, body1, body2) } body1.postUpdate(); body2.postUpdate(); return true }, intersects: function(body1, body2) { if (body1 === body2) { return false } if (!body1.isCircle && !body2.isCircle) { return !(body1.right <= body2.position.x || body1.bottom <= body2.position.y || body1.position.x >= body2.right || body1.position.y >= body2.bottom) } else if (body1.isCircle) { if (body2.isCircle) { return DistanceBetween(body1.center.x, body1.center.y, body2.center.x, body2.center.y) <= body1.halfWidth + body2.halfWidth } else { return this.circleBodyIntersects(body1, body2) } } else { return this.circleBodyIntersects(body2, body1) } }, circleBodyIntersects: function(circle, body) { var x = Clamp(circle.center.x, body.left, body.right); var y = Clamp(circle.center.y, body.top, body.bottom); var dx = (circle.center.x - x) * (circle.center.x - x); var dy = (circle.center.y - y) * (circle.center.y - y); return dx + dy <= circle.halfWidth * circle.halfWidth }, overlap: function(object1, object2, overlapCallback, processCallback, callbackContext) { if (overlapCallback === undefined) { overlapCallback = null } if (processCallback === undefined) { processCallback = null } if (callbackContext === undefined) { callbackContext = overlapCallback } return this.collideObjects(object1, object2, overlapCallback, processCallback, callbackContext, true) }, collide: function(object1, object2, collideCallback, processCallback, callbackContext) { if (collideCallback === undefined) { collideCallback = null } if (processCallback === undefined) { processCallback = null } if (callbackContext === undefined) { callbackContext = collideCallback } return this.collideObjects(object1, object2, collideCallback, processCallback, callbackContext, false) }, collideObjects: function(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly) { var i; if (object1.isParent && object1.physicsType === undefined) { object1 = object1.children.entries } if (object2 && object2.isParent && object2.physicsType === undefined) { object2 = object2.children.entries } var object1isArray = Array.isArray(object1); var object2isArray = Array.isArray(object2); this._total = 0; if (!object1isArray && !object2isArray) { this.collideHandler(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly) } else if (!object1isArray && object2isArray) { for (i = 0; i < object2.length; i++) { this.collideHandler(object1, object2[i], collideCallback, processCallback, callbackContext, overlapOnly) } } else if (object1isArray && !object2isArray) { for (i = 0; i < object1.length; i++) { this.collideHandler(object1[i], object2, collideCallback, processCallback, callbackContext, overlapOnly) } } else { for (i = 0; i < object1.length; i++) { for (var j = 0; j < object2.length; j++) { this.collideHandler(object1[i], object2[j], collideCallback, processCallback, callbackContext, overlapOnly) } } } return this._total > 0 }, collideHandler: function(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly) { if (object2 === undefined && object1.isParent) { return this.collideGroupVsGroup(object1, object1, collideCallback, processCallback, callbackContext, overlapOnly) } if (!object1 || !object2) { return false } if (object1.body) { if (object2.body) { return this.collideSpriteVsSprite(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly) } else if (object2.isParent) { return this.collideSpriteVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly) } else if (object2.isTilemap) { return this.collideSpriteVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly) } } else if (object1.isParent) { if (object2.body) { return this.collideSpriteVsGroup(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly) } else if (object2.isParent) { return this.collideGroupVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly) } else if (object2.isTilemap) { return this.collideGroupVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly) } } else if (object1.isTilemap) { if (object2.body) { return this.collideSpriteVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly) } else if (object2.isParent) { return this.collideGroupVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly) } } }, collideSpriteVsSprite: function(sprite1, sprite2, collideCallback, processCallback, callbackContext, overlapOnly) { if (!sprite1.body || !sprite2.body) { return false } if (this.separate(sprite1.body, sprite2.body, processCallback, callbackContext, overlapOnly)) { if (collideCallback) { collideCallback.call(callbackContext, sprite1, sprite2) } this._total++ } return true }, collideSpriteVsGroup: function(sprite, group, collideCallback, processCallback, callbackContext, overlapOnly) { var bodyA = sprite.body; if (group.length === 0 || !bodyA || !bodyA.enable) { return } var i; var len; var bodyB; if (this.useTree) { var minMax = this.treeMinMax; minMax.minX = bodyA.left; minMax.minY = bodyA.top; minMax.maxX = bodyA.right; minMax.maxY = bodyA.bottom; var results = group.physicsType === CONST.DYNAMIC_BODY ? this.tree.search(minMax) : this.staticTree.search(minMax); len = results.length; for (i = 0; i < len; i++) { bodyB = results[i]; if (bodyA === bodyB || !group.contains(bodyB.gameObject)) { continue } if (this.separate(bodyA, bodyB, processCallback, callbackContext, overlapOnly)) { if (collideCallback) { collideCallback.call(callbackContext, bodyA.gameObject, bodyB.gameObject) } this._total++ } } } else { var children = group.getChildren(); var skipIndex = group.children.entries.indexOf(sprite); len = children.length; for (i = 0; i < len; i++) { bodyB = children[i].body; if (!bodyB || i === skipIndex || !bodyB.enable) { continue } if (this.separate(bodyA, bodyB, processCallback, callbackContext, overlapOnly)) { if (collideCallback) { collideCallback.call(callbackContext, bodyA.gameObject, bodyB.gameObject) } this._total++ } } } }, collideGroupVsTilemapLayer: function(group, tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly) { var children = group.getChildren(); if (children.length === 0) { return false } var didCollide = false; for (var i = 0; i < children.length; i++) { if (children[i].body) { if (this.collideSpriteVsTilemapLayer(children[i], tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly)) { didCollide = true } } } return didCollide }, collideSpriteVsTilemapLayer: function(sprite, tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly) { var body = sprite.body; if (!body.enable) { return false } var x = body.position.x; var y = body.position.y; var w = body.width; var h = body.height; var layerData = tilemapLayer.layer; if (layerData.tileWidth > layerData.baseTileWidth) { var xDiff = (layerData.tileWidth - layerData.baseTileWidth) * tilemapLayer.scaleX; x -= xDiff; w += xDiff } if (layerData.tileHeight > layerData.baseTileHeight) { var yDiff = (layerData.tileHeight - layerData.baseTileHeight) * tilemapLayer.scaleY; h += yDiff } var mapData = tilemapLayer.getTilesWithinWorldXY(x, y, w, h); if (mapData.length === 0) { return false } var tile; var tileWorldRect = { left: 0, right: 0, top: 0, bottom: 0 }; for (var i = 0; i < mapData.length; i++) { tile = mapData[i]; tileWorldRect.left = tilemapLayer.tileToWorldX(tile.x); tileWorldRect.top = tilemapLayer.tileToWorldY(tile.y); if (tile.baseHeight !== tile.height) { tileWorldRect.top -= (tile.height - tile.baseHeight) * tilemapLayer.scaleY } tileWorldRect.right = tileWorldRect.left + tile.width * tilemapLayer.scaleX; tileWorldRect.bottom = tileWorldRect.top + tile.height * tilemapLayer.scaleY; if (TileIntersectsBody(tileWorldRect, body) && (!processCallback || processCallback.call(callbackContext, sprite, tile)) && ProcessTileCallbacks(tile, sprite) && (overlapOnly || SeparateTile(i, body, tile, tileWorldRect, tilemapLayer, this.TILE_BIAS))) { this._total++; if (collideCallback) { collideCallback.call(callbackContext, sprite, tile) } if (overlapOnly && body.onOverlap) { sprite.emit("overlap", body.gameObject, tile, body, null) } else if (body.onCollide) { sprite.emit("collide", body.gameObject, tile, body, null) } body.postUpdate() } } }, collideGroupVsGroup: function(group1, group2, collideCallback, processCallback, callbackContext, overlapOnly) { if (group1.length === 0 || group2.length === 0) { return } var children = group1.getChildren(); for (var i = 0; i < children.length; i++) { this.collideSpriteVsGroup(children[i], group2, collideCallback, processCallback, callbackContext, overlapOnly) } }, wrap: function(object, padding) { if (object.body) { this.wrapObject(object, padding) } else if (object.getChildren) { this.wrapArray(object.getChildren(), padding) } else if (Array.isArray(object)) { this.wrapArray(object, padding) } else { this.wrapObject(object, padding) } }, wrapArray: function(objects, padding) { for (var i = 0; i < objects.length; i++) { this.wrapObject(objects[i], padding) } }, wrapObject: function(object, padding) { if (padding === undefined) { padding = 0 } object.x = Wrap(object.x, this.bounds.left - padding, this.bounds.right + padding); object.y = Wrap(object.y, this.bounds.top - padding, this.bounds.bottom + padding) }, shutdown: function() { this.tree.clear(); this.staticTree.clear(); this.bodies.clear(); this.staticBodies.clear(); this.colliders.destroy(); this.removeAllListeners() }, destroy: function() { this.shutdown(); this.scene = null } }); module.exports = World }, function(module, exports, __webpack_require__) { var CircleContains = __webpack_require__(46); var Class = __webpack_require__(0); var CONST = __webpack_require__(52); var RadToDeg = __webpack_require__(165); var Rectangle = __webpack_require__(9); var RectangleContains = __webpack_require__(47); var Vector2 = __webpack_require__(3); var Body = new Class({ initialize: function Body(world, gameObject) { var width = gameObject.width ? gameObject.width : 64; var height = gameObject.height ? gameObject.height : 64; this.world = world; this.gameObject = gameObject; this.transform = { x: gameObject.x, y: gameObject.y, rotation: gameObject.angle, scaleX: gameObject.scaleX, scaleY: gameObject.scaleY, displayOriginX: gameObject.displayOriginX, displayOriginY: gameObject.displayOriginY }; this.debugShowBody = world.defaults.debugShowBody; this.debugShowVelocity = world.defaults.debugShowVelocity; this.debugBodyColor = world.defaults.bodyDebugColor; this.enable = true; this.isCircle = false; this.radius = 0; this.offset = new Vector2; this.position = new Vector2(gameObject.x, gameObject.y); this.prev = new Vector2(gameObject.x, gameObject.y); this.allowRotation = true; this.rotation = gameObject.angle; this.preRotation = gameObject.angle; this.width = width; this.height = height; this.sourceWidth = width; this.sourceHeight = height; if (gameObject.frame) { this.sourceWidth = gameObject.frame.realWidth; this.sourceHeight = gameObject.frame.realHeight } this.halfWidth = Math.abs(width / 2); this.halfHeight = Math.abs(height / 2); this.center = new Vector2(gameObject.x + this.halfWidth, gameObject.y + this.halfHeight); this.velocity = new Vector2; this.newVelocity = new Vector2; this.deltaMax = new Vector2; this.acceleration = new Vector2; this.allowDrag = true; this.drag = new Vector2; this.allowGravity = true; this.gravity = new Vector2; this.bounce = new Vector2; this.worldBounce = null; this.onWorldBounds = false; this.onCollide = false; this.onOverlap = false; this.maxVelocity = new Vector2(1e4, 1e4); this.friction = new Vector2(1, 0); this.useDamping = false; this.angularVelocity = 0; this.angularAcceleration = 0; this.angularDrag = 0; this.maxAngular = 1e3; this.mass = 1; this.angle = 0; this.speed = 0; this.facing = CONST.FACING_NONE; this.immovable = false; this.moves = true; this.customSeparateX = false; this.customSeparateY = false; this.overlapX = 0; this.overlapY = 0; this.overlapR = 0; this.embedded = false; this.collideWorldBounds = false; this.checkCollision = { none: false, up: true, down: true, left: true, right: true }; this.touching = { none: true, up: false, down: false, left: false, right: false }; this.wasTouching = { none: true, up: false, down: false, left: false, right: false }; this.blocked = { none: true, up: false, down: false, left: false, right: false }; this.syncBounds = false; this.isMoving = false; this.stopVelocityOnCollide = true; this.physicsType = CONST.DYNAMIC_BODY; this._reset = true; this._sx = gameObject.scaleX; this._sy = gameObject.scaleY; this._dx = 0; this._dy = 0; this._bounds = new Rectangle }, updateBounds: function() { var sprite = this.gameObject; var transform = this.transform; if (sprite.parentContainer) { var matrix = sprite.getWorldTransformMatrix(this.world._tempMatrix, this.world._tempMatrix2); transform.x = matrix.tx; transform.y = matrix.ty; transform.rotation = RadToDeg(matrix.rotation); transform.scaleX = matrix.scaleX; transform.scaleY = matrix.scaleY; transform.displayOriginX = sprite.displayOriginX; transform.displayOriginY = sprite.displayOriginY } else { transform.x = sprite.x; transform.y = sprite.y; transform.rotation = sprite.angle; transform.scaleX = sprite.scaleX; transform.scaleY = sprite.scaleY; transform.displayOriginX = sprite.displayOriginX; transform.displayOriginY = sprite.displayOriginY } var recalc = false; if (this.syncBounds) { var b = sprite.getBounds(this._bounds); this.width = b.width; this.height = b.height; recalc = true } else { var asx = Math.abs(transform.scaleX); var asy = Math.abs(transform.scaleY); if (this._sx !== asx || this._sy !== asy) { this.width = this.sourceWidth * asx; this.height = this.sourceHeight * asy; this._sx = asx; this._sy = asy; recalc = true } } if (recalc) { this.halfWidth = Math.floor(this.width / 2); this.halfHeight = Math.floor(this.height / 2); this.updateCenter() } }, updateCenter: function() { this.center.set(this.position.x + this.halfWidth, this.position.y + this.halfHeight) }, update: function(delta) { this.wasTouching.none = this.touching.none; this.wasTouching.up = this.touching.up; this.wasTouching.down = this.touching.down; this.wasTouching.left = this.touching.left; this.wasTouching.right = this.touching.right; this.touching.none = true; this.touching.up = false; this.touching.down = false; this.touching.left = false; this.touching.right = false; this.blocked.none = true; this.blocked.up = false; this.blocked.down = false; this.blocked.left = false; this.blocked.right = false; this.overlapR = 0; this.overlapX = 0; this.overlapY = 0; this.embedded = false; this.updateBounds(); var sprite = this.transform; this.position.x = sprite.x + sprite.scaleX * (this.offset.x - sprite.displayOriginX); this.position.y = sprite.y + sprite.scaleY * (this.offset.y - sprite.displayOriginY); this.updateCenter(); this.rotation = sprite.rotation; this.preRotation = this.rotation; if (this._reset) { this.prev.x = this.position.x; this.prev.y = this.position.y } if (this.moves) { this.world.updateMotion(this, delta); var vx = this.velocity.x; var vy = this.velocity.y; this.newVelocity.set(vx * delta, vy * delta); this.position.add(this.newVelocity); this.updateCenter(); this.angle = Math.atan2(vy, vx); this.speed = Math.sqrt(vx * vx + vy * vy); if (this.collideWorldBounds && this.checkWorldBounds() && this.onWorldBounds) { this.world.emit("worldbounds", this, this.blocked.up, this.blocked.down, this.blocked.left, this.blocked.right) } } this._dx = this.position.x - this.prev.x; this._dy = this.position.y - this.prev.y }, postUpdate: function() { this._dx = this.position.x - this.prev.x; this._dy = this.position.y - this.prev.y; if (this.moves) { if (this.deltaMax.x !== 0 && this._dx !== 0) { if (this._dx < 0 && this._dx < -this.deltaMax.x) { this._dx = -this.deltaMax.x } else if (this._dx > 0 && this._dx > this.deltaMax.x) { this._dx = this.deltaMax.x } } if (this.deltaMax.y !== 0 && this._dy !== 0) { if (this._dy < 0 && this._dy < -this.deltaMax.y) { this._dy = -this.deltaMax.y } else if (this._dy > 0 && this._dy > this.deltaMax.y) { this._dy = this.deltaMax.y } } this.gameObject.x += this._dx; this.gameObject.y += this._dy; this._reset = true } if (this._dx < 0) { this.facing = CONST.FACING_LEFT } else if (this._dx > 0) { this.facing = CONST.FACING_RIGHT } if (this._dy < 0) { this.facing = CONST.FACING_UP } else if (this._dy > 0) { this.facing = CONST.FACING_DOWN } if (this.allowRotation) { this.gameObject.angle += this.deltaZ() } this.prev.x = this.position.x; this.prev.y = this.position.y }, checkWorldBounds: function() { var pos = this.position; var bounds = this.world.bounds; var check = this.world.checkCollision; var bx = this.worldBounce ? -this.worldBounce.x : -this.bounce.x; var by = this.worldBounce ? -this.worldBounce.y : -this.bounce.y; if (pos.x < bounds.x && check.left) { pos.x = bounds.x; this.velocity.x *= bx; this.blocked.left = true; this.blocked.none = false } else if (this.right > bounds.right && check.right) { pos.x = bounds.right - this.width; this.velocity.x *= bx; this.blocked.right = true; this.blocked.none = false } if (pos.y < bounds.y && check.up) { pos.y = bounds.y; this.velocity.y *= by; this.blocked.up = true; this.blocked.none = false } else if (this.bottom > bounds.bottom && check.down) { pos.y = bounds.bottom - this.height; this.velocity.y *= by; this.blocked.down = true; this.blocked.none = false } return !this.blocked.none }, setOffset: function(x, y) { if (y === undefined) { y = x } this.offset.set(x, y); return this }, setSize: function(width, height, center) { if (center === undefined) { center = true } var gameObject = this.gameObject; if (!width && gameObject.frame) { width = gameObject.frame.realWidth } if (!height && gameObject.frame) { height = gameObject.frame.realHeight } this.sourceWidth = width; this.sourceHeight = height; this.width = this.sourceWidth * this._sx; this.height = this.sourceHeight * this._sy; this.halfWidth = Math.floor(this.width / 2); this.halfHeight = Math.floor(this.height / 2); this.updateCenter(); if (center && gameObject.getCenter) { var ox = gameObject.displayWidth / 2; var oy = gameObject.displayHeight / 2; this.offset.set(ox - this.halfWidth, oy - this.halfHeight) } this.isCircle = false; this.radius = 0; return this }, setCircle: function(radius, offsetX, offsetY) { if (offsetX === undefined) { offsetX = this.offset.x } if (offsetY === undefined) { offsetY = this.offset.y } if (radius > 0) { this.isCircle = true; this.radius = radius; this.sourceWidth = radius * 2; this.sourceHeight = radius * 2; this.width = this.sourceWidth * this._sx; this.height = this.sourceHeight * this._sy; this.halfWidth = Math.floor(this.width / 2); this.halfHeight = Math.floor(this.height / 2); this.offset.set(offsetX, offsetY); this.updateCenter() } else { this.isCircle = false } return this }, reset: function(x, y) { this.stop(); var gameObject = this.gameObject; gameObject.setPosition(x, y); gameObject.getTopLeft(this.position); this.prev.copy(this.position); this.rotation = gameObject.angle; this.preRotation = gameObject.angle; this.updateBounds(); this.updateCenter() }, stop: function() { this.velocity.set(0); this.acceleration.set(0); this.speed = 0; this.angularVelocity = 0; this.angularAcceleration = 0; return this }, getBounds: function(obj) { obj.x = this.x; obj.y = this.y; obj.right = this.right; obj.bottom = this.bottom; return obj }, hitTest: function(x, y) { return this.isCircle ? CircleContains(this, x, y) : RectangleContains(this, x, y) }, onFloor: function() { return this.blocked.down }, onCeiling: function() { return this.blocked.up }, onWall: function() { return this.blocked.left || this.blocked.right }, deltaAbsX: function() { return this._dx > 0 ? this._dx : -this._dx }, deltaAbsY: function() { return this._dy > 0 ? this._dy : -this._dy }, deltaX: function() { return this._dx }, deltaY: function() { return this._dy }, deltaZ: function() { return this.rotation - this.preRotation }, destroy: function() { this.enable = false; this.world.pendingDestroy.set(this) }, drawDebug: function(graphic) { var pos = this.position; var x = pos.x + this.halfWidth; var y = pos.y + this.halfHeight; if (this.debugShowBody) { graphic.lineStyle(1, this.debugBodyColor); if (this.isCircle) { graphic.strokeCircle(x, y, this.width / 2) } else { graphic.strokeRect(pos.x, pos.y, this.width, this.height) } } if (this.debugShowVelocity) { graphic.lineStyle(1, this.world.defaults.velocityDebugColor, 1); graphic.lineBetween(x, y, x + this.velocity.x / 2, y + this.velocity.y / 2) } }, willDrawDebug: function() { return this.debugShowBody || this.debugShowVelocity }, setCollideWorldBounds: function(value) { if (value === undefined) { value = true } this.collideWorldBounds = value; return this }, setVelocity: function(x, y) { this.velocity.set(x, y); this.speed = Math.sqrt(x * x + y * y); return this }, setVelocityX: function(value) { this.velocity.x = value; var vx = value; var vy = this.velocity.y; this.speed = Math.sqrt(vx * vx + vy * vy); return this }, setVelocityY: function(value) { this.velocity.y = value; var vx = this.velocity.x; var vy = value; this.speed = Math.sqrt(vx * vx + vy * vy); return this }, setMaxVelocity: function(x, y) { this.maxVelocity.set(x, y); return this }, setBounce: function(x, y) { this.bounce.set(x, y); return this }, setBounceX: function(value) { this.bounce.x = value; return this }, setBounceY: function(value) { this.bounce.y = value; return this }, setAcceleration: function(x, y) { this.acceleration.set(x, y); return this }, setAccelerationX: function(value) { this.acceleration.x = value; return this }, setAccelerationY: function(value) { this.acceleration.y = value; return this }, setAllowDrag: function(value) { if (value === undefined) { value = true } this.allowDrag = value; return this }, setAllowGravity: function(value) { if (value === undefined) { value = true } this.allowGravity = value; return this }, setAllowRotation: function(value) { if (value === undefined) { value = true } this.allowRotation = value; return this }, setDrag: function(x, y) { this.drag.set(x, y); return this }, setDragX: function(value) { this.drag.x = value; return this }, setDragY: function(value) { this.drag.y = value; return this }, setGravity: function(x, y) { this.gravity.set(x, y); return this }, setGravityX: function(value) { this.gravity.x = value; return this }, setGravityY: function(value) { this.gravity.y = value; return this }, setFriction: function(x, y) { this.friction.set(x, y); return this }, setFrictionX: function(value) { this.friction.x = value; return this }, setFrictionY: function(value) { this.friction.y = value; return this }, setAngularVelocity: function(value) { this.angularVelocity = value; return this }, setAngularAcceleration: function(value) { this.angularAcceleration = value; return this }, setAngularDrag: function(value) { this.angularDrag = value; return this }, setMass: function(value) { this.mass = value; return this }, setImmovable: function(value) { if (value === undefined) { value = true } this.immovable = value; return this }, setEnable: function(value) { if (value === undefined) { value = true } this.enable = value; return this }, x: { get: function() { return this.position.x }, set: function(value) { this.position.x = value } }, y: { get: function() { return this.position.y }, set: function(value) { this.position.y = value } }, left: { get: function() { return this.position.x } }, right: { get: function() { return this.position.x + this.width } }, top: { get: function() { return this.position.y } }, bottom: { get: function() { return this.position.y + this.height } } }); module.exports = Body }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Collider = new Class({ initialize: function Collider(world, overlapOnly, object1, object2, collideCallback, processCallback, callbackContext) { this.world = world; this.name = ""; this.active = true; this.overlapOnly = overlapOnly; this.object1 = object1; this.object2 = object2; this.collideCallback = collideCallback; this.processCallback = processCallback; this.callbackContext = callbackContext }, setName: function(name) { this.name = name; return this }, update: function() { this.world.collideObjects(this.object1, this.object2, this.collideCallback, this.processCallback, this.callbackContext, this.overlapOnly) }, destroy: function() { this.world.removeCollider(this); this.active = false; this.world = null; this.object1 = null; this.object2 = null; this.collideCallback = null; this.processCallback = null; this.callbackContext = null } }); module.exports = Collider }, function(module, exports, __webpack_require__) { var CONST = __webpack_require__(52); var GetOverlapX = function(body1, body2, overlapOnly, bias) { var overlap = 0; var maxOverlap = body1.deltaAbsX() + body2.deltaAbsX() + bias; if (body1._dx === 0 && body2._dx === 0) { body1.embedded = true; body2.embedded = true } else if (body1._dx > body2._dx) { overlap = body1.right - body2.x; if (overlap > maxOverlap && !overlapOnly || body1.checkCollision.right === false || body2.checkCollision.left === false) { overlap = 0 } else { body1.touching.none = false; body1.touching.right = true; body2.touching.none = false; body2.touching.left = true; if (body2.physicsType === CONST.STATIC_BODY) { body1.blocked.none = false; body1.blocked.right = true } if (body1.physicsType === CONST.STATIC_BODY) { body2.blocked.none = false; body2.blocked.left = true } } } else if (body1._dx < body2._dx) { overlap = body1.x - body2.width - body2.x; if (-overlap > maxOverlap && !overlapOnly || body1.checkCollision.left === false || body2.checkCollision.right === false) { overlap = 0 } else { body1.touching.none = false; body1.touching.left = true; body2.touching.none = false; body2.touching.right = true; if (body2.physicsType === CONST.STATIC_BODY) { body1.blocked.none = false; body1.blocked.left = true } if (body1.physicsType === CONST.STATIC_BODY) { body2.blocked.none = false; body2.blocked.right = true } } } body1.overlapX = overlap; body2.overlapX = overlap; return overlap }; module.exports = GetOverlapX }, function(module, exports, __webpack_require__) { var CONST = __webpack_require__(52); var GetOverlapY = function(body1, body2, overlapOnly, bias) { var overlap = 0; var maxOverlap = body1.deltaAbsY() + body2.deltaAbsY() + bias; if (body1._dy === 0 && body2._dy === 0) { body1.embedded = true; body2.embedded = true } else if (body1._dy > body2._dy) { overlap = body1.bottom - body2.y; if (overlap > maxOverlap && !overlapOnly || body1.checkCollision.down === false || body2.checkCollision.up === false) { overlap = 0 } else { body1.touching.none = false; body1.touching.down = true; body2.touching.none = false; body2.touching.up = true; if (body2.physicsType === CONST.STATIC_BODY) { body1.blocked.none = false; body1.blocked.down = true } if (body1.physicsType === CONST.STATIC_BODY) { body2.blocked.none = false; body2.blocked.up = true } } } else if (body1._dy < body2._dy) { overlap = body1.y - body2.bottom; if (-overlap > maxOverlap && !overlapOnly || body1.checkCollision.up === false || body2.checkCollision.down === false) { overlap = 0 } else { body1.touching.none = false; body1.touching.up = true; body2.touching.none = false; body2.touching.down = true; if (body2.physicsType === CONST.STATIC_BODY) { body1.blocked.none = false; body1.blocked.up = true } if (body1.physicsType === CONST.STATIC_BODY) { body2.blocked.none = false; body2.blocked.down = true } } } body1.overlapY = overlap; body2.overlapY = overlap; return overlap }; module.exports = GetOverlapY }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var ProcessQueue = new Class({ initialize: function ProcessQueue() { this._pending = []; this._active = []; this._destroy = []; this._toProcess = 0 }, add: function(item) { this._pending.push(item); this._toProcess++; return this }, remove: function(item) { this._destroy.push(item); this._toProcess++; return this }, update: function() { if (this._toProcess === 0) { return this._active } var list = this._destroy; var active = this._active; var i; var item; for (i = 0; i < list.length; i++) { item = list[i]; var idx = active.indexOf(item); if (idx !== -1) { active.splice(idx, 1) } } list.length = 0; list = this._pending; for (i = 0; i < list.length; i++) { item = list[i]; this._active.push(item) } list.length = 0; this._toProcess = 0; return this._active }, getActive: function() { return this._active }, destroy: function() { this._pending = []; this._active = []; this._destroy = [] } }); module.exports = ProcessQueue }, function(module, exports, __webpack_require__) { var quickselect = __webpack_require__(337); function rbush(maxEntries) { var format = [".left", ".top", ".right", ".bottom"]; if (!(this instanceof rbush)) return new rbush(maxEntries, format); this._maxEntries = Math.max(4, maxEntries || 9); this._minEntries = Math.max(2, Math.ceil(this._maxEntries * .4)); this.clear() } rbush.prototype = { all: function() { return this._all(this.data, []) }, search: function(bbox) { var node = this.data, result = [], toBBox = this.toBBox; if (!intersects(bbox, node)) return result; var nodesToSearch = [], i, len, child, childBBox; while (node) { for (i = 0, len = node.children.length; i < len; i++) { child = node.children[i]; childBBox = node.leaf ? toBBox(child) : child; if (intersects(bbox, childBBox)) { if (node.leaf) result.push(child); else if (contains(bbox, childBBox)) this._all(child, result); else nodesToSearch.push(child) } } node = nodesToSearch.pop() } return result }, collides: function(bbox) { var node = this.data, toBBox = this.toBBox; if (!intersects(bbox, node)) return false; var nodesToSearch = [], i, len, child, childBBox; while (node) { for (i = 0, len = node.children.length; i < len; i++) { child = node.children[i]; childBBox = node.leaf ? toBBox(child) : child; if (intersects(bbox, childBBox)) { if (node.leaf || contains(bbox, childBBox)) return true; nodesToSearch.push(child) } } node = nodesToSearch.pop() } return false }, load: function(data) { if (!(data && data.length)) return this; if (data.length < this._minEntries) { for (var i = 0, len = data.length; i < len; i++) { this.insert(data[i]) } return this } var node = this._build(data.slice(), 0, data.length - 1, 0); if (!this.data.children.length) { this.data = node } else if (this.data.height === node.height) { this._splitRoot(this.data, node) } else { if (this.data.height < node.height) { var tmpNode = this.data; this.data = node; node = tmpNode } this._insert(node, this.data.height - node.height - 1, true) } return this }, insert: function(item) { if (item) this._insert(item, this.data.height - 1); return this }, clear: function() { this.data = createNode([]); return this }, remove: function(item, equalsFn) { if (!item) return this; var node = this.data, bbox = this.toBBox(item), path = [], indexes = [], i, parent, index, goingUp; while (node || path.length) { if (!node) { node = path.pop(); parent = path[path.length - 1]; i = indexes.pop(); goingUp = true } if (node.leaf) { index = findItem(item, node.children, equalsFn); if (index !== -1) { node.children.splice(index, 1); path.push(node); this._condense(path); return this } } if (!goingUp && !node.leaf && contains(node, bbox)) { path.push(node); indexes.push(i); i = 0; parent = node; node = node.children[0] } else if (parent) { i++; node = parent.children[i]; goingUp = false } else node = null } return this }, toBBox: function(item) { return item }, compareMinX: compareNodeMinX, compareMinY: compareNodeMinY, toJSON: function() { return this.data }, fromJSON: function(data) { this.data = data; return this }, _all: function(node, result) { var nodesToSearch = []; while (node) { if (node.leaf) result.push.apply(result, node.children); else nodesToSearch.push.apply(nodesToSearch, node.children); node = nodesToSearch.pop() } return result }, _build: function(items, left, right, height) { var N = right - left + 1, M = this._maxEntries, node; if (N <= M) { node = createNode(items.slice(left, right + 1)); calcBBox(node, this.toBBox); return node } if (!height) { height = Math.ceil(Math.log(N) / Math.log(M)); M = Math.ceil(N / Math.pow(M, height - 1)) } node = createNode([]); node.leaf = false; node.height = height; var N2 = Math.ceil(N / M), N1 = N2 * Math.ceil(Math.sqrt(M)), i, j, right2, right3; multiSelect(items, left, right, N1, this.compareMinX); for (i = left; i <= right; i += N1) { right2 = Math.min(i + N1 - 1, right); multiSelect(items, i, right2, N2, this.compareMinY); for (j = i; j <= right2; j += N2) { right3 = Math.min(j + N2 - 1, right2); node.children.push(this._build(items, j, right3, height - 1)) } } calcBBox(node, this.toBBox); return node }, _chooseSubtree: function(bbox, node, level, path) { var i, len, child, targetNode, area, enlargement, minArea, minEnlargement; while (true) { path.push(node); if (node.leaf || path.length - 1 === level) break; minArea = minEnlargement = Infinity; for (i = 0, len = node.children.length; i < len; i++) { child = node.children[i]; area = bboxArea(child); enlargement = enlargedArea(bbox, child) - area; if (enlargement < minEnlargement) { minEnlargement = enlargement; minArea = area < minArea ? area : minArea; targetNode = child } else if (enlargement === minEnlargement) { if (area < minArea) { minArea = area; targetNode = child } } } node = targetNode || node.children[0] } return node }, _insert: function(item, level, isNode) { var toBBox = this.toBBox, bbox = isNode ? item : toBBox(item), insertPath = []; var node = this._chooseSubtree(bbox, this.data, level, insertPath); node.children.push(item); extend(node, bbox); while (level >= 0) { if (insertPath[level].children.length > this._maxEntries) { this._split(insertPath, level); level-- } else break } this._adjustParentBBoxes(bbox, insertPath, level) }, _split: function(insertPath, level) { var node = insertPath[level], M = node.children.length, m = this._minEntries; this._chooseSplitAxis(node, m, M); var splitIndex = this._chooseSplitIndex(node, m, M); var newNode = createNode(node.children.splice(splitIndex, node.children.length - splitIndex)); newNode.height = node.height; newNode.leaf = node.leaf; calcBBox(node, this.toBBox); calcBBox(newNode, this.toBBox); if (level) insertPath[level - 1].children.push(newNode); else this._splitRoot(node, newNode) }, _splitRoot: function(node, newNode) { this.data = createNode([node, newNode]); this.data.height = node.height + 1; this.data.leaf = false; calcBBox(this.data, this.toBBox) }, _chooseSplitIndex: function(node, m, M) { var i, bbox1, bbox2, overlap, area, minOverlap, minArea, index; minOverlap = minArea = Infinity; for (i = m; i <= M - m; i++) { bbox1 = distBBox(node, 0, i, this.toBBox); bbox2 = distBBox(node, i, M, this.toBBox); overlap = intersectionArea(bbox1, bbox2); area = bboxArea(bbox1) + bboxArea(bbox2); if (overlap < minOverlap) { minOverlap = overlap; index = i; minArea = area < minArea ? area : minArea } else if (overlap === minOverlap) { if (area < minArea) { minArea = area; index = i } } } return index }, _chooseSplitAxis: function(node, m, M) { var compareMinX = node.leaf ? this.compareMinX : compareNodeMinX, compareMinY = node.leaf ? this.compareMinY : compareNodeMinY, xMargin = this._allDistMargin(node, m, M, compareMinX), yMargin = this._allDistMargin(node, m, M, compareMinY); if (xMargin < yMargin) node.children.sort(compareMinX) }, _allDistMargin: function(node, m, M, compare) { node.children.sort(compare); var toBBox = this.toBBox, leftBBox = distBBox(node, 0, m, toBBox), rightBBox = distBBox(node, M - m, M, toBBox), margin = bboxMargin(leftBBox) + bboxMargin(rightBBox), i, child; for (i = m; i < M - m; i++) { child = node.children[i]; extend(leftBBox, node.leaf ? toBBox(child) : child); margin += bboxMargin(leftBBox) } for (i = M - m - 1; i >= m; i--) { child = node.children[i]; extend(rightBBox, node.leaf ? toBBox(child) : child); margin += bboxMargin(rightBBox) } return margin }, _adjustParentBBoxes: function(bbox, path, level) { for (var i = level; i >= 0; i--) { extend(path[i], bbox) } }, _condense: function(path) { for (var i = path.length - 1, siblings; i >= 0; i--) { if (path[i].children.length === 0) { if (i > 0) { siblings = path[i - 1].children; siblings.splice(siblings.indexOf(path[i]), 1) } else this.clear() } else calcBBox(path[i], this.toBBox) } }, compareMinX: function(a, b) { return a.left - b.left }, compareMinY: function(a, b) { return a.top - b.top }, toBBox: function(a) { return { minX: a.left, minY: a.top, maxX: a.right, maxY: a.bottom } } }; function findItem(item, items, equalsFn) { if (!equalsFn) return items.indexOf(item); for (var i = 0; i < items.length; i++) { if (equalsFn(item, items[i])) return i } return -1 } function calcBBox(node, toBBox) { distBBox(node, 0, node.children.length, toBBox, node) } function distBBox(node, k, p, toBBox, destNode) { if (!destNode) destNode = createNode(null); destNode.minX = Infinity; destNode.minY = Infinity; destNode.maxX = -Infinity; destNode.maxY = -Infinity; for (var i = k, child; i < p; i++) { child = node.children[i]; extend(destNode, node.leaf ? toBBox(child) : child) } return destNode } function extend(a, b) { a.minX = Math.min(a.minX, b.minX); a.minY = Math.min(a.minY, b.minY); a.maxX = Math.max(a.maxX, b.maxX); a.maxY = Math.max(a.maxY, b.maxY); return a } function compareNodeMinX(a, b) { return a.minX - b.minX } function compareNodeMinY(a, b) { return a.minY - b.minY } function bboxArea(a) { return (a.maxX - a.minX) * (a.maxY - a.minY) } function bboxMargin(a) { return a.maxX - a.minX + (a.maxY - a.minY) } function enlargedArea(a, b) { return (Math.max(b.maxX, a.maxX) - Math.min(b.minX, a.minX)) * (Math.max(b.maxY, a.maxY) - Math.min(b.minY, a.minY)) } function intersectionArea(a, b) { var minX = Math.max(a.minX, b.minX), minY = Math.max(a.minY, b.minY), maxX = Math.min(a.maxX, b.maxX), maxY = Math.min(a.maxY, b.maxY); return Math.max(0, maxX - minX) * Math.max(0, maxY - minY) } function contains(a, b) { return a.minX <= b.minX && a.minY <= b.minY && b.maxX <= a.maxX && b.maxY <= a.maxY } function intersects(a, b) { return b.minX <= a.maxX && b.minY <= a.maxY && b.maxX >= a.minX && b.maxY >= a.minY } function createNode(children) { return { children: children, height: 1, leaf: true, minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity } } function multiSelect(arr, left, right, n, compare) { var stack = [left, right], mid; while (stack.length) { right = stack.pop(); left = stack.pop(); if (right - left <= n) continue; mid = left + Math.ceil((right - left) / n / 2) * n; quickselect(arr, mid, left, right, compare); stack.push(left, mid, mid, right) } } module.exports = rbush }, function(module, exports) { var TileIntersectsBody = function(tileWorldRect, body) { return !(body.right <= tileWorldRect.left || body.bottom <= tileWorldRect.top || body.position.x >= tileWorldRect.right || body.position.y >= tileWorldRect.bottom) }; module.exports = TileIntersectsBody }, function(module, exports, __webpack_require__) { var CircleContains = __webpack_require__(46); var Class = __webpack_require__(0); var CONST = __webpack_require__(52); var RectangleContains = __webpack_require__(47); var Vector2 = __webpack_require__(3); var StaticBody = new Class({ initialize: function StaticBody(world, gameObject) { var width = gameObject.width ? gameObject.width : 64; var height = gameObject.height ? gameObject.height : 64; this.world = world; this.gameObject = gameObject; this.debugShowBody = world.defaults.debugShowStaticBody; this.debugBodyColor = world.defaults.staticBodyDebugColor; this.enable = true; this.isCircle = false; this.radius = 0; this.offset = new Vector2; this.position = new Vector2(gameObject.x - gameObject.displayOriginX, gameObject.y - gameObject.displayOriginY); this.width = width; this.height = height; this.halfWidth = Math.abs(this.width / 2); this.halfHeight = Math.abs(this.height / 2); this.center = new Vector2(gameObject.x + this.halfWidth, gameObject.y + this.halfHeight); this.velocity = Vector2.ZERO; this.allowGravity = false; this.gravity = Vector2.ZERO; this.bounce = Vector2.ZERO; this.onWorldBounds = false; this.onCollide = false; this.onOverlap = false; this.mass = 1; this.immovable = true; this.customSeparateX = false; this.customSeparateY = false; this.overlapX = 0; this.overlapY = 0; this.overlapR = 0; this.embedded = false; this.collideWorldBounds = false; this.checkCollision = { none: false, up: true, down: true, left: true, right: true }; this.touching = { none: true, up: false, down: false, left: false, right: false }; this.wasTouching = { none: true, up: false, down: false, left: false, right: false }; this.blocked = { none: true, up: false, down: false, left: false, right: false }; this.physicsType = CONST.STATIC_BODY; this._dx = 0; this._dy = 0 }, setGameObject: function(gameObject, update) { if (gameObject && gameObject !== this.gameObject) { this.gameObject.body = null; gameObject.body = this; this.gameObject = gameObject } if (update) { this.updateFromGameObject() } return this }, updateFromGameObject: function() { this.world.staticTree.remove(this); var gameObject = this.gameObject; gameObject.getTopLeft(this.position); this.width = gameObject.displayWidth; this.height = gameObject.displayHeight; this.halfWidth = Math.abs(this.width / 2); this.halfHeight = Math.abs(this.height / 2); this.center.set(this.position.x + this.halfWidth, this.position.y + this.halfHeight); this.world.staticTree.insert(this); return this }, setOffset: function(x, y) { if (y === undefined) { y = x } this.world.staticTree.remove(this); this.position.x -= this.offset.x; this.position.y -= this.offset.y; this.offset.set(x, y); this.position.x += this.offset.x; this.position.y += this.offset.y; this.updateCenter(); this.world.staticTree.insert(this); return this }, setSize: function(width, height, offsetX, offsetY) { if (offsetX === undefined) { offsetX = this.offset.x } if (offsetY === undefined) { offsetY = this.offset.y } var gameObject = this.gameObject; if (!width && gameObject.frame) { width = gameObject.frame.realWidth } if (!height && gameObject.frame) { height = gameObject.frame.realHeight } this.world.staticTree.remove(this); this.width = width; this.height = height; this.halfWidth = Math.floor(width / 2); this.halfHeight = Math.floor(height / 2); this.offset.set(offsetX, offsetY); this.updateCenter(); this.isCircle = false; this.radius = 0; this.world.staticTree.insert(this); return this }, setCircle: function(radius, offsetX, offsetY) { if (offsetX === undefined) { offsetX = this.offset.x } if (offsetY === undefined) { offsetY = this.offset.y } if (radius > 0) { this.world.staticTree.remove(this); this.isCircle = true; this.radius = radius; this.width = radius * 2; this.height = radius * 2; this.halfWidth = Math.floor(this.width / 2); this.halfHeight = Math.floor(this.height / 2); this.offset.set(offsetX, offsetY); this.updateCenter(); this.world.staticTree.insert(this) } else { this.isCircle = false } return this }, updateCenter: function() { this.center.set(this.position.x + this.halfWidth, this.position.y + this.halfHeight) }, reset: function(x, y) { var gameObject = this.gameObject; if (x === undefined) { x = gameObject.x } if (y === undefined) { y = gameObject.y } this.world.staticTree.remove(this); gameObject.getTopLeft(this.position); this.updateCenter(); this.world.staticTree.insert(this) }, stop: function() { return this }, getBounds: function(obj) { obj.x = this.x; obj.y = this.y; obj.right = this.right; obj.bottom = this.bottom; return obj }, hitTest: function(x, y) { return this.isCircle ? CircleContains(this, x, y) : RectangleContains(this, x, y) }, postUpdate: function() {}, deltaAbsX: function() { return 0 }, deltaAbsY: function() { return 0 }, deltaX: function() { return 0 }, deltaY: function() { return 0 }, deltaZ: function() { return 0 }, destroy: function() { this.enable = false; this.world.pendingDestroy.set(this) }, drawDebug: function(graphic) { var pos = this.position; if (this.debugShowBody) { graphic.lineStyle(1, this.debugBodyColor, 1); graphic.strokeRect(pos.x, pos.y, this.width, this.height) } }, willDrawDebug: function() { return this.debugShowBody }, setMass: function(value) { if (value <= 0) { value = .1 } this.mass = value; return this }, x: { get: function() { return this.position.x }, set: function(value) { this.world.staticTree.remove(this); this.position.x = value; this.world.staticTree.insert(this) } }, y: { get: function() { return this.position.y }, set: function(value) { this.world.staticTree.remove(this); this.position.y = value; this.world.staticTree.insert(this) } }, left: { get: function() { return this.position.x } }, right: { get: function() { return this.position.x + this.width } }, top: { get: function() { return this.position.y } }, bottom: { get: function() { return this.position.y + this.height } } }); module.exports = StaticBody }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var COLLIDES = __webpack_require__(101); var GetVelocity = __webpack_require__(1035); var TYPE = __webpack_require__(102); var UpdateMotion = __webpack_require__(1036); var Body = new Class({ initialize: function Body(world, x, y, sx, sy) { if (sx === undefined) { sx = 16 } if (sy === undefined) { sy = sx } this.world = world; this.gameObject = null; this.enabled = true; this.parent; this.id = world.getNextID(); this.name = ""; this.size = { x: sx, y: sy }; this.offset = { x: 0, y: 0 }; this.pos = { x: x, y: y }; this.last = { x: x, y: y }; this.vel = { x: 0, y: 0 }; this.accel = { x: 0, y: 0 }; this.friction = { x: 0, y: 0 }; this.maxVel = { x: world.defaults.maxVelocityX, y: world.defaults.maxVelocityY }; this.standing = false; this.gravityFactor = world.defaults.gravityFactor; this.bounciness = world.defaults.bounciness; this.minBounceVelocity = world.defaults.minBounceVelocity; this.accelGround = 0; this.accelAir = 0; this.jumpSpeed = 0; this.type = TYPE.NONE; this.checkAgainst = TYPE.NONE; this.collides = COLLIDES.NEVER; this.debugShowBody = world.defaults.debugShowBody; this.debugShowVelocity = world.defaults.debugShowVelocity; this.debugBodyColor = world.defaults.bodyDebugColor; this.updateCallback; this.slopeStanding = { min: .767944870877505, max: 2.3736477827122884 } }, reset: function(x, y) { this.pos = { x: x, y: y }; this.last = { x: x, y: y }; this.vel = { x: 0, y: 0 }; this.accel = { x: 0, y: 0 }; this.friction = { x: 0, y: 0 }; this.maxVel = { x: 100, y: 100 }; this.standing = false; this.gravityFactor = 1; this.bounciness = 0; this.minBounceVelocity = 40; this.accelGround = 0; this.accelAir = 0; this.jumpSpeed = 0; this.type = TYPE.NONE; this.checkAgainst = TYPE.NONE; this.collides = COLLIDES.NEVER }, update: function(delta) { var pos = this.pos; this.last.x = pos.x; this.last.y = pos.y; this.vel.y += this.world.gravity * delta * this.gravityFactor; this.vel.x = GetVelocity(delta, this.vel.x, this.accel.x, this.friction.x, this.maxVel.x); this.vel.y = GetVelocity(delta, this.vel.y, this.accel.y, this.friction.y, this.maxVel.y); var mx = this.vel.x * delta; var my = this.vel.y * delta; var res = this.world.collisionMap.trace(pos.x, pos.y, mx, my, this.size.x, this.size.y); if (this.handleMovementTrace(res)) { UpdateMotion(this, res) } var go = this.gameObject; if (go) { go.x = pos.x - this.offset.x + go.displayOriginX * go.scaleX; go.y = pos.y - this.offset.y + go.displayOriginY * go.scaleY } if (this.updateCallback) { this.updateCallback(this) } }, drawDebug: function(graphic) { var pos = this.pos; if (this.debugShowBody) { graphic.lineStyle(1, this.debugBodyColor, 1); graphic.strokeRect(pos.x, pos.y, this.size.x, this.size.y) } if (this.debugShowVelocity) { var x = pos.x + this.size.x / 2; var y = pos.y + this.size.y / 2; graphic.lineStyle(1, this.world.defaults.velocityDebugColor, 1); graphic.lineBetween(x, y, x + this.vel.x, y + this.vel.y) } }, willDrawDebug: function() { return this.debugShowBody || this.debugShowVelocity }, skipHash: function() { return !this.enabled || this.type === 0 && this.checkAgainst === 0 && this.collides === 0 }, touches: function(other) { return !(this.pos.x >= other.pos.x + other.size.x || this.pos.x + this.size.x <= other.pos.x || this.pos.y >= other.pos.y + other.size.y || this.pos.y + this.size.y <= other.pos.y) }, resetSize: function(x, y, width, height) { this.pos.x = x; this.pos.y = y; this.size.x = width; this.size.y = height; return this }, toJSON: function() { var output = { name: this.name, size: { x: this.size.x, y: this.size.y }, pos: { x: this.pos.x, y: this.pos.y }, vel: { x: this.vel.x, y: this.vel.y }, accel: { x: this.accel.x, y: this.accel.y }, friction: { x: this.friction.x, y: this.friction.y }, maxVel: { x: this.maxVel.x, y: this.maxVel.y }, gravityFactor: this.gravityFactor, bounciness: this.bounciness, minBounceVelocity: this.minBounceVelocity, type: this.type, checkAgainst: this.checkAgainst, collides: this.collides }; return output }, fromJSON: function() {}, check: function() {}, collideWith: function(other, axis) { if (this.parent && this.parent._collideCallback) { this.parent._collideCallback.call(this.parent._callbackScope, this, other, axis) } }, handleMovementTrace: function() { return true }, destroy: function() { this.world.remove(this); this.enabled = false; this.world = null; this.gameObject = null; this.parent = null } }); module.exports = Body }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var DefaultDefs = __webpack_require__(1037); var CollisionMap = new Class({ initialize: function CollisionMap(tilesize, data) { if (tilesize === undefined) { tilesize = 32 } this.tilesize = tilesize; this.data = Array.isArray(data) ? data : []; this.width = Array.isArray(data) ? data[0].length : 0; this.height = Array.isArray(data) ? data.length : 0; this.lastSlope = 55; this.tiledef = DefaultDefs }, trace: function(x, y, vx, vy, objectWidth, objectHeight) { var res = { collision: { x: false, y: false, slope: false }, pos: { x: x + vx, y: y + vy }, tile: { x: 0, y: 0 } }; if (!this.data) { return res } var steps = Math.ceil(Math.max(Math.abs(vx), Math.abs(vy)) / this.tilesize); if (steps > 1) { var sx = vx / steps; var sy = vy / steps; for (var i = 0; i < steps && (sx || sy); i++) { this.step(res, x, y, sx, sy, objectWidth, objectHeight, vx, vy, i); x = res.pos.x; y = res.pos.y; if (res.collision.x) { sx = 0; vx = 0 } if (res.collision.y) { sy = 0; vy = 0 } if (res.collision.slope) { break } } } else { this.step(res, x, y, vx, vy, objectWidth, objectHeight, vx, vy, 0) } return res }, step: function(res, x, y, vx, vy, width, height, rvx, rvy, step) { var t = 0; var tileX; var tileY; var tilesize = this.tilesize; var mapWidth = this.width; var mapHeight = this.height; if (vx) { var pxOffsetX = vx > 0 ? width : 0; var tileOffsetX = vx < 0 ? tilesize : 0; var firstTileY = Math.max(Math.floor(y / tilesize), 0); var lastTileY = Math.min(Math.ceil((y + height) / tilesize), mapHeight); tileX = Math.floor((res.pos.x + pxOffsetX) / tilesize); var prevTileX = Math.floor((x + pxOffsetX) / tilesize); if (step > 0 || tileX === prevTileX || prevTileX < 0 || prevTileX >= mapWidth) { prevTileX = -1 } if (tileX >= 0 && tileX < mapWidth) { for (tileY = firstTileY; tileY < lastTileY; tileY++) { if (prevTileX !== -1) { t = this.data[tileY][prevTileX]; if (t > 1 && t <= this.lastSlope && this.checkDef(res, t, x, y, rvx, rvy, width, height, prevTileX, tileY)) { break } } t = this.data[tileY][tileX]; if (t === 1 || t > this.lastSlope || t > 1 && this.checkDef(res, t, x, y, rvx, rvy, width, height, tileX, tileY)) { if (t > 1 && t <= this.lastSlope && res.collision.slope) { break } res.collision.x = true; res.tile.x = t; res.pos.x = tileX * tilesize - pxOffsetX + tileOffsetX; x = res.pos.x; rvx = 0; break } } } } if (vy) { var pxOffsetY = vy > 0 ? height : 0; var tileOffsetY = vy < 0 ? tilesize : 0; var firstTileX = Math.max(Math.floor(res.pos.x / tilesize), 0); var lastTileX = Math.min(Math.ceil((res.pos.x + width) / tilesize), mapWidth); tileY = Math.floor((res.pos.y + pxOffsetY) / tilesize); var prevTileY = Math.floor((y + pxOffsetY) / tilesize); if (step > 0 || tileY === prevTileY || prevTileY < 0 || prevTileY >= mapHeight) { prevTileY = -1 } if (tileY >= 0 && tileY < mapHeight) { for (tileX = firstTileX; tileX < lastTileX; tileX++) { if (prevTileY !== -1) { t = this.data[prevTileY][tileX]; if (t > 1 && t <= this.lastSlope && this.checkDef(res, t, x, y, rvx, rvy, width, height, tileX, prevTileY)) { break } } t = this.data[tileY][tileX]; if (t === 1 || t > this.lastSlope || t > 1 && this.checkDef(res, t, x, y, rvx, rvy, width, height, tileX, tileY)) { if (t > 1 && t <= this.lastSlope && res.collision.slope) { break } res.collision.y = true; res.tile.y = t; res.pos.y = tileY * tilesize - pxOffsetY + tileOffsetY; break } } } } }, checkDef: function(res, t, x, y, vx, vy, width, height, tileX, tileY) { var def = this.tiledef[t]; if (!def) { return false } var tilesize = this.tilesize; var lx = (tileX + def[0]) * tilesize; var ly = (tileY + def[1]) * tilesize; var lvx = (def[2] - def[0]) * tilesize; var lvy = (def[3] - def[1]) * tilesize; var solid = def[4]; var tx = x + vx + (lvy < 0 ? width : 0) - lx; var ty = y + vy + (lvx > 0 ? height : 0) - ly; if (lvx * ty - lvy * tx > 0) { if (vx * -lvy + vy * lvx < 0) { return solid } var length = Math.sqrt(lvx * lvx + lvy * lvy); var nx = lvy / length; var ny = -lvx / length; var proj = tx * nx + ty * ny; var px = nx * proj; var py = ny * proj; if (px * px + py * py >= vx * vx + vy * vy) { return solid || lvx * (ty - vy) - lvy * (tx - vx) < .5 } res.pos.x = x + vx - px; res.pos.y = y + vy - py; res.collision.slope = { x: lvx, y: lvy, nx: nx, ny: ny }; return true } return false } }); module.exports = CollisionMap }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var ImpactBody = __webpack_require__(432); var ImpactImage = __webpack_require__(433); var ImpactSprite = __webpack_require__(434); var Factory = new Class({ initialize: function Factory(world) { this.world = world; this.sys = world.scene.sys }, body: function(x, y, width, height) { return new ImpactBody(this.world, x, y, width, height) }, existing: function(gameObject) { var x = gameObject.x - gameObject.frame.centerX; var y = gameObject.y - gameObject.frame.centerY; var w = gameObject.width; var h = gameObject.height; gameObject.body = this.world.create(x, y, w, h); gameObject.body.parent = gameObject; gameObject.body.gameObject = gameObject; return gameObject }, image: function(x, y, key, frame) { var image = new ImpactImage(this.world, x, y, key, frame); this.sys.displayList.add(image); return image }, sprite: function(x, y, key, frame) { var sprite = new ImpactSprite(this.world, x, y, key, frame); this.sys.displayList.add(sprite); this.sys.updateList.add(sprite); return sprite }, destroy: function() { this.world = null; this.sys = null } }); module.exports = Factory }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Components = __webpack_require__(203); var ImpactBody = new Class({ Mixins: [Components.Acceleration, Components.BodyScale, Components.BodyType, Components.Bounce, Components.CheckAgainst, Components.Collides, Components.Debug, Components.Friction, Components.Gravity, Components.Offset, Components.SetGameObject, Components.Velocity], initialize: function ImpactBody(world, x, y, width, height) { this.body = world.create(x, y, width, height); this.body.parent = this; this.size = this.body.size; this.offset = this.body.offset; this.vel = this.body.vel; this.accel = this.body.accel; this.friction = this.body.friction; this.maxVel = this.body.maxVel } }); module.exports = ImpactBody }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Components = __webpack_require__(203); var Image = __webpack_require__(82); var ImpactImage = new Class({ Extends: Image, Mixins: [Components.Acceleration, Components.BodyScale, Components.BodyType, Components.Bounce, Components.CheckAgainst, Components.Collides, Components.Debug, Components.Friction, Components.Gravity, Components.Offset, Components.SetGameObject, Components.Velocity], initialize: function ImpactImage(world, x, y, texture, frame) { Image.call(this, world.scene, x, y, texture, frame); this.body = world.create(x - this.frame.centerX, y - this.frame.centerY, this.width, this.height); this.body.parent = this; this.body.gameObject = this; this.size = this.body.size; this.offset = this.body.offset; this.vel = this.body.vel; this.accel = this.body.accel; this.friction = this.body.friction; this.maxVel = this.body.maxVel } }); module.exports = ImpactImage }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Components = __webpack_require__(203); var Sprite = __webpack_require__(50); var ImpactSprite = new Class({ Extends: Sprite, Mixins: [Components.Acceleration, Components.BodyScale, Components.BodyType, Components.Bounce, Components.CheckAgainst, Components.Collides, Components.Debug, Components.Friction, Components.Gravity, Components.Offset, Components.SetGameObject, Components.Velocity], initialize: function ImpactSprite(world, x, y, texture, frame) { Sprite.call(this, world.scene, x, y, texture, frame); this.body = world.create(x - this.frame.centerX, y - this.frame.centerY, this.width, this.height); this.body.parent = this; this.body.gameObject = this; this.size = this.body.size; this.offset = this.body.offset; this.vel = this.body.vel; this.accel = this.body.accel; this.friction = this.body.friction; this.maxVel = this.body.maxVel } }); module.exports = ImpactSprite }, function(module, exports, __webpack_require__) { var Body = __webpack_require__(429); var Class = __webpack_require__(0); var COLLIDES = __webpack_require__(101); var CollisionMap = __webpack_require__(430); var EventEmitter = __webpack_require__(11); var GetFastValue = __webpack_require__(1); var HasValue = __webpack_require__(83); var Set = __webpack_require__(81); var Solver = __webpack_require__(1051); var TILEMAP_FORMATS = __webpack_require__(31); var TYPE = __webpack_require__(102); var World = new Class({ Extends: EventEmitter, initialize: function World(scene, config) { EventEmitter.call(this); this.scene = scene; this.bodies = new Set; this.gravity = GetFastValue(config, "gravity", 0); this.cellSize = GetFastValue(config, "cellSize", 64); this.collisionMap = new CollisionMap; this.timeScale = GetFastValue(config, "timeScale", 1); this.maxStep = GetFastValue(config, "maxStep", .05); this.enabled = true; this.drawDebug = GetFastValue(config, "debug", false); this.debugGraphic; var _maxVelocity = GetFastValue(config, "maxVelocity", 100); this.defaults = { debugShowBody: GetFastValue(config, "debugShowBody", true), debugShowVelocity: GetFastValue(config, "debugShowVelocity", true), bodyDebugColor: GetFastValue(config, "debugBodyColor", 16711935), velocityDebugColor: GetFastValue(config, "debugVelocityColor", 65280), maxVelocityX: GetFastValue(config, "maxVelocityX", _maxVelocity), maxVelocityY: GetFastValue(config, "maxVelocityY", _maxVelocity), minBounceVelocity: GetFastValue(config, "minBounceVelocity", 40), gravityFactor: GetFastValue(config, "gravityFactor", 1), bounciness: GetFastValue(config, "bounciness", 0) }; this.walls = { left: null, right: null, top: null, bottom: null }; this.delta = 0; this._lastId = 0; if (GetFastValue(config, "setBounds", false)) { var boundsConfig = config["setBounds"]; if (typeof boundsConfig === "boolean") { this.setBounds() } else { var x = GetFastValue(boundsConfig, "x", 0); var y = GetFastValue(boundsConfig, "y", 0); var width = GetFastValue(boundsConfig, "width", scene.sys.game.config.width); var height = GetFastValue(boundsConfig, "height", scene.sys.game.config.height); var thickness = GetFastValue(boundsConfig, "thickness", 64); var left = GetFastValue(boundsConfig, "left", true); var right = GetFastValue(boundsConfig, "right", true); var top = GetFastValue(boundsConfig, "top", true); var bottom = GetFastValue(boundsConfig, "bottom", true); this.setBounds(x, y, width, height, thickness, left, right, top, bottom) } } if (this.drawDebug) { this.createDebugGraphic() } }, setCollisionMap: function(key, tileSize) { if (typeof key === "string") { var tilemapData = this.scene.cache.tilemap.get(key); if (!tilemapData || tilemapData.format !== TILEMAP_FORMATS.WELTMEISTER) { console.warn("The specified key does not correspond to a Weltmeister tilemap: " + key); return null } var layers = tilemapData.data.layer; var collisionLayer; for (var i = 0; i < layers.length; i++) { if (layers[i].name === "collision") { collisionLayer = layers[i]; break } } if (tileSize === undefined) { tileSize = collisionLayer.tilesize } this.collisionMap = new CollisionMap(tileSize, collisionLayer.data) } else if (Array.isArray(key)) { this.collisionMap = new CollisionMap(tileSize, key) } else { console.warn("Invalid Weltmeister collision map data: " + key) } return this.collisionMap }, setCollisionMapFromTilemapLayer: function(tilemapLayer, options) { if (options === undefined) { options = {} } var slopeProperty = GetFastValue(options, "slopeProperty", null); var slopeMap = GetFastValue(options, "slopeMap", null); var collidingSlope = GetFastValue(options, "defaultCollidingSlope", null); var nonCollidingSlope = GetFastValue(options, "defaultNonCollidingSlope", 0); var layerData = tilemapLayer.layer; var tileSize = layerData.baseTileWidth; var collisionData = []; for (var ty = 0; ty < layerData.height; ty++) { collisionData[ty] = []; for (var tx = 0; tx < layerData.width; tx++) { var tile = layerData.data[ty][tx]; if (tile && tile.collides) { if (slopeProperty !== null && HasValue(tile.properties, slopeProperty)) { collisionData[ty][tx] = parseInt(tile.properties[slopeProperty], 10) } else if (slopeMap !== null && HasValue(slopeMap, tile.index)) { collisionData[ty][tx] = slopeMap[tile.index] } else if (collidingSlope !== null) { collisionData[ty][tx] = collidingSlope } else { collisionData[ty][tx] = tile.index } } else { collisionData[ty][tx] = nonCollidingSlope } } } this.collisionMap = new CollisionMap(tileSize, collisionData); return this.collisionMap }, setBounds: function(x, y, width, height, thickness, left, right, top, bottom) { if (x === undefined) { x = 0 } if (y === undefined) { y = 0 } if (width === undefined) { width = this.scene.sys.game.config.width } if (height === undefined) { height = this.scene.sys.game.config.height } if (thickness === undefined) { thickness = 64 } if (left === undefined) { left = true } if (right === undefined) { right = true } if (top === undefined) { top = true } if (bottom === undefined) { bottom = true } this.updateWall(left, "left", x - thickness, y, thickness, height); this.updateWall(right, "right", x + width, y, thickness, height); this.updateWall(top, "top", x, y - thickness, width, thickness); this.updateWall(bottom, "bottom", x, y + height, width, thickness); return this }, updateWall: function(add, position, x, y, width, height) { var wall = this.walls[position]; if (add) { if (wall) { wall.resetSize(x, y, width, height) } else { this.walls[position] = this.create(x, y, width, height); this.walls[position].name = position; this.walls[position].gravityFactor = 0; this.walls[position].collides = COLLIDES.FIXED } } else { if (wall) { this.bodies.remove(wall) } this.walls[position] = null } }, createDebugGraphic: function() { var graphic = this.scene.sys.add.graphics({ x: 0, y: 0 }); graphic.setDepth(Number.MAX_VALUE); this.debugGraphic = graphic; this.drawDebug = true; return graphic }, getNextID: function() { return this._lastId++ }, create: function(x, y, sizeX, sizeY) { var body = new Body(this, x, y, sizeX, sizeY); this.bodies.set(body); return body }, remove: function(object) { this.bodies.delete(object) }, pause: function() { this.enabled = false; this.emit("pause"); return this }, resume: function() { this.enabled = true; this.emit("resume"); return this }, update: function(time, delta) { if (!this.enabled || this.bodies.size === 0) { return } var clampedDelta = Math.min(delta / 1e3, this.maxStep) * this.timeScale; this.delta = clampedDelta; var i; var body; var bodies = this.bodies.entries; var len = bodies.length; var hash = {}; var size = this.cellSize; for (i = 0; i < len; i++) { body = bodies[i]; if (body.enabled) { body.update(clampedDelta) } } for (i = 0; i < len; i++) { body = bodies[i]; if (body && !body.skipHash()) { this.checkHash(body, hash, size) } } if (this.drawDebug) { var graphics = this.debugGraphic; graphics.clear(); for (i = 0; i < len; i++) { body = bodies[i]; if (body && body.willDrawDebug()) { body.drawDebug(graphics) } } } }, checkHash: function(body, hash, size) { var checked = {}; var xmin = Math.floor(body.pos.x / size); var ymin = Math.floor(body.pos.y / size); var xmax = Math.floor((body.pos.x + body.size.x) / size) + 1; var ymax = Math.floor((body.pos.y + body.size.y) / size) + 1; for (var x = xmin; x < xmax; x++) { for (var y = ymin; y < ymax; y++) { if (!hash[x]) { hash[x] = {}; hash[x][y] = [body] } else if (!hash[x][y]) { hash[x][y] = [body] } else { var cell = hash[x][y]; for (var c = 0; c < cell.length; c++) { if (body.touches(cell[c]) && !checked[cell[c].id]) { checked[cell[c].id] = true; this.checkBodies(body, cell[c]) } } cell.push(body) } } } }, checkBodies: function(bodyA, bodyB) { if (bodyA.collides === COLLIDES.FIXED && bodyB.collides === COLLIDES.FIXED) { return } if (bodyA.checkAgainst & bodyB.type) { bodyA.check(bodyB) } if (bodyB.checkAgainst & bodyA.type) { bodyB.check(bodyA) } if (bodyA.collides && bodyB.collides && bodyA.collides + bodyB.collides > COLLIDES.ACTIVE) { Solver(this, bodyA, bodyB) } }, setCollidesNever: function(bodies) { for (var i = 0; i < bodies.length; i++) { bodies[i].collides = COLLIDES.NEVER } return this }, setLite: function(bodies) { for (var i = 0; i < bodies.length; i++) { bodies[i].collides = COLLIDES.LITE } return this }, setPassive: function(bodies) { for (var i = 0; i < bodies.length; i++) { bodies[i].collides = COLLIDES.PASSIVE } return this }, setActive: function(bodies) { for (var i = 0; i < bodies.length; i++) { bodies[i].collides = COLLIDES.ACTIVE } return this }, setFixed: function(bodies) { for (var i = 0; i < bodies.length; i++) { bodies[i].collides = COLLIDES.FIXED } return this }, setTypeNone: function(bodies) { for (var i = 0; i < bodies.length; i++) { bodies[i].type = TYPE.NONE } return this }, setTypeA: function(bodies) { for (var i = 0; i < bodies.length; i++) { bodies[i].type = TYPE.A } return this }, setTypeB: function(bodies) { for (var i = 0; i < bodies.length; i++) { bodies[i].type = TYPE.B } return this }, setAvsB: function(bodies) { for (var i = 0; i < bodies.length; i++) { bodies[i].type = TYPE.A; bodies[i].checkAgainst = TYPE.B } return this }, setBvsA: function(bodies) { for (var i = 0; i < bodies.length; i++) { bodies[i].type = TYPE.B; bodies[i].checkAgainst = TYPE.A } return this }, setCheckAgainstNone: function(bodies) { for (var i = 0; i < bodies.length; i++) { bodies[i].checkAgainst = TYPE.NONE } return this }, setCheckAgainstA: function(bodies) { for (var i = 0; i < bodies.length; i++) { bodies[i].checkAgainst = TYPE.A } return this }, setCheckAgainstB: function(bodies) { for (var i = 0; i < bodies.length; i++) { bodies[i].checkAgainst = TYPE.B } return this }, shutdown: function() { this.removeAllListeners() }, destroy: function() { this.removeAllListeners(); this.scene = null; this.bodies.clear(); this.bodies = null; this.collisionMap = null } }); module.exports = World }, function(module, exports, __webpack_require__) { var Bodies = __webpack_require__(58); var Class = __webpack_require__(0); var Composites = __webpack_require__(438); var Constraint = __webpack_require__(88); var MatterGameObject = __webpack_require__(1055); var MatterImage = __webpack_require__(439); var MatterSprite = __webpack_require__(440); var MatterTileBody = __webpack_require__(205); var PointerConstraint = __webpack_require__(1069); var Factory = new Class({ initialize: function Factory(world) { this.world = world; this.scene = world.scene; this.sys = world.scene.sys }, rectangle: function(x, y, width, height, options) { var body = Bodies.rectangle(x, y, width, height, options); this.world.add(body); return body }, trapezoid: function(x, y, width, height, slope, options) { var body = Bodies.trapezoid(x, y, width, height, slope, options); this.world.add(body); return body }, circle: function(x, y, radius, options, maxSides) { var body = Bodies.circle(x, y, radius, options, maxSides); this.world.add(body); return body }, polygon: function(x, y, sides, radius, options) { var body = Bodies.polygon(x, y, sides, radius, options); this.world.add(body); return body }, fromVertices: function(x, y, vertexSets, options, flagInternal, removeCollinear, minimumArea) { var body = Bodies.fromVertices(x, y, vertexSets, options, flagInternal, removeCollinear, minimumArea); this.world.add(body); return body }, imageStack: function(key, frame, x, y, columns, rows, columnGap, rowGap, options) { if (columnGap === undefined) { columnGap = 0 } if (rowGap === undefined) { rowGap = 0 } if (options === undefined) { options = {} } var world = this.world; var displayList = this.sys.displayList; options.addToWorld = false; var stack = Composites.stack(x, y, columns, rows, columnGap, rowGap, function(x, y) { var image = new MatterImage(world, x, y, key, frame, options); displayList.add(image); return image.body }); world.add(stack); return stack }, stack: function(x, y, columns, rows, columnGap, rowGap, callback) { var stack = Composites.stack(x, y, columns, rows, columnGap, rowGap, callback); this.world.add(stack); return stack }, pyramid: function(x, y, columns, rows, columnGap, rowGap, callback) { var stack = Composites.pyramid(x, y, columns, rows, columnGap, rowGap, callback); this.world.add(stack); return stack }, chain: function(composite, xOffsetA, yOffsetA, xOffsetB, yOffsetB, options) { return Composites.chain(composite, xOffsetA, yOffsetA, xOffsetB, yOffsetB, options) }, mesh: function(composite, columns, rows, crossBrace, options) { return Composites.mesh(composite, columns, rows, crossBrace, options) }, newtonsCradle: function(x, y, number, size, length) { var composite = Composites.newtonsCradle(x, y, number, size, length); this.world.add(composite); return composite }, car: function(x, y, width, height, wheelSize) { var composite = Composites.car(x, y, width, height, wheelSize); this.world.add(composite); return composite }, softBody: function(x, y, columns, rows, columnGap, rowGap, crossBrace, particleRadius, particleOptions, constraintOptions) { var composite = Composites.softBody(x, y, columns, rows, columnGap, rowGap, crossBrace, particleRadius, particleOptions, constraintOptions); this.world.add(composite); return composite }, joint: function(bodyA, bodyB, length, stiffness, options) { return this.constraint(bodyA, bodyB, length, stiffness, options) }, spring: function(bodyA, bodyB, length, stiffness, options) { return this.constraint(bodyA, bodyB, length, stiffness, options) }, constraint: function(bodyA, bodyB, length, stiffness, options) { if (stiffness === undefined) { stiffness = 1 } if (options === undefined) { options = {} } options.bodyA = bodyA.type === "body" ? bodyA : bodyA.body; options.bodyB = bodyB.type === "body" ? bodyB : bodyB.body; options.length = length; options.stiffness = stiffness; var constraint = Constraint.create(options); this.world.add(constraint); return constraint }, worldConstraint: function(bodyB, length, stiffness, options) { if (stiffness === undefined) { stiffness = 1 } if (options === undefined) { options = {} } options.bodyB = bodyB.type === "body" ? bodyB : bodyB.body; options.length = length; options.stiffness = stiffness; var constraint = Constraint.create(options); this.world.add(constraint); return constraint }, mouseSpring: function(options) { return this.pointerConstraint(options) }, pointerConstraint: function(options) { if (options === undefined) { options = {} } if (!options.hasOwnProperty("render")) { options.render = { visible: false } } var pointerConstraint = new PointerConstraint(this.scene, this.world, options); this.world.add(pointerConstraint.constraint); return pointerConstraint }, image: function(x, y, key, frame, options) { var image = new MatterImage(this.world, x, y, key, frame, options); this.sys.displayList.add(image); return image }, tileBody: function(tile, options) { var tileBody = new MatterTileBody(this.world, tile, options); return tileBody }, sprite: function(x, y, key, frame, options) { var sprite = new MatterSprite(this.world, x, y, key, frame, options); this.sys.displayList.add(sprite); this.sys.updateList.add(sprite); return sprite }, gameObject: function(gameObject, options) { return MatterGameObject(this.world, gameObject, options) }, destroy: function() { this.world = null; this.scene = null; this.sys = null } }); module.exports = Factory }, function(module, exports) { module.exports = { decomp: polygonDecomp, quickDecomp: polygonQuickDecomp, isSimple: polygonIsSimple, removeCollinearPoints: polygonRemoveCollinearPoints, removeDuplicatePoints: polygonRemoveDuplicatePoints, makeCCW: polygonMakeCCW }; function lineInt(l1, l2, precision) { precision = precision || 0; var i = [0, 0]; var a1, b1, c1, a2, b2, c2, det; a1 = l1[1][1] - l1[0][1]; b1 = l1[0][0] - l1[1][0]; c1 = a1 * l1[0][0] + b1 * l1[0][1]; a2 = l2[1][1] - l2[0][1]; b2 = l2[0][0] - l2[1][0]; c2 = a2 * l2[0][0] + b2 * l2[0][1]; det = a1 * b2 - a2 * b1; if (!scalar_eq(det, 0, precision)) { i[0] = (b2 * c1 - b1 * c2) / det; i[1] = (a1 * c2 - a2 * c1) / det } return i } function lineSegmentsIntersect(p1, p2, q1, q2) { var dx = p2[0] - p1[0]; var dy = p2[1] - p1[1]; var da = q2[0] - q1[0]; var db = q2[1] - q1[1]; if (da * dy - db * dx === 0) { return false } var s = (dx * (q1[1] - p1[1]) + dy * (p1[0] - q1[0])) / (da * dy - db * dx); var t = (da * (p1[1] - q1[1]) + db * (q1[0] - p1[0])) / (db * dx - da * dy); return s >= 0 && s <= 1 && t >= 0 && t <= 1 } function triangleArea(a, b, c) { return (b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1]) } function isLeft(a, b, c) { return triangleArea(a, b, c) > 0 } function isLeftOn(a, b, c) { return triangleArea(a, b, c) >= 0 } function isRight(a, b, c) { return triangleArea(a, b, c) < 0 } function isRightOn(a, b, c) { return triangleArea(a, b, c) <= 0 } var tmpPoint1 = [], tmpPoint2 = []; function collinear(a, b, c, thresholdAngle) { if (!thresholdAngle) { return triangleArea(a, b, c) === 0 } else { var ab = tmpPoint1, bc = tmpPoint2; ab[0] = b[0] - a[0]; ab[1] = b[1] - a[1]; bc[0] = c[0] - b[0]; bc[1] = c[1] - b[1]; var dot = ab[0] * bc[0] + ab[1] * bc[1], magA = Math.sqrt(ab[0] * ab[0] + ab[1] * ab[1]), magB = Math.sqrt(bc[0] * bc[0] + bc[1] * bc[1]), angle = Math.acos(dot / (magA * magB)); return angle < thresholdAngle } } function sqdist(a, b) { var dx = b[0] - a[0]; var dy = b[1] - a[1]; return dx * dx + dy * dy } function polygonAt(polygon, i) { var s = polygon.length; return polygon[i < 0 ? i % s + s : i % s] } function polygonClear(polygon) { polygon.length = 0 } function polygonAppend(polygon, poly, from, to) { for (var i = from; i < to; i++) { polygon.push(poly[i]) } } function polygonMakeCCW(polygon) { var br = 0, v = polygon; for (var i = 1; i < polygon.length; ++i) { if (v[i][1] < v[br][1] || v[i][1] === v[br][1] && v[i][0] > v[br][0]) { br = i } } if (!isLeft(polygonAt(polygon, br - 1), polygonAt(polygon, br), polygonAt(polygon, br + 1))) { polygonReverse(polygon); return true } else { return false } } function polygonReverse(polygon) { var tmp = []; var N = polygon.length; for (var i = 0; i !== N; i++) { tmp.push(polygon.pop()) } for (var i = 0; i !== N; i++) { polygon[i] = tmp[i] } } function polygonIsReflex(polygon, i) { return isRight(polygonAt(polygon, i - 1), polygonAt(polygon, i), polygonAt(polygon, i + 1)) } var tmpLine1 = [], tmpLine2 = []; function polygonCanSee(polygon, a, b) { var p, dist, l1 = tmpLine1, l2 = tmpLine2; if (isLeftOn(polygonAt(polygon, a + 1), polygonAt(polygon, a), polygonAt(polygon, b)) && isRightOn(polygonAt(polygon, a - 1), polygonAt(polygon, a), polygonAt(polygon, b))) { return false } dist = sqdist(polygonAt(polygon, a), polygonAt(polygon, b)); for (var i = 0; i !== polygon.length; ++i) { if ((i + 1) % polygon.length === a || i === a) { continue } if (isLeftOn(polygonAt(polygon, a), polygonAt(polygon, b), polygonAt(polygon, i + 1)) && isRightOn(polygonAt(polygon, a), polygonAt(polygon, b), polygonAt(polygon, i))) { l1[0] = polygonAt(polygon, a); l1[1] = polygonAt(polygon, b); l2[0] = polygonAt(polygon, i); l2[1] = polygonAt(polygon, i + 1); p = lineInt(l1, l2); if (sqdist(polygonAt(polygon, a), p) < dist) { return false } } } return true } function polygonCanSee2(polygon, a, b) { for (var i = 0; i !== polygon.length; ++i) { if (i === a || i === b || (i + 1) % polygon.length === a || (i + 1) % polygon.length === b) { continue } if (lineSegmentsIntersect(polygonAt(polygon, a), polygonAt(polygon, b), polygonAt(polygon, i), polygonAt(polygon, i + 1))) { return false } } return true } function polygonCopy(polygon, i, j, targetPoly) { var p = targetPoly || []; polygonClear(p); if (i < j) { for (var k = i; k <= j; k++) { p.push(polygon[k]) } } else { for (var k = 0; k <= j; k++) { p.push(polygon[k]) } for (var k = i; k < polygon.length; k++) { p.push(polygon[k]) } } return p } function polygonGetCutEdges(polygon) { var min = [], tmp1 = [], tmp2 = [], tmpPoly = []; var nDiags = Number.MAX_VALUE; for (var i = 0; i < polygon.length; ++i) { if (polygonIsReflex(polygon, i)) { for (var j = 0; j < polygon.length; ++j) { if (polygonCanSee(polygon, i, j)) { tmp1 = polygonGetCutEdges(polygonCopy(polygon, i, j, tmpPoly)); tmp2 = polygonGetCutEdges(polygonCopy(polygon, j, i, tmpPoly)); for (var k = 0; k < tmp2.length; k++) { tmp1.push(tmp2[k]) } if (tmp1.length < nDiags) { min = tmp1; nDiags = tmp1.length; min.push([polygonAt(polygon, i), polygonAt(polygon, j)]) } } } } } return min } function polygonDecomp(polygon) { var edges = polygonGetCutEdges(polygon); if (edges.length > 0) { return polygonSlice(polygon, edges) } else { return [polygon] } } function polygonSlice(polygon, cutEdges) { if (cutEdges.length === 0) { return [polygon] } if (cutEdges instanceof Array && cutEdges.length && cutEdges[0] instanceof Array && cutEdges[0].length === 2 && cutEdges[0][0] instanceof Array) { var polys = [polygon]; for (var i = 0; i < cutEdges.length; i++) { var cutEdge = cutEdges[i]; for (var j = 0; j < polys.length; j++) { var poly = polys[j]; var result = polygonSlice(poly, cutEdge); if (result) { polys.splice(j, 1); polys.push(result[0], result[1]); break } } } return polys } else { var cutEdge = cutEdges; var i = polygon.indexOf(cutEdge[0]); var j = polygon.indexOf(cutEdge[1]); if (i !== -1 && j !== -1) { return [polygonCopy(polygon, i, j), polygonCopy(polygon, j, i)] } else { return false } } } function polygonIsSimple(polygon) { var path = polygon, i; for (i = 0; i < path.length - 1; i++) { for (var j = 0; j < i - 1; j++) { if (lineSegmentsIntersect(path[i], path[i + 1], path[j], path[j + 1])) { return false } } } for (i = 1; i < path.length - 2; i++) { if (lineSegmentsIntersect(path[0], path[path.length - 1], path[i], path[i + 1])) { return false } } return true } function getIntersectionPoint(p1, p2, q1, q2, delta) { delta = delta || 0; var a1 = p2[1] - p1[1]; var b1 = p1[0] - p2[0]; var c1 = a1 * p1[0] + b1 * p1[1]; var a2 = q2[1] - q1[1]; var b2 = q1[0] - q2[0]; var c2 = a2 * q1[0] + b2 * q1[1]; var det = a1 * b2 - a2 * b1; if (!scalar_eq(det, 0, delta)) { return [(b2 * c1 - b1 * c2) / det, (a1 * c2 - a2 * c1) / det] } else { return [0, 0] } } function polygonQuickDecomp(polygon, result, reflexVertices, steinerPoints, delta, maxlevel, level) { maxlevel = maxlevel || 100; level = level || 0; delta = delta || 25; result = typeof result !== "undefined" ? result : []; reflexVertices = reflexVertices || []; steinerPoints = steinerPoints || []; var upperInt = [0, 0], lowerInt = [0, 0], p = [0, 0]; var upperDist = 0, lowerDist = 0, d = 0, closestDist = 0; var upperIndex = 0, lowerIndex = 0, closestIndex = 0; var lowerPoly = [], upperPoly = []; var poly = polygon, v = polygon; if (v.length < 3) { return result } level++; if (level > maxlevel) { console.warn("quickDecomp: max level (" + maxlevel + ") reached."); return result } for (var i = 0; i < polygon.length; ++i) { if (polygonIsReflex(poly, i)) { reflexVertices.push(poly[i]); upperDist = lowerDist = Number.MAX_VALUE; for (var j = 0; j < polygon.length; ++j) { if (isLeft(polygonAt(poly, i - 1), polygonAt(poly, i), polygonAt(poly, j)) && isRightOn(polygonAt(poly, i - 1), polygonAt(poly, i), polygonAt(poly, j - 1))) { p = getIntersectionPoint(polygonAt(poly, i - 1), polygonAt(poly, i), polygonAt(poly, j), polygonAt(poly, j - 1)); if (isRight(polygonAt(poly, i + 1), polygonAt(poly, i), p)) { d = sqdist(poly[i], p); if (d < lowerDist) { lowerDist = d; lowerInt = p; lowerIndex = j } } } if (isLeft(polygonAt(poly, i + 1), polygonAt(poly, i), polygonAt(poly, j + 1)) && isRightOn(polygonAt(poly, i + 1), polygonAt(poly, i), polygonAt(poly, j))) { p = getIntersectionPoint(polygonAt(poly, i + 1), polygonAt(poly, i), polygonAt(poly, j), polygonAt(poly, j + 1)); if (isLeft(polygonAt(poly, i - 1), polygonAt(poly, i), p)) { d = sqdist(poly[i], p); if (d < upperDist) { upperDist = d; upperInt = p; upperIndex = j } } } } if (lowerIndex === (upperIndex + 1) % polygon.length) { p[0] = (lowerInt[0] + upperInt[0]) / 2; p[1] = (lowerInt[1] + upperInt[1]) / 2; steinerPoints.push(p); if (i < upperIndex) { polygonAppend(lowerPoly, poly, i, upperIndex + 1); lowerPoly.push(p); upperPoly.push(p); if (lowerIndex !== 0) { polygonAppend(upperPoly, poly, lowerIndex, poly.length) } polygonAppend(upperPoly, poly, 0, i + 1) } else { if (i !== 0) { polygonAppend(lowerPoly, poly, i, poly.length) } polygonAppend(lowerPoly, poly, 0, upperIndex + 1); lowerPoly.push(p); upperPoly.push(p); polygonAppend(upperPoly, poly, lowerIndex, i + 1) } } else { if (lowerIndex > upperIndex) { upperIndex += polygon.length } closestDist = Number.MAX_VALUE; if (upperIndex < lowerIndex) { return result } for (var j = lowerIndex; j <= upperIndex; ++j) { if (isLeftOn(polygonAt(poly, i - 1), polygonAt(poly, i), polygonAt(poly, j)) && isRightOn(polygonAt(poly, i + 1), polygonAt(poly, i), polygonAt(poly, j))) { d = sqdist(polygonAt(poly, i), polygonAt(poly, j)); if (d < closestDist && polygonCanSee2(poly, i, j)) { closestDist = d; closestIndex = j % polygon.length } } } if (i < closestIndex) { polygonAppend(lowerPoly, poly, i, closestIndex + 1); if (closestIndex !== 0) { polygonAppend(upperPoly, poly, closestIndex, v.length) } polygonAppend(upperPoly, poly, 0, i + 1) } else { if (i !== 0) { polygonAppend(lowerPoly, poly, i, v.length) } polygonAppend(lowerPoly, poly, 0, closestIndex + 1); polygonAppend(upperPoly, poly, closestIndex, i + 1) } } if (lowerPoly.length < upperPoly.length) { polygonQuickDecomp(lowerPoly, result, reflexVertices, steinerPoints, delta, maxlevel, level); polygonQuickDecomp(upperPoly, result, reflexVertices, steinerPoints, delta, maxlevel, level) } else { polygonQuickDecomp(upperPoly, result, reflexVertices, steinerPoints, delta, maxlevel, level); polygonQuickDecomp(lowerPoly, result, reflexVertices, steinerPoints, delta, maxlevel, level) } return result } } result.push(polygon); return result } function polygonRemoveCollinearPoints(polygon, precision) { var num = 0; for (var i = polygon.length - 1; polygon.length > 3 && i >= 0; --i) { if (collinear(polygonAt(polygon, i - 1), polygonAt(polygon, i), polygonAt(polygon, i + 1), precision)) { polygon.splice(i % polygon.length, 1); num++ } } return num } function polygonRemoveDuplicatePoints(polygon, precision) { for (var i = polygon.length - 1; i >= 1; --i) { var pi = polygon[i]; for (var j = i - 1; j >= 0; --j) { if (points_eq(pi, polygon[j], precision)) { polygon.splice(i, 1); continue } } } } function scalar_eq(a, b, precision) { precision = precision || 0; return Math.abs(a - b) <= precision } function points_eq(a, b, precision) { return scalar_eq(a[0], b[0], precision) && scalar_eq(a[1], b[1], precision) } }, function(module, exports, __webpack_require__) { var Composites = {}; module.exports = Composites; var Composite = __webpack_require__(70); var Constraint = __webpack_require__(88); var Common = __webpack_require__(17); var Body = __webpack_require__(25); var Bodies = __webpack_require__(58); (function() { Composites.stack = function(xx, yy, columns, rows, columnGap, rowGap, callback) { var stack = Composite.create({ label: "Stack" }), x = xx, y = yy, lastBody, i = 0; for (var row = 0; row < rows; row++) { var maxHeight = 0; for (var column = 0; column < columns; column++) { var body = callback(x, y, column, row, lastBody, i); if (body) { var bodyHeight = body.bounds.max.y - body.bounds.min.y, bodyWidth = body.bounds.max.x - body.bounds.min.x; if (bodyHeight > maxHeight) maxHeight = bodyHeight; Body.translate(body, { x: bodyWidth * .5, y: bodyHeight * .5 }); x = body.bounds.max.x + columnGap; Composite.addBody(stack, body); lastBody = body; i += 1 } else { x += columnGap } } y += maxHeight + rowGap; x = xx } return stack }; Composites.chain = function(composite, xOffsetA, yOffsetA, xOffsetB, yOffsetB, options) { var bodies = composite.bodies; for (var i = 1; i < bodies.length; i++) { var bodyA = bodies[i - 1], bodyB = bodies[i], bodyAHeight = bodyA.bounds.max.y - bodyA.bounds.min.y, bodyAWidth = bodyA.bounds.max.x - bodyA.bounds.min.x, bodyBHeight = bodyB.bounds.max.y - bodyB.bounds.min.y, bodyBWidth = bodyB.bounds.max.x - bodyB.bounds.min.x; var defaults = { bodyA: bodyA, pointA: { x: bodyAWidth * xOffsetA, y: bodyAHeight * yOffsetA }, bodyB: bodyB, pointB: { x: bodyBWidth * xOffsetB, y: bodyBHeight * yOffsetB } }; var constraint = Common.extend(defaults, options); Composite.addConstraint(composite, Constraint.create(constraint)) } composite.label += " Chain"; return composite }; Composites.mesh = function(composite, columns, rows, crossBrace, options) { var bodies = composite.bodies, row, col, bodyA, bodyB, bodyC; for (row = 0; row < rows; row++) { for (col = 1; col < columns; col++) { bodyA = bodies[col - 1 + row * columns]; bodyB = bodies[col + row * columns]; Composite.addConstraint(composite, Constraint.create(Common.extend({ bodyA: bodyA, bodyB: bodyB }, options))) } if (row > 0) { for (col = 0; col < columns; col++) { bodyA = bodies[col + (row - 1) * columns]; bodyB = bodies[col + row * columns]; Composite.addConstraint(composite, Constraint.create(Common.extend({ bodyA: bodyA, bodyB: bodyB }, options))); if (crossBrace && col > 0) { bodyC = bodies[col - 1 + (row - 1) * columns]; Composite.addConstraint(composite, Constraint.create(Common.extend({ bodyA: bodyC, bodyB: bodyB }, options))) } if (crossBrace && col < columns - 1) { bodyC = bodies[col + 1 + (row - 1) * columns]; Composite.addConstraint(composite, Constraint.create(Common.extend({ bodyA: bodyC, bodyB: bodyB }, options))) } } } } composite.label += " Mesh"; return composite }; Composites.pyramid = function(xx, yy, columns, rows, columnGap, rowGap, callback) { return Composites.stack(xx, yy, columns, rows, columnGap, rowGap, function(x, y, column, row, lastBody, i) { var actualRows = Math.min(rows, Math.ceil(columns / 2)), lastBodyWidth = lastBody ? lastBody.bounds.max.x - lastBody.bounds.min.x : 0; if (row > actualRows) return; row = actualRows - row; var start = row, end = columns - 1 - row; if (column < start || column > end) return; if (i === 1) { Body.translate(lastBody, { x: (column + (columns % 2 === 1 ? 1 : -1)) * lastBodyWidth, y: 0 }) } var xOffset = lastBody ? column * lastBodyWidth : 0; return callback(xx + xOffset + column * columnGap, y, column, row, lastBody, i) }) }; Composites.newtonsCradle = function(xx, yy, number, size, length) { var newtonsCradle = Composite.create({ label: "Newtons Cradle" }); for (var i = 0; i < number; i++) { var separation = 1.9, circle = Bodies.circle(xx + i * (size * separation), yy + length, size, { inertia: Infinity, restitution: 1, friction: 0, frictionAir: 1e-4, slop: 1 }), constraint = Constraint.create({ pointA: { x: xx + i * (size * separation), y: yy }, bodyB: circle }); Composite.addBody(newtonsCradle, circle); Composite.addConstraint(newtonsCradle, constraint) } return newtonsCradle }; Composites.car = function(xx, yy, width, height, wheelSize) { var group = Body.nextGroup(true), wheelBase = 20, wheelAOffset = -width * .5 + wheelBase, wheelBOffset = width * .5 - wheelBase, wheelYOffset = 0; var car = Composite.create({ label: "Car" }), body = Bodies.rectangle(xx, yy, width, height, { collisionFilter: { group: group }, chamfer: { radius: height * .5 }, density: 2e-4 }); var wheelA = Bodies.circle(xx + wheelAOffset, yy + wheelYOffset, wheelSize, { collisionFilter: { group: group }, friction: .8 }); var wheelB = Bodies.circle(xx + wheelBOffset, yy + wheelYOffset, wheelSize, { collisionFilter: { group: group }, friction: .8 }); var axelA = Constraint.create({ bodyB: body, pointB: { x: wheelAOffset, y: wheelYOffset }, bodyA: wheelA, stiffness: 1, length: 0 }); var axelB = Constraint.create({ bodyB: body, pointB: { x: wheelBOffset, y: wheelYOffset }, bodyA: wheelB, stiffness: 1, length: 0 }); Composite.addBody(car, body); Composite.addBody(car, wheelA); Composite.addBody(car, wheelB); Composite.addConstraint(car, axelA); Composite.addConstraint(car, axelB); return car }; Composites.softBody = function(xx, yy, columns, rows, columnGap, rowGap, crossBrace, particleRadius, particleOptions, constraintOptions) { particleOptions = Common.extend({ inertia: Infinity }, particleOptions); constraintOptions = Common.extend({ stiffness: .2, render: { type: "line", anchors: false } }, constraintOptions); var softBody = Composites.stack(xx, yy, columns, rows, columnGap, rowGap, function(x, y) { return Bodies.circle(x, y, particleRadius, particleOptions) }); Composites.mesh(softBody, columns, rows, crossBrace, constraintOptions); softBody.label = "Soft Body"; return softBody } })() }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Components = __webpack_require__(131); var GameObject = __webpack_require__(12); var GetFastValue = __webpack_require__(1); var Image = __webpack_require__(82); var Pipeline = __webpack_require__(109); var Vector2 = __webpack_require__(3); var MatterImage = new Class({ Extends: Image, Mixins: [Components.Bounce, Components.Collision, Components.Force, Components.Friction, Components.Gravity, Components.Mass, Components.Sensor, Components.SetBody, Components.Sleep, Components.Static, Components.Transform, Components.Velocity, Pipeline], initialize: function MatterImage(world, x, y, texture, frame, options) { GameObject.call(this, world.scene, "Image"); this.setTexture(texture, frame); this.setSizeToFrame(); this.setOrigin(); this.world = world; this._tempVec2 = new Vector2(x, y); var shape = GetFastValue(options, "shape", null); if (shape) { this.setBody(shape, options) } else { this.setRectangle(this.width, this.height, options) } this.setPosition(x, y); this.initPipeline("TextureTintPipeline") } }); module.exports = MatterImage }, function(module, exports, __webpack_require__) { var AnimationComponent = __webpack_require__(242); var Class = __webpack_require__(0); var Components = __webpack_require__(131); var GameObject = __webpack_require__(12); var GetFastValue = __webpack_require__(1); var Pipeline = __webpack_require__(109); var Sprite = __webpack_require__(50); var Vector2 = __webpack_require__(3); var MatterSprite = new Class({ Extends: Sprite, Mixins: [Components.Bounce, Components.Collision, Components.Force, Components.Friction, Components.Gravity, Components.Mass, Components.Sensor, Components.SetBody, Components.Sleep, Components.Static, Components.Transform, Components.Velocity, Pipeline], initialize: function MatterSprite(world, x, y, texture, frame, options) { GameObject.call(this, world.scene, "Image"); this.anims = new AnimationComponent(this); this.setTexture(texture, frame); this.setSizeToFrame(); this.setOrigin(); this.world = world; this._tempVec2 = new Vector2(x, y); var shape = GetFastValue(options, "shape", null); if (shape) { this.setBody(shape, options) } else { this.setRectangle(this.width, this.height, options) } this.setPosition(x, y); this.initPipeline("TextureTintPipeline") } }); module.exports = MatterSprite }, function(module, exports, __webpack_require__) { var Matter = {}; module.exports = Matter; var Plugin = __webpack_require__(209); var Common = __webpack_require__(17); (function() { Matter.name = "matter-js"; Matter.version = "0.14.2"; Matter.uses = []; Matter.used = []; Matter.use = function() { Plugin.use(Matter, Array.prototype.slice.call(arguments)) }; Matter.before = function(path, func) { path = path.replace(/^Matter./, ""); return Common.chainPathBefore(Matter, path, func) }; Matter.after = function(path, func) { path = path.replace(/^Matter./, ""); return Common.chainPathAfter(Matter, path, func) } })() }, function(module, exports, __webpack_require__) { var Grid = {}; module.exports = Grid; var Pair = __webpack_require__(132); var Detector = __webpack_require__(206); var Common = __webpack_require__(17); (function() { Grid.create = function(options) { var defaults = { controller: Grid, detector: Detector.collisions, buckets: {}, pairs: {}, pairsList: [], bucketWidth: 48, bucketHeight: 48 }; return Common.extend(defaults, options) }; Grid.update = function(grid, bodies, engine, forceUpdate) { var i, col, row, world = engine.world, buckets = grid.buckets, bucket, bucketId, gridChanged = false; var metrics = engine.metrics; metrics.broadphaseTests = 0; for (i = 0; i < bodies.length; i++) { var body = bodies[i]; if (body.isSleeping && !forceUpdate) continue; if (body.bounds.max.x < world.bounds.min.x || body.bounds.min.x > world.bounds.max.x || body.bounds.max.y < world.bounds.min.y || body.bounds.min.y > world.bounds.max.y) continue; var newRegion = Grid._getRegion(grid, body); if (!body.region || newRegion.id !== body.region.id || forceUpdate) { metrics.broadphaseTests += 1; if (!body.region || forceUpdate) body.region = newRegion; var union = Grid._regionUnion(newRegion, body.region); for (col = union.startCol; col <= union.endCol; col++) { for (row = union.startRow; row <= union.endRow; row++) { bucketId = Grid._getBucketId(col, row); bucket = buckets[bucketId]; var isInsideNewRegion = col >= newRegion.startCol && col <= newRegion.endCol && row >= newRegion.startRow && row <= newRegion.endRow; var isInsideOldRegion = col >= body.region.startCol && col <= body.region.endCol && row >= body.region.startRow && row <= body.region.endRow; if (!isInsideNewRegion && isInsideOldRegion) { if (isInsideOldRegion) { if (bucket) Grid._bucketRemoveBody(grid, bucket, body) } } if (body.region === newRegion || isInsideNewRegion && !isInsideOldRegion || forceUpdate) { if (!bucket) bucket = Grid._createBucket(buckets, bucketId); Grid._bucketAddBody(grid, bucket, body) } } } body.region = newRegion; gridChanged = true } } if (gridChanged) grid.pairsList = Grid._createActivePairsList(grid) }; Grid.clear = function(grid) { grid.buckets = {}; grid.pairs = {}; grid.pairsList = [] }; Grid._regionUnion = function(regionA, regionB) { var startCol = Math.min(regionA.startCol, regionB.startCol), endCol = Math.max(regionA.endCol, regionB.endCol), startRow = Math.min(regionA.startRow, regionB.startRow), endRow = Math.max(regionA.endRow, regionB.endRow); return Grid._createRegion(startCol, endCol, startRow, endRow) }; Grid._getRegion = function(grid, body) { var bounds = body.bounds, startCol = Math.floor(bounds.min.x / grid.bucketWidth), endCol = Math.floor(bounds.max.x / grid.bucketWidth), startRow = Math.floor(bounds.min.y / grid.bucketHeight), endRow = Math.floor(bounds.max.y / grid.bucketHeight); return Grid._createRegion(startCol, endCol, startRow, endRow) }; Grid._createRegion = function(startCol, endCol, startRow, endRow) { return { id: startCol + "," + endCol + "," + startRow + "," + endRow, startCol: startCol, endCol: endCol, startRow: startRow, endRow: endRow } }; Grid._getBucketId = function(column, row) { return "C" + column + "R" + row }; Grid._createBucket = function(buckets, bucketId) { var bucket = buckets[bucketId] = []; return bucket }; Grid._bucketAddBody = function(grid, bucket, body) { for (var i = 0; i < bucket.length; i++) { var bodyB = bucket[i]; if (body.id === bodyB.id || body.isStatic && bodyB.isStatic) continue; var pairId = Pair.id(body, bodyB), pair = grid.pairs[pairId]; if (pair) { pair[2] += 1 } else { grid.pairs[pairId] = [body, bodyB, 1] } } bucket.push(body) }; Grid._bucketRemoveBody = function(grid, bucket, body) { bucket.splice(Common.indexOf(bucket, body), 1); for (var i = 0; i < bucket.length; i++) { var bodyB = bucket[i], pairId = Pair.id(body, bodyB), pair = grid.pairs[pairId]; if (pair) pair[2] -= 1 } }; Grid._createActivePairsList = function(grid) { var pairKeys, pair, pairs = []; pairKeys = Common.keys(grid.pairs); for (var k = 0; k < pairKeys.length; k++) { pair = grid.pairs[pairKeys[k]]; if (pair[2] > 0) { pairs.push(pair) } else { delete grid.pairs[pairKeys[k]] } } return pairs } })() }, function(module, exports, __webpack_require__) { var Pairs = {}; module.exports = Pairs; var Pair = __webpack_require__(132); var Common = __webpack_require__(17); (function() { Pairs._pairMaxIdleLife = 1e3; Pairs.create = function(options) { return Common.extend({ table: {}, list: [], collisionStart: [], collisionActive: [], collisionEnd: [] }, options) }; Pairs.update = function(pairs, collisions, timestamp) { var pairsList = pairs.list, pairsTable = pairs.table, collisionStart = pairs.collisionStart, collisionEnd = pairs.collisionEnd, collisionActive = pairs.collisionActive, collision, pairId, pair, i; collisionStart.length = 0; collisionEnd.length = 0; collisionActive.length = 0; for (i = 0; i < pairsList.length; i++) { pairsList[i].confirmedActive = false } for (i = 0; i < collisions.length; i++) { collision = collisions[i]; if (collision.collided) { pairId = Pair.id(collision.bodyA, collision.bodyB); pair = pairsTable[pairId]; if (pair) { if (pair.isActive) { collisionActive.push(pair) } else { collisionStart.push(pair) } Pair.update(pair, collision, timestamp); pair.confirmedActive = true } else { pair = Pair.create(collision, timestamp); pairsTable[pairId] = pair; collisionStart.push(pair); pairsList.push(pair) } } } for (i = 0; i < pairsList.length; i++) { pair = pairsList[i]; if (pair.isActive && !pair.confirmedActive) { Pair.setActive(pair, false, timestamp); collisionEnd.push(pair) } } }; Pairs.removeOld = function(pairs, timestamp) { var pairsList = pairs.list, pairsTable = pairs.table, indexesToRemove = [], pair, collision, pairIndex, i; for (i = 0; i < pairsList.length; i++) { pair = pairsList[i]; collision = pair.collision; if (collision.bodyA.isSleeping || collision.bodyB.isSleeping) { pair.timeUpdated = timestamp; continue } if (timestamp - pair.timeUpdated > Pairs._pairMaxIdleLife) { indexesToRemove.push(i) } } for (i = 0; i < indexesToRemove.length; i++) { pairIndex = indexesToRemove[i] - i; pair = pairsList[pairIndex]; delete pairsTable[pair.id]; pairsList.splice(pairIndex, 1) } }; Pairs.clear = function(pairs) { pairs.table = {}; pairs.list.length = 0; pairs.collisionStart.length = 0; pairs.collisionActive.length = 0; pairs.collisionEnd.length = 0; return pairs } })() }, function(module, exports, __webpack_require__) { var Resolver = {}; module.exports = Resolver; var Vertices = __webpack_require__(32); var Vector = __webpack_require__(33); var Common = __webpack_require__(17); var Bounds = __webpack_require__(34); (function() { Resolver._restingThresh = 4; Resolver._restingThreshTangent = 6; Resolver._positionDampen = .9; Resolver._positionWarming = .8; Resolver._frictionNormalMultiplier = 5; Resolver.preSolvePosition = function(pairs) { var i, pair, activeCount; for (i = 0; i < pairs.length; i++) { pair = pairs[i]; if (!pair.isActive) continue; activeCount = pair.activeContacts.length; pair.collision.parentA.totalContacts += activeCount; pair.collision.parentB.totalContacts += activeCount } }; Resolver.solvePosition = function(pairs, bodies, timeScale) { var i, normalX, normalY, pair, collision, bodyA, bodyB, normal, separation, penetration, positionImpulseA, positionImpulseB, contactShare, bodyBtoAX, bodyBtoAY, positionImpulse, impulseCoefficient = timeScale * Resolver._positionDampen; for (i = 0; i < bodies.length; i++) { var body = bodies[i]; body.previousPositionImpulse.x = body.positionImpulse.x; body.previousPositionImpulse.y = body.positionImpulse.y } for (i = 0; i < pairs.length; i++) { pair = pairs[i]; if (!pair.isActive || pair.isSensor) continue; collision = pair.collision; bodyA = collision.parentA; bodyB = collision.parentB; normal = collision.normal; positionImpulseA = bodyA.previousPositionImpulse; positionImpulseB = bodyB.previousPositionImpulse; penetration = collision.penetration; bodyBtoAX = positionImpulseB.x - positionImpulseA.x + penetration.x; bodyBtoAY = positionImpulseB.y - positionImpulseA.y + penetration.y; normalX = normal.x; normalY = normal.y; separation = normalX * bodyBtoAX + normalY * bodyBtoAY; pair.separation = separation; positionImpulse = (separation - pair.slop) * impulseCoefficient; if (bodyA.isStatic || bodyB.isStatic) positionImpulse *= 2; if (!(bodyA.isStatic || bodyA.isSleeping)) { contactShare = positionImpulse / bodyA.totalContacts; bodyA.positionImpulse.x += normalX * contactShare; bodyA.positionImpulse.y += normalY * contactShare } if (!(bodyB.isStatic || bodyB.isSleeping)) { contactShare = positionImpulse / bodyB.totalContacts; bodyB.positionImpulse.x -= normalX * contactShare; bodyB.positionImpulse.y -= normalY * contactShare } } }; Resolver.postSolvePosition = function(bodies) { for (var i = 0; i < bodies.length; i++) { var body = bodies[i]; body.totalContacts = 0; if (body.positionImpulse.x !== 0 || body.positionImpulse.y !== 0) { for (var j = 0; j < body.parts.length; j++) { var part = body.parts[j]; Vertices.translate(part.vertices, body.positionImpulse); Bounds.update(part.bounds, part.vertices, body.velocity); part.position.x += body.positionImpulse.x; part.position.y += body.positionImpulse.y } body.positionPrev.x += body.positionImpulse.x; body.positionPrev.y += body.positionImpulse.y; if (Vector.dot(body.positionImpulse, body.velocity) < 0) { body.positionImpulse.x = 0; body.positionImpulse.y = 0 } else { body.positionImpulse.x *= Resolver._positionWarming; body.positionImpulse.y *= Resolver._positionWarming } } } }; Resolver.preSolveVelocity = function(pairs) { var i, j, pair, contacts, collision, bodyA, bodyB, normal, tangent, contact, contactVertex, normalImpulse, tangentImpulse, offset, impulse = Vector._temp[0], tempA = Vector._temp[1]; for (i = 0; i < pairs.length; i++) { pair = pairs[i]; if (!pair.isActive || pair.isSensor) continue; contacts = pair.activeContacts; collision = pair.collision; bodyA = collision.parentA; bodyB = collision.parentB; normal = collision.normal; tangent = collision.tangent; for (j = 0; j < contacts.length; j++) { contact = contacts[j]; contactVertex = contact.vertex; normalImpulse = contact.normalImpulse; tangentImpulse = contact.tangentImpulse; if (normalImpulse !== 0 || tangentImpulse !== 0) { impulse.x = normal.x * normalImpulse + tangent.x * tangentImpulse; impulse.y = normal.y * normalImpulse + tangent.y * tangentImpulse; if (!(bodyA.isStatic || bodyA.isSleeping)) { offset = Vector.sub(contactVertex, bodyA.position, tempA); bodyA.positionPrev.x += impulse.x * bodyA.inverseMass; bodyA.positionPrev.y += impulse.y * bodyA.inverseMass; bodyA.anglePrev += Vector.cross(offset, impulse) * bodyA.inverseInertia } if (!(bodyB.isStatic || bodyB.isSleeping)) { offset = Vector.sub(contactVertex, bodyB.position, tempA); bodyB.positionPrev.x -= impulse.x * bodyB.inverseMass; bodyB.positionPrev.y -= impulse.y * bodyB.inverseMass; bodyB.anglePrev -= Vector.cross(offset, impulse) * bodyB.inverseInertia } } } } }; Resolver.solveVelocity = function(pairs, timeScale) { var timeScaleSquared = timeScale * timeScale, impulse = Vector._temp[0], tempA = Vector._temp[1], tempB = Vector._temp[2], tempC = Vector._temp[3], tempD = Vector._temp[4], tempE = Vector._temp[5]; for (var i = 0; i < pairs.length; i++) { var pair = pairs[i]; if (!pair.isActive || pair.isSensor) continue; var collision = pair.collision, bodyA = collision.parentA, bodyB = collision.parentB, normal = collision.normal, tangent = collision.tangent, contacts = pair.activeContacts, contactShare = 1 / contacts.length; bodyA.velocity.x = bodyA.position.x - bodyA.positionPrev.x; bodyA.velocity.y = bodyA.position.y - bodyA.positionPrev.y; bodyB.velocity.x = bodyB.position.x - bodyB.positionPrev.x; bodyB.velocity.y = bodyB.position.y - bodyB.positionPrev.y; bodyA.angularVelocity = bodyA.angle - bodyA.anglePrev; bodyB.angularVelocity = bodyB.angle - bodyB.anglePrev; for (var j = 0; j < contacts.length; j++) { var contact = contacts[j], contactVertex = contact.vertex, offsetA = Vector.sub(contactVertex, bodyA.position, tempA), offsetB = Vector.sub(contactVertex, bodyB.position, tempB), velocityPointA = Vector.add(bodyA.velocity, Vector.mult(Vector.perp(offsetA), bodyA.angularVelocity), tempC), velocityPointB = Vector.add(bodyB.velocity, Vector.mult(Vector.perp(offsetB), bodyB.angularVelocity), tempD), relativeVelocity = Vector.sub(velocityPointA, velocityPointB, tempE), normalVelocity = Vector.dot(normal, relativeVelocity); var tangentVelocity = Vector.dot(tangent, relativeVelocity), tangentSpeed = Math.abs(tangentVelocity), tangentVelocityDirection = Common.sign(tangentVelocity); var normalImpulse = (1 + pair.restitution) * normalVelocity, normalForce = Common.clamp(pair.separation + normalVelocity, 0, 1) * Resolver._frictionNormalMultiplier; var tangentImpulse = tangentVelocity, maxFriction = Infinity; if (tangentSpeed > pair.friction * pair.frictionStatic * normalForce * timeScaleSquared) { maxFriction = tangentSpeed; tangentImpulse = Common.clamp(pair.friction * tangentVelocityDirection * timeScaleSquared, -maxFriction, maxFriction) } var oAcN = Vector.cross(offsetA, normal), oBcN = Vector.cross(offsetB, normal), share = contactShare / (bodyA.inverseMass + bodyB.inverseMass + bodyA.inverseInertia * oAcN * oAcN + bodyB.inverseInertia * oBcN * oBcN); normalImpulse *= share; tangentImpulse *= share; if (normalVelocity < 0 && normalVelocity * normalVelocity > Resolver._restingThresh * timeScaleSquared) { contact.normalImpulse = 0 } else { var contactNormalImpulse = contact.normalImpulse; contact.normalImpulse = Math.min(contact.normalImpulse + normalImpulse, 0); normalImpulse = contact.normalImpulse - contactNormalImpulse } if (tangentVelocity * tangentVelocity > Resolver._restingThreshTangent * timeScaleSquared) { contact.tangentImpulse = 0 } else { var contactTangentImpulse = contact.tangentImpulse; contact.tangentImpulse = Common.clamp(contact.tangentImpulse + tangentImpulse, -maxFriction, maxFriction); tangentImpulse = contact.tangentImpulse - contactTangentImpulse } impulse.x = normal.x * normalImpulse + tangent.x * tangentImpulse; impulse.y = normal.y * normalImpulse + tangent.y * tangentImpulse; if (!(bodyA.isStatic || bodyA.isSleeping)) { bodyA.positionPrev.x += impulse.x * bodyA.inverseMass; bodyA.positionPrev.y += impulse.y * bodyA.inverseMass; bodyA.anglePrev += Vector.cross(offsetA, impulse) * bodyA.inverseInertia } if (!(bodyB.isStatic || bodyB.isSleeping)) { bodyB.positionPrev.x -= impulse.x * bodyB.inverseMass; bodyB.positionPrev.y -= impulse.y * bodyB.inverseMass; bodyB.anglePrev -= Vector.cross(offsetB, impulse) * bodyB.inverseInertia } } } } })() }, function(module, exports, __webpack_require__) { var Engine = {}; module.exports = Engine; var World = __webpack_require__(210); var Sleeping = __webpack_require__(103); var Resolver = __webpack_require__(444); var Pairs = __webpack_require__(443); var Metrics = __webpack_require__(1071); var Grid = __webpack_require__(442); var Events = __webpack_require__(87); var Composite = __webpack_require__(70); var Constraint = __webpack_require__(88); var Common = __webpack_require__(17); var Body = __webpack_require__(25); (function() { Engine.create = function(element, options) { options = Common.isElement(element) ? options : element; element = Common.isElement(element) ? element : null; options = options || {}; if (element || options.render) { Common.warn("Engine.create: engine.render is deprecated (see docs)") } var defaults = { positionIterations: 6, velocityIterations: 4, constraintIterations: 2, enableSleeping: false, events: [], plugin: {}, timing: { timestamp: 0, timeScale: 1 }, broadphase: { controller: Grid } }; var engine = Common.extend(defaults, options); if (element || engine.render) { var renderDefaults = { element: element, controller: Render }; engine.render = Common.extend(renderDefaults, engine.render) } if (engine.render && engine.render.controller) { engine.render = engine.render.controller.create(engine.render) } if (engine.render) { engine.render.engine = engine } engine.world = options.world || World.create(engine.world); engine.pairs = Pairs.create(); engine.broadphase = engine.broadphase.controller.create(engine.broadphase); engine.metrics = engine.metrics || { extended: false }; engine.metrics = Metrics.create(engine.metrics); return engine }; Engine.update = function(engine, delta, correction) { delta = delta || 1e3 / 60; correction = correction || 1; var world = engine.world, timing = engine.timing, broadphase = engine.broadphase, broadphasePairs = [], i; timing.timestamp += delta * timing.timeScale; var event = { timestamp: timing.timestamp }; Events.trigger(engine, "beforeUpdate", event); var allBodies = Composite.allBodies(world), allConstraints = Composite.allConstraints(world); Metrics.reset(engine.metrics); if (engine.enableSleeping) Sleeping.update(allBodies, timing.timeScale); Engine._bodiesApplyGravity(allBodies, world.gravity); Engine._bodiesUpdate(allBodies, delta, timing.timeScale, correction, world.bounds); Constraint.preSolveAll(allBodies); for (i = 0; i < engine.constraintIterations; i++) { Constraint.solveAll(allConstraints, timing.timeScale) } Constraint.postSolveAll(allBodies); if (broadphase.controller) { if (world.isModified) broadphase.controller.clear(broadphase); broadphase.controller.update(broadphase, allBodies, engine, world.isModified); broadphasePairs = broadphase.pairsList } else { broadphasePairs = allBodies } if (world.isModified) { Composite.setModified(world, false, false, true) } var collisions = broadphase.detector(broadphasePairs, engine); var pairs = engine.pairs, timestamp = timing.timestamp; Pairs.update(pairs, collisions, timestamp); Pairs.removeOld(pairs, timestamp); if (engine.enableSleeping) Sleeping.afterCollisions(pairs.list, timing.timeScale); if (pairs.collisionStart.length > 0) Events.trigger(engine, "collisionStart", { pairs: pairs.collisionStart }); Resolver.preSolvePosition(pairs.list); for (i = 0; i < engine.positionIterations; i++) { Resolver.solvePosition(pairs.list, allBodies, timing.timeScale) } Resolver.postSolvePosition(allBodies); Constraint.preSolveAll(allBodies); for (i = 0; i < engine.constraintIterations; i++) { Constraint.solveAll(allConstraints, timing.timeScale) } Constraint.postSolveAll(allBodies); Resolver.preSolveVelocity(pairs.list); for (i = 0; i < engine.velocityIterations; i++) { Resolver.solveVelocity(pairs.list, timing.timeScale) } if (pairs.collisionActive.length > 0) Events.trigger(engine, "collisionActive", { pairs: pairs.collisionActive }); if (pairs.collisionEnd.length > 0) Events.trigger(engine, "collisionEnd", { pairs: pairs.collisionEnd }); Metrics.update(engine.metrics, engine); Engine._bodiesClearForces(allBodies); Events.trigger(engine, "afterUpdate", event); return engine }; Engine.merge = function(engineA, engineB) { Common.extend(engineA, engineB); if (engineB.world) { engineA.world = engineB.world; Engine.clear(engineA); var bodies = Composite.allBodies(engineA.world); for (var i = 0; i < bodies.length; i++) { var body = bodies[i]; Sleeping.set(body, false); body.id = Common.nextId() } } }; Engine.clear = function(engine) { var world = engine.world; Pairs.clear(engine.pairs); var broadphase = engine.broadphase; if (broadphase.controller) { var bodies = Composite.allBodies(world); broadphase.controller.clear(broadphase); broadphase.controller.update(broadphase, bodies, engine, true) } }; Engine._bodiesClearForces = function(bodies) { for (var i = 0; i < bodies.length; i++) { var body = bodies[i]; body.force.x = 0; body.force.y = 0; body.torque = 0 } }; Engine._bodiesApplyGravity = function(bodies, gravity) { var gravityScale = typeof gravity.scale !== "undefined" ? gravity.scale : .001; if (gravity.x === 0 && gravity.y === 0 || gravityScale === 0) { return } for (var i = 0; i < bodies.length; i++) { var body = bodies[i]; if (body.ignoreGravity || body.isStatic || body.isSleeping) continue; body.force.y += body.mass * gravity.y * gravityScale; body.force.x += body.mass * gravity.x * gravityScale } }; Engine._bodiesUpdate = function(bodies, deltaTime, timeScale, correction, worldBounds) { for (var i = 0; i < bodies.length; i++) { var body = bodies[i]; if (body.isStatic || body.isSleeping) continue; Body.update(body, deltaTime, timeScale, correction) } } })() }, function(module, exports, __webpack_require__) { var Bodies = __webpack_require__(58); var Class = __webpack_require__(0); var Common = __webpack_require__(17); var Composite = __webpack_require__(70); var Engine = __webpack_require__(445); var EventEmitter = __webpack_require__(11); var GetFastValue = __webpack_require__(1); var GetValue = __webpack_require__(4); var MatterBody = __webpack_require__(25); var MatterEvents = __webpack_require__(87); var MatterTileBody = __webpack_require__(205); var MatterWorld = __webpack_require__(210); var Vector = __webpack_require__(33); var World = new Class({ Extends: EventEmitter, initialize: function World(scene, config) { EventEmitter.call(this); this.scene = scene; this.engine = Engine.create(config); this.localWorld = this.engine.world; var gravity = GetValue(config, "gravity", null); if (gravity) { this.setGravity(gravity.x, gravity.y, gravity.scale) } this.walls = { left: null, right: null, top: null, bottom: null }; if (GetFastValue(config, "setBounds", false)) { var boundsConfig = config["setBounds"]; if (typeof boundsConfig === "boolean") { this.setBounds() } else { var x = GetFastValue(boundsConfig, "x", 0); var y = GetFastValue(boundsConfig, "y", 0); var width = GetFastValue(boundsConfig, "width", scene.sys.game.config.width); var height = GetFastValue(boundsConfig, "height", scene.sys.game.config.height); var thickness = GetFastValue(boundsConfig, "thickness", 64); var left = GetFastValue(boundsConfig, "left", true); var right = GetFastValue(boundsConfig, "right", true); var top = GetFastValue(boundsConfig, "top", true); var bottom = GetFastValue(boundsConfig, "bottom", true); this.setBounds(x, y, width, height, thickness, left, right, top, bottom) } } this.enabled = GetValue(config, "enabled", true); this.correction = GetValue(config, "correction", 1); this.getDelta = GetValue(config, "getDelta", this.update60Hz); this.autoUpdate = GetValue(config, "autoUpdate", true); this.drawDebug = GetValue(config, "debug", false); this.debugGraphic; this.defaults = { debugShowBody: GetFastValue(config, "debugShowBody", true), debugShowStaticBody: GetFastValue(config, "debugShowStaticBody", true), debugShowVelocity: GetFastValue(config, "debugShowVelocity", true), bodyDebugColor: GetFastValue(config, "debugBodyColor", 16711935), bodyDebugFillColor: GetFastValue(config, "bodyDebugFillColor", 14919651), staticBodyDebugColor: GetFastValue(config, "debugBodyColor", 255), velocityDebugColor: GetFastValue(config, "debugVelocityColor", 65280), debugShowJoint: GetFastValue(config, "debugShowJoint", true), jointDebugColor: GetFastValue(config, "debugJointColor", 0), debugWireframes: GetFastValue(config, "debugWireframes", true), debugShowInternalEdges: GetFastValue(config, "debugShowInternalEdges", false), debugShowConvexHulls: GetFastValue(config, "debugShowConvexHulls", false), debugConvexHullColor: GetFastValue(config, "debugConvexHullColor", 11184810), debugShowSleeping: GetFastValue(config, "debugShowSleeping", false) }; if (this.drawDebug) { this.createDebugGraphic() } this.setEventsProxy() }, setEventsProxy: function() { var _this = this; var engine = this.engine; MatterEvents.on(engine, "beforeUpdate", function(event) { _this.emit("beforeupdate", event) }); MatterEvents.on(engine, "afterUpdate", function(event) { _this.emit("afterupdate", event) }); MatterEvents.on(engine, "collisionStart", function(event) { var pairs = event.pairs; var bodyA; var bodyB; if (pairs.length > 0) { bodyA = pairs[0].bodyA; bodyB = pairs[0].bodyB } _this.emit("collisionstart", event, bodyA, bodyB) }); MatterEvents.on(engine, "collisionActive", function(event) { var pairs = event.pairs; var bodyA; var bodyB; if (pairs.length > 0) { bodyA = pairs[0].bodyA; bodyB = pairs[0].bodyB } _this.emit("collisionactive", event, bodyA, bodyB) }); MatterEvents.on(engine, "collisionEnd", function(event) { var pairs = event.pairs; var bodyA; var bodyB; if (pairs.length > 0) { bodyA = pairs[0].bodyA; bodyB = pairs[0].bodyB } _this.emit("collisionend", event, bodyA, bodyB) }) }, setBounds: function(x, y, width, height, thickness, left, right, top, bottom) { if (x === undefined) { x = 0 } if (y === undefined) { y = 0 } if (width === undefined) { width = this.scene.sys.game.config.width } if (height === undefined) { height = this.scene.sys.game.config.height } if (thickness === undefined) { thickness = 128 } if (left === undefined) { left = true } if (right === undefined) { right = true } if (top === undefined) { top = true } if (bottom === undefined) { bottom = true } this.updateWall(left, "left", x - thickness, y, thickness, height); this.updateWall(right, "right", x + width, y, thickness, height); this.updateWall(top, "top", x, y - thickness, width, thickness); this.updateWall(bottom, "bottom", x, y + height, width, thickness); return this }, updateWall: function(add, position, x, y, width, height) { var wall = this.walls[position]; if (add) { if (wall) { MatterWorld.remove(this.localWorld, wall) } x += width / 2; y += height / 2; this.walls[position] = this.create(x, y, width, height, { isStatic: true, friction: 0, frictionStatic: 0 }) } else { if (wall) { MatterWorld.remove(this.localWorld, wall) } this.walls[position] = null } }, createDebugGraphic: function() { var graphic = this.scene.sys.add.graphics({ x: 0, y: 0 }); graphic.setDepth(Number.MAX_VALUE); this.debugGraphic = graphic; this.drawDebug = true; return graphic }, disableGravity: function() { this.localWorld.gravity.x = 0; this.localWorld.gravity.y = 0; this.localWorld.gravity.scale = 0; return this }, setGravity: function(x, y, scale) { if (x === undefined) { x = 0 } if (y === undefined) { y = 1 } this.localWorld.gravity.x = x; this.localWorld.gravity.y = y; if (scale !== undefined) { this.localWorld.gravity.scale = scale } return this }, create: function(x, y, width, height, options) { var body = Bodies.rectangle(x, y, width, height, options); MatterWorld.add(this.localWorld, body); return body }, add: function(object) { MatterWorld.add(this.localWorld, object); return this }, remove: function(object, deep) { var body = object.body ? object.body : object; Composite.removeBody(this.localWorld, body, deep); return this }, removeConstraint: function(constraint, deep) { Composite.remove(this.localWorld, constraint, deep); return this }, convertTilemapLayer: function(tilemapLayer, options) { var layerData = tilemapLayer.layer; var tiles = tilemapLayer.getTilesWithin(0, 0, layerData.width, layerData.height, { isColliding: true }); this.convertTiles(tiles, options); return this }, convertTiles: function(tiles, options) { if (tiles.length === 0) { return this } for (var i = 0; i < tiles.length; i++) { new MatterTileBody(this, tiles[i], options) } return this }, nextGroup: function(isNonColliding) { return MatterBody.nextGroup(isNonColliding) }, nextCategory: function() { return MatterBody.nextCategory() }, pause: function() { this.enabled = false; this.emit("pause"); return this }, resume: function() { this.enabled = true; this.emit("resume"); return this }, update: function(time, delta) { if (this.enabled && this.autoUpdate) { Engine.update(this.engine, this.getDelta(time, delta), this.correction) } }, step: function(delta, correction) { Engine.update(this.engine, delta, correction) }, update60Hz: function() { return 1e3 / 60 }, update30Hz: function() { return 1e3 / 30 }, postUpdate: function() { if (!this.drawDebug) { return } this.debugGraphic.clear(); var bodies = Composite.allBodies(this.localWorld); if (this.defaults.debugWireframes) { if (this.defaults.debugShowConvexHulls) { this.renderConvexHulls(bodies) } this.renderWireframes(bodies) } else { this.renderBodies(bodies) } if (this.defaults.debugShowJoint) { this.renderJoints() } }, renderConvexHulls: function(bodies) { var graphics = this.debugGraphic; graphics.lineStyle(1, this.defaults.debugConvexHullColor); graphics.beginPath(); for (var i = 0; i < bodies.length; i++) { var body = bodies[i]; if (!body.render.visible || body.parts.length === 1) { continue } graphics.moveTo(body.vertices[0].x, body.vertices[0].y); for (var j = 1; j < body.vertices.length; j++) { graphics.lineTo(body.vertices[j].x, body.vertices[j].y) } graphics.lineTo(body.vertices[0].x, body.vertices[0].y) } graphics.strokePath() }, renderWireframes: function(bodies) { var graphics = this.debugGraphic; var showInternalEdges = this.defaults.debugShowInternalEdges; graphics.lineStyle(1, this.defaults.bodyDebugColor); graphics.beginPath(); for (var i = 0; i < bodies.length; i++) { var body = bodies[i]; if (!body.render.visible) { continue } for (var k = body.parts.length > 1 ? 1 : 0; k < body.parts.length; k++) { var part = body.parts[k]; var vertLength = part.vertices.length; graphics.moveTo(part.vertices[0].x, part.vertices[0].y); for (var j = 1; j < vertLength; j++) { if (!part.vertices[j - 1].isInternal || showInternalEdges) { graphics.lineTo(part.vertices[j].x, part.vertices[j].y) } else { graphics.moveTo(part.vertices[j].x, part.vertices[j].y) } if (part.vertices[j].isInternal && !showInternalEdges) { graphics.moveTo(part.vertices[(j + 1) % vertLength].x, part.vertices[(j + 1) % vertLength].y) } } graphics.lineTo(part.vertices[0].x, part.vertices[0].y) } } graphics.strokePath() }, renderBodies: function(bodies) { var graphics = this.debugGraphic; var showInternalEdges = this.defaults.debugShowInternalEdges || !this.defaults.debugWireframes; var showSleeping = this.defaults.debugShowSleeping; var wireframes = this.defaults.debugWireframes; var body; var part; var i; var k; for (i = 0; i < bodies.length; i++) { body = bodies[i]; if (!body.render.visible) { continue } for (k = body.parts.length > 1 ? 1 : 0; k < body.parts.length; k++) { part = body.parts[k]; if (!part.render.visible) { continue } if (showSleeping && body.isSleeping) { graphics.lineStyle(1, this.defaults.bodyDebugColor, .5 * part.render.opacity); graphics.fillStyle(this.defaults.bodyDebugColor, .5 * part.render.opacity) } else { graphics.lineStyle(1, this.defaults.bodyDebugColor, part.render.opacity); graphics.fillStyle(this.defaults.bodyDebugColor, part.render.opacity) } if (part.circleRadius) { graphics.beginPath(); graphics.arc(part.position.x, part.position.y, part.circleRadius, 0, 2 * Math.PI) } else { graphics.beginPath(); graphics.moveTo(part.vertices[0].x, part.vertices[0].y); var vertLength = part.vertices.length; for (var j = 1; j < vertLength; j++) { if (!part.vertices[j - 1].isInternal || showInternalEdges) { graphics.lineTo(part.vertices[j].x, part.vertices[j].y) } else { graphics.moveTo(part.vertices[j].x, part.vertices[j].y) } if (part.vertices[j].isInternal && !showInternalEdges) { graphics.moveTo(part.vertices[(j + 1) % part.vertices.length].x, part.vertices[(j + 1) % part.vertices.length].y) } } graphics.lineTo(part.vertices[0].x, part.vertices[0].y); graphics.closePath() } if (!wireframes) { graphics.fillPath() } else { graphics.strokePath() } } } }, renderJoints: function() { var graphics = this.debugGraphic; graphics.lineStyle(2, this.defaults.jointDebugColor); var constraints = Composite.allConstraints(this.localWorld); for (var i = 0; i < constraints.length; i++) { var constraint = constraints[i]; if (!constraint.render.visible || !constraint.pointA || !constraint.pointB) { continue } if (constraint.render.lineWidth) { graphics.lineStyle(constraint.render.lineWidth, Common.colorToNumber(constraint.render.strokeStyle)) } var bodyA = constraint.bodyA; var bodyB = constraint.bodyB; var start; var end; if (bodyA) { start = Vector.add(bodyA.position, constraint.pointA) } else { start = constraint.pointA } if (constraint.render.type === "pin") { graphics.beginPath(); graphics.arc(start.x, start.y, 3, 0, 2 * Math.PI); graphics.closePath() } else { if (bodyB) { end = Vector.add(bodyB.position, constraint.pointB) } else { end = constraint.pointB } graphics.beginPath(); graphics.moveTo(start.x, start.y); if (constraint.render.type === "spring") { var delta = Vector.sub(end, start); var normal = Vector.perp(Vector.normalise(delta)); var coils = Math.ceil(Common.clamp(constraint.length / 5, 12, 20)); var offset; for (var j = 1; j < coils; j += 1) { offset = j % 2 === 0 ? 1 : -1; graphics.lineTo(start.x + delta.x * (j / coils) + normal.x * offset * 4, start.y + delta.y * (j / coils) + normal.y * offset * 4) } } graphics.lineTo(end.x, end.y) } if (constraint.render.lineWidth) { graphics.strokePath() } if (constraint.render.anchors) { graphics.fillStyle(Common.colorToNumber(constraint.render.strokeStyle)); graphics.beginPath(); graphics.arc(start.x, start.y, 6, 0, 2 * Math.PI); graphics.arc(end.x, end.y, 6, 0, 2 * Math.PI); graphics.closePath(); graphics.fillPath() } } }, fromPath: function(path, points) { if (points === undefined) { points = [] } var pathPattern = /L?\s*([\-\d\.e]+)[\s,]*([\-\d\.e]+)*/gi; path.replace(pathPattern, function(match, x, y) { points.push({ x: parseFloat(x), y: parseFloat(y) }) }); return points }, shutdown: function() { MatterEvents.off(this.engine); this.removeAllListeners(); MatterWorld.clear(this.localWorld, false); Engine.clear(this.engine); if (this.drawDebug) { this.debugGraphic.destroy() } }, destroy: function() { this.shutdown() } }); module.exports = World }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var BasePlugin = new Class({ initialize: function BasePlugin(pluginManager) { this.pluginManager = pluginManager; this.game = pluginManager.game; this.scene; this.systems }, init: function() {}, start: function() {}, stop: function() {}, boot: function() {}, destroy: function() { this.pluginManager = null; this.game = null; this.scene = null; this.systems = null } }); module.exports = BasePlugin }, function(module, exports, __webpack_require__) { var GetTilesWithin = __webpack_require__(21); var ReplaceByIndex = function(findIndex, newIndex, tileX, tileY, width, height, layer) { var tiles = GetTilesWithin(tileX, tileY, width, height, null, layer); for (var i = 0; i < tiles.length; i++) { if (tiles[i] && tiles[i].index === findIndex) { tiles[i].index = newIndex } } }; module.exports = ReplaceByIndex }, function(module, exports, __webpack_require__) { var IsInLayerBounds = __webpack_require__(104); var HasTileAt = function(tileX, tileY, layer) { if (IsInLayerBounds(tileX, tileY, layer)) { var tile = layer.data[tileY][tileX]; return tile !== null && tile.index > -1 } else { return false } }; module.exports = HasTileAt }, function(module, exports, __webpack_require__) { var Tile = __webpack_require__(72); var IsInLayerBounds = __webpack_require__(104); var CalculateFacesAt = __webpack_require__(211); var RemoveTileAt = function(tileX, tileY, replaceWithNull, recalculateFaces, layer) { if (replaceWithNull === undefined) { replaceWithNull = false } if (recalculateFaces === undefined) { recalculateFaces = true } if (!IsInLayerBounds(tileX, tileY, layer)) { return null } var tile = layer.data[tileY][tileX]; if (tile === null) { return null } else { layer.data[tileY][tileX] = replaceWithNull ? null : new Tile(layer, -1, tileX, tileY, tile.width, tile.height) } if (recalculateFaces && tile && tile.collides) { CalculateFacesAt(tileX, tileY, layer) } return tile }; module.exports = RemoveTileAt }, function(module, exports, __webpack_require__) { var Formats = __webpack_require__(31); var Parse2DArray = __webpack_require__(214); var ParseCSV = __webpack_require__(452); var ParseJSONTiled = __webpack_require__(453); var ParseWeltmeister = __webpack_require__(458); var Parse = function(name, mapFormat, data, tileWidth, tileHeight, insertNull) { var newMap; switch (mapFormat) { case Formats.ARRAY_2D: newMap = Parse2DArray(name, data, tileWidth, tileHeight, insertNull); break; case Formats.CSV: newMap = ParseCSV(name, data, tileWidth, tileHeight, insertNull); break; case Formats.TILED_JSON: newMap = ParseJSONTiled(name, data, insertNull); break; case Formats.WELTMEISTER: newMap = ParseWeltmeister(name, data, insertNull); break; default: console.warn("Unrecognized tilemap data format: " + mapFormat); newMap = null } return newMap }; module.exports = Parse }, function(module, exports, __webpack_require__) { var Formats = __webpack_require__(31); var Parse2DArray = __webpack_require__(214); var ParseCSV = function(name, data, tileWidth, tileHeight, insertNull) { var array2D = data.trim().split("\n").map(function(row) { return row.split(",") }); var map = Parse2DArray(name, array2D, tileWidth, tileHeight, insertNull); map.format = Formats.CSV; return map }; module.exports = ParseCSV }, function(module, exports, __webpack_require__) { var Formats = __webpack_require__(31); var MapData = __webpack_require__(106); var ParseTileLayers = __webpack_require__(1120); var ParseImageLayers = __webpack_require__(1122); var ParseTilesets = __webpack_require__(1123); var ParseObjectLayers = __webpack_require__(1125); var BuildTilesetIndex = __webpack_require__(1126); var AssignTileProperties = __webpack_require__(1127); var ParseJSONTiled = function(name, json, insertNull) { if (json.orientation !== "orthogonal") { console.warn("Only orthogonal map types are supported in this version of Phaser"); return null } var mapData = new MapData({ width: json.width, height: json.height, name: name, tileWidth: json.tilewidth, tileHeight: json.tileheight, orientation: json.orientation, format: Formats.TILED_JSON, version: json.version, properties: json.properties, renderOrder: json.renderorder }); mapData.layers = ParseTileLayers(json, insertNull); mapData.images = ParseImageLayers(json); var sets = ParseTilesets(json); mapData.tilesets = sets.tilesets; mapData.imageCollections = sets.imageCollections; mapData.objects = ParseObjectLayers(json); mapData.tiles = BuildTilesetIndex(mapData); AssignTileProperties(mapData); return mapData }; module.exports = ParseJSONTiled }, function(module, exports) { var FLIPPED_HORIZONTAL = 2147483648; var FLIPPED_VERTICAL = 1073741824; var FLIPPED_ANTI_DIAGONAL = 536870912; var ParseGID = function(gid) { var flippedHorizontal = Boolean(gid & FLIPPED_HORIZONTAL); var flippedVertical = Boolean(gid & FLIPPED_VERTICAL); var flippedAntiDiagonal = Boolean(gid & FLIPPED_ANTI_DIAGONAL); gid = gid & ~(FLIPPED_HORIZONTAL | FLIPPED_VERTICAL | FLIPPED_ANTI_DIAGONAL); var rotation = 0; var flipped = false; if (flippedHorizontal && flippedVertical && flippedAntiDiagonal) { rotation = Math.PI / 2; flipped = true } else if (flippedHorizontal && flippedVertical && !flippedAntiDiagonal) { rotation = Math.PI; flipped = false } else if (flippedHorizontal && !flippedVertical && flippedAntiDiagonal) { rotation = Math.PI / 2; flipped = false } else if (flippedHorizontal && !flippedVertical && !flippedAntiDiagonal) { rotation = 0; flipped = true } else if (!flippedHorizontal && flippedVertical && flippedAntiDiagonal) { rotation = 3 * Math.PI / 2; flipped = false } else if (!flippedHorizontal && flippedVertical && !flippedAntiDiagonal) { rotation = Math.PI; flipped = true } else if (!flippedHorizontal && !flippedVertical && flippedAntiDiagonal) { rotation = 3 * Math.PI / 2; flipped = true } else if (!flippedHorizontal && !flippedVertical && !flippedAntiDiagonal) { rotation = 0; flipped = false } return { gid: gid, flippedHorizontal: flippedHorizontal, flippedVertical: flippedVertical, flippedAntiDiagonal: flippedAntiDiagonal, rotation: rotation, flipped: flipped } }; module.exports = ParseGID }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var ImageCollection = new Class({ initialize: function ImageCollection(name, firstgid, width, height, margin, spacing, properties) { if (width === undefined || width <= 0) { width = 32 } if (height === undefined || height <= 0) { height = 32 } if (margin === undefined) { margin = 0 } if (spacing === undefined) { spacing = 0 } this.name = name; this.firstgid = firstgid | 0; this.imageWidth = width | 0; this.imageHeight = height | 0; this.imageMargin = margin | 0; this.imageSpacing = spacing | 0; this.properties = properties || {}; this.images = []; this.total = 0 }, containsImageIndex: function(imageIndex) { return imageIndex >= this.firstgid && imageIndex < this.firstgid + this.total }, addImage: function(gid, image) { this.images.push({ gid: gid, image: image }); this.total++; return this } }); module.exports = ImageCollection }, function(module, exports, __webpack_require__) { var Pick = __webpack_require__(1124); var ParseGID = __webpack_require__(454); var copyPoints = function(p) { return { x: p.x, y: p.y } }; var commonObjectProps = ["id", "name", "type", "rotation", "properties", "visible", "x", "y", "width", "height"]; var ParseObject = function(tiledObject, offsetX, offsetY) { if (offsetX === undefined) { offsetX = 0 } if (offsetY === undefined) { offsetY = 0 } var parsedObject = Pick(tiledObject, commonObjectProps); parsedObject.x += offsetX; parsedObject.y += offsetY; if (tiledObject.gid) { var gidInfo = ParseGID(tiledObject.gid); parsedObject.gid = gidInfo.gid; parsedObject.flippedHorizontal = gidInfo.flippedHorizontal; parsedObject.flippedVertical = gidInfo.flippedVertical; parsedObject.flippedAntiDiagonal = gidInfo.flippedAntiDiagonal } else if (tiledObject.polyline) { parsedObject.polyline = tiledObject.polyline.map(copyPoints) } else if (tiledObject.polygon) { parsedObject.polygon = tiledObject.polygon.map(copyPoints) } else if (tiledObject.ellipse) { parsedObject.ellipse = tiledObject.ellipse; parsedObject.width = tiledObject.width; parsedObject.height = tiledObject.height } else if (tiledObject.text) { parsedObject.width = tiledObject.width; parsedObject.height = tiledObject.height; parsedObject.text = tiledObject.text } else { parsedObject.rectangle = true; parsedObject.width = tiledObject.width; parsedObject.height = tiledObject.height } return parsedObject }; module.exports = ParseObject }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var GetFastValue = __webpack_require__(1); var ObjectLayer = new Class({ initialize: function ObjectLayer(config) { if (config === undefined) { config = {} } this.name = GetFastValue(config, "name", "object layer"); this.opacity = GetFastValue(config, "opacity", 1); this.properties = GetFastValue(config, "properties", {}); this.propertyTypes = GetFastValue(config, "propertytypes", {}); this.type = GetFastValue(config, "type", "objectgroup"); this.visible = GetFastValue(config, "visible", true); this.objects = GetFastValue(config, "objects", []) } }); module.exports = ObjectLayer }, function(module, exports, __webpack_require__) { var Formats = __webpack_require__(31); var MapData = __webpack_require__(106); var ParseTileLayers = __webpack_require__(1128); var ParseTilesets = __webpack_require__(1129); var ParseWeltmeister = function(name, json, insertNull) { if (json.layer.length === 0) { console.warn("No layers found in the Weltmeister map: " + name); return null } var width = 0; var height = 0; for (var i = 0; i < json.layer.length; i++) { if (json.layer[i].width > width) { width = json.layer[i].width } if (json.layer[i].height > height) { height = json.layer[i].height } } var mapData = new MapData({ width: width, height: height, name: name, tileWidth: json.layer[0].tilesize, tileHeight: json.layer[0].tilesize, format: Formats.WELTMEISTER }); mapData.layers = ParseTileLayers(json, insertNull); mapData.tilesets = ParseTilesets(json); return mapData }; module.exports = ParseWeltmeister }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var DegToRad = __webpack_require__(36); var DynamicTilemapLayer = __webpack_require__(460); var Extend = __webpack_require__(19); var Formats = __webpack_require__(31); var LayerData = __webpack_require__(105); var Rotate = __webpack_require__(411); var StaticTilemapLayer = __webpack_require__(461); var Tile = __webpack_require__(72); var TilemapComponents = __webpack_require__(133); var Tileset = __webpack_require__(137); var Tilemap = new Class({ initialize: function Tilemap(scene, mapData) { this.scene = scene; this.tileWidth = mapData.tileWidth; this.tileHeight = mapData.tileHeight; this.width = mapData.width; this.height = mapData.height; this.orientation = mapData.orientation; this.renderOrder = mapData.renderOrder; this.format = mapData.format; this.version = mapData.version; this.properties = mapData.properties; this.widthInPixels = mapData.widthInPixels; this.heightInPixels = mapData.heightInPixels; this.imageCollections = mapData.imageCollections; this.images = mapData.images; this.layers = mapData.layers; this.tilesets = mapData.tilesets; this.objects = mapData.objects; this.currentLayerIndex = 0 }, setRenderOrder: function(renderOrder) { var orders = ["right-down", "left-down", "right-up", "left-up"]; if (typeof renderOrder === "number") { renderOrder = orders[renderOrder] } if (orders.indexOf(renderOrder) > -1) { this.renderOrder = renderOrder } return this }, addTilesetImage: function(tilesetName, key, tileWidth, tileHeight, tileMargin, tileSpacing, gid) { if (tilesetName === undefined) { return null } if (key === undefined || key === null) { key = tilesetName } if (!this.scene.sys.textures.exists(key)) { console.warn("Invalid Tileset Image: " + key); return null } var texture = this.scene.sys.textures.get(key); var index = this.getTilesetIndex(tilesetName); if (index === null && this.format === Formats.TILED_JSON) { console.warn("No data found for Tileset: " + tilesetName); return null } var tileset = this.tilesets[index]; if (tileset) { tileset.setTileSize(tileWidth, tileHeight); tileset.setSpacing(tileMargin, tileSpacing); tileset.setImage(texture); return tileset } if (tileWidth === undefined) { tileWidth = this.tileWidth } if (tileHeight === undefined) { tileHeight = this.tileHeight } if (tileMargin === undefined) { tileMargin = 0 } if (tileSpacing === undefined) { tileSpacing = 0 } if (gid === undefined) { gid = 0 } tileset = new Tileset(tilesetName, gid, tileWidth, tileHeight, tileMargin, tileSpacing); tileset.setImage(texture); this.tilesets.push(tileset); return tileset }, convertLayerToStatic: function(layer) { layer = this.getLayer(layer); if (layer === null) { return null } var dynamicLayer = layer.tilemapLayer; if (!dynamicLayer || !(dynamicLayer instanceof DynamicTilemapLayer)) { return null } var staticLayer = new StaticTilemapLayer(dynamicLayer.scene, dynamicLayer.tilemap, dynamicLayer.layerIndex, dynamicLayer.tileset, dynamicLayer.x, dynamicLayer.y); this.scene.sys.displayList.add(staticLayer); dynamicLayer.destroy(); return staticLayer }, copy: function(srcTileX, srcTileY, width, height, destTileX, destTileY, recalculateFaces, layer) { layer = this.getLayer(layer); if (this._isStaticCall(layer, "copy")) { return this } if (layer !== null) { TilemapComponents.Copy(srcTileX, srcTileY, width, height, destTileX, destTileY, recalculateFaces, layer) } return this }, createBlankDynamicLayer: function(name, tileset, x, y, width, height, tileWidth, tileHeight) { if (tileWidth === undefined) { tileWidth = tileset.tileWidth } if (tileHeight === undefined) { tileHeight = tileset.tileHeight } if (width === undefined) { width = this.width } if (height === undefined) { height = this.height } if (x === undefined) { x = 0 } if (y === undefined) { y = 0 } var index = this.getLayerIndex(name); if (index !== null) { console.warn("Invalid Tilemap Layer ID: " + name); return null } var layerData = new LayerData({ name: name, tileWidth: tileWidth, tileHeight: tileHeight, width: width, height: height }); var row; for (var tileY = 0; tileY < height; tileY++) { row = []; for (var tileX = 0; tileX < width; tileX++) { row.push(new Tile(layerData, -1, tileX, tileY, tileWidth, tileHeight, this.tileWidth, this.tileHeight)) } layerData.data.push(row) } this.layers.push(layerData); this.currentLayerIndex = this.layers.length - 1; var dynamicLayer = new DynamicTilemapLayer(this.scene, this, this.currentLayerIndex, tileset, x, y); dynamicLayer.setRenderOrder(this.renderOrder); this.scene.sys.displayList.add(dynamicLayer); return dynamicLayer }, createDynamicLayer: function(layerID, tileset, x, y) { var index = this.getLayerIndex(layerID); if (index === null) { console.warn("Invalid Tilemap Layer ID: " + layerID); return null } var layerData = this.layers[index]; if (layerData.tilemapLayer) { console.warn("Tilemap Layer ID already exists:" + layerID); return null } this.currentLayerIndex = index; if (x === undefined && this.layers[index].x) { x = this.layers[index].x } if (y === undefined && this.layers[index].y) { y = this.layers[index].y } var layer = new DynamicTilemapLayer(this.scene, this, index, tileset, x, y); layer.setRenderOrder(this.renderOrder); this.scene.sys.displayList.add(layer); return layer }, createFromObjects: function(name, id, spriteConfig, scene) { if (spriteConfig === undefined) { spriteConfig = {} } if (scene === undefined) { scene = this.scene } var objectLayer = this.getObjectLayer(name); if (!objectLayer) { console.warn("Cannot create from object. Invalid objectgroup name given: " + name); return } var objects = objectLayer.objects; var sprites = []; for (var i = 0; i < objects.length; i++) { var found = false; var obj = objects[i]; if (obj.gid !== undefined && typeof id === "number" && obj.gid === id || obj.id !== undefined && typeof id === "number" && obj.id === id || obj.name !== undefined && typeof id === "string" && obj.name === id) { found = true } if (found) { var config = Extend({}, spriteConfig, obj.properties); config.x = obj.x; config.y = obj.y; var sprite = this.scene.make.sprite(config); sprite.name = obj.name; if (obj.width) { sprite.displayWidth = obj.width } if (obj.height) { sprite.displayHeight = obj.height } var offset = { x: sprite.originX * sprite.displayWidth, y: (sprite.originY - 1) * sprite.displayHeight }; if (obj.rotation) { var angle = DegToRad(obj.rotation); Rotate(offset, angle); sprite.rotation = angle } sprite.x += offset.x; sprite.y += offset.y; if (obj.flippedHorizontal !== undefined || obj.flippedVertical !== undefined) { sprite.setFlip(obj.flippedHorizontal, obj.flippedVertical) } if (!obj.visible) { sprite.visible = false } for (var key in obj.properties) { if (sprite.hasOwnProperty(key)) { continue } sprite.setData(key, obj.properties[key]) } sprites.push(sprite) } } return sprites }, createFromTiles: function(indexes, replacements, spriteConfig, scene, camera, layer) { layer = this.getLayer(layer); if (layer === null) { return null } return TilemapComponents.CreateFromTiles(indexes, replacements, spriteConfig, scene, camera, layer) }, createStaticLayer: function(layerID, tileset, x, y) { var index = this.getLayerIndex(layerID); if (index === null) { console.warn("Invalid Tilemap Layer ID: " + layerID); return null } var layerData = this.layers[index]; if (layerData.tilemapLayer) { console.warn("Tilemap Layer ID already exists:" + layerID); return null } this.currentLayerIndex = index; if (x === undefined && this.layers[index].x) { x = this.layers[index].x } if (y === undefined && this.layers[index].y) { y = this.layers[index].y } var layer = new StaticTilemapLayer(this.scene, this, index, tileset, x, y); layer.setRenderOrder(this.renderOrder); this.scene.sys.displayList.add(layer); return layer }, destroy: function() { this.removeAllLayers(); this.tilesets.length = 0; this.objects.length = 0; this.scene = undefined }, fill: function(index, tileX, tileY, width, height, recalculateFaces, layer) { layer = this.getLayer(layer); if (this._isStaticCall(layer, "fill")) { return this } if (layer !== null) { TilemapComponents.Fill(index, tileX, tileY, width, height, recalculateFaces, layer) } return this }, filterObjects: function(objectLayer, callback, context) { if (typeof objectLayer === "string") { var name = objectLayer; objectLayer = this.getObjectLayer(objectLayer); if (!objectLayer) { console.warn("No object layer found with the name: " + name); return null } } return objectLayer.objects.filter(callback, context) }, filterTiles: function(callback, context, tileX, tileY, width, height, filteringOptions, layer) { layer = this.getLayer(layer); if (layer === null) { return null } return TilemapComponents.FilterTiles(callback, context, tileX, tileY, width, height, filteringOptions, layer) }, findByIndex: function(findIndex, skip, reverse, layer) { layer = this.getLayer(layer); if (layer === null) { return null } return TilemapComponents.FindByIndex(findIndex, skip, reverse, layer) }, findObject: function(objectLayer, callback, context) { if (typeof objectLayer === "string") { var name = objectLayer; objectLayer = this.getObjectLayer(objectLayer); if (!objectLayer) { console.warn("No object layer found with the name: " + name); return null } } return objectLayer.objects.find(callback, context) || null }, findTile: function(callback, context, tileX, tileY, width, height, filteringOptions, layer) { layer = this.getLayer(layer); if (layer === null) { return null } return TilemapComponents.FindTile(callback, context, tileX, tileY, width, height, filteringOptions, layer) }, forEachTile: function(callback, context, tileX, tileY, width, height, filteringOptions, layer) { layer = this.getLayer(layer); if (layer !== null) { TilemapComponents.ForEachTile(callback, context, tileX, tileY, width, height, filteringOptions, layer) } return this }, getImageIndex: function(name) { return this.getIndex(this.images, name) }, getIndex: function(location, name) { for (var i = 0; i < location.length; i++) { if (location[i].name === name) { return i } } return null }, getLayer: function(layer) { var index = this.getLayerIndex(layer); return index !== null ? this.layers[index] : null }, getObjectLayer: function(name) { var index = this.getIndex(this.objects, name); return index !== null ? this.objects[index] : null }, getLayerIndex: function(layer) { if (layer === undefined) { return this.currentLayerIndex } else if (typeof layer === "string") { return this.getLayerIndexByName(layer) } else if (typeof layer === "number" && layer < this.layers.length) { return layer } else if (layer instanceof StaticTilemapLayer || layer instanceof DynamicTilemapLayer) { return layer.layerIndex } else { return null } }, getLayerIndexByName: function(name) { return this.getIndex(this.layers, name) }, getTileAt: function(tileX, tileY, nonNull, layer) { layer = this.getLayer(layer); if (layer === null) { return null } return TilemapComponents.GetTileAt(tileX, tileY, nonNull, layer) }, getTileAtWorldXY: function(worldX, worldY, nonNull, camera, layer) { layer = this.getLayer(layer); if (layer === null) { return null } else { return TilemapComponents.GetTileAtWorldXY(worldX, worldY, nonNull, camera, layer) } }, getTilesWithin: function(tileX, tileY, width, height, filteringOptions, layer) { layer = this.getLayer(layer); if (layer === null) { return null } return TilemapComponents.GetTilesWithin(tileX, tileY, width, height, filteringOptions, layer) }, getTilesWithinShape: function(shape, filteringOptions, camera, layer) { layer = this.getLayer(layer); if (layer === null) { return null } return TilemapComponents.GetTilesWithinShape(shape, filteringOptions, camera, layer) }, getTilesWithinWorldXY: function(worldX, worldY, width, height, filteringOptions, camera, layer) { layer = this.getLayer(layer); if (layer === null) { return null } return TilemapComponents.GetTilesWithinWorldXY(worldX, worldY, width, height, filteringOptions, camera, layer) }, getTileset: function(name) { var index = this.getIndex(this.tilesets, name); return index !== null ? this.tilesets[index] : null }, getTilesetIndex: function(name) { return this.getIndex(this.tilesets, name) }, hasTileAt: function(tileX, tileY, layer) { layer = this.getLayer(layer); if (layer === null) { return null } return TilemapComponents.HasTileAt(tileX, tileY, layer) }, hasTileAtWorldXY: function(worldX, worldY, camera, layer) { layer = this.getLayer(layer); if (layer === null) { return null } return TilemapComponents.HasTileAtWorldXY(worldX, worldY, camera, layer) }, layer: { get: function() { return this.layers[this.currentLayerIndex] }, set: function(layer) { this.setLayer(layer) } }, putTileAt: function(tile, tileX, tileY, recalculateFaces, layer) { layer = this.getLayer(layer); if (this._isStaticCall(layer, "putTileAt")) { return null } if (layer === null) { return null } return TilemapComponents.PutTileAt(tile, tileX, tileY, recalculateFaces, layer) }, putTileAtWorldXY: function(tile, worldX, worldY, recalculateFaces, camera, layer) { layer = this.getLayer(layer); if (this._isStaticCall(layer, "putTileAtWorldXY")) { return null } if (layer === null) { return null } return TilemapComponents.PutTileAtWorldXY(tile, worldX, worldY, recalculateFaces, camera, layer) }, putTilesAt: function(tilesArray, tileX, tileY, recalculateFaces, layer) { layer = this.getLayer(layer); if (this._isStaticCall(layer, "putTilesAt")) { return this } if (layer !== null) { TilemapComponents.PutTilesAt(tilesArray, tileX, tileY, recalculateFaces, layer) } return this }, randomize: function(tileX, tileY, width, height, indexes, layer) { layer = this.getLayer(layer); if (this._isStaticCall(layer, "randomize")) { return this } if (layer !== null) { TilemapComponents.Randomize(tileX, tileY, width, height, indexes, layer) } return this }, calculateFacesAt: function(tileX, tileY, layer) { layer = this.getLayer(layer); if (layer === null) { return this } TilemapComponents.CalculateFacesAt(tileX, tileY, layer); return this }, calculateFacesWithin: function(tileX, tileY, width, height, layer) { layer = this.getLayer(layer); if (layer === null) { return this } TilemapComponents.CalculateFacesWithin(tileX, tileY, width, height, layer); return this }, removeAllLayers: function() { for (var i = 0; i < this.layers.length; i++) { if (this.layers[i].tilemapLayer) { this.layers[i].tilemapLayer.destroy() } } this.layers.length = 0; this.currentLayerIndex = 0; return this }, removeTileAt: function(tileX, tileY, replaceWithNull, recalculateFaces, layer) { layer = this.getLayer(layer); if (this._isStaticCall(layer, "removeTileAt")) { return null } if (layer === null) { return null } return TilemapComponents.RemoveTileAt(tileX, tileY, replaceWithNull, recalculateFaces, layer) }, removeTileAtWorldXY: function(worldX, worldY, replaceWithNull, recalculateFaces, camera, layer) { layer = this.getLayer(layer); if (this._isStaticCall(layer, "removeTileAtWorldXY")) { return null } if (layer === null) { return null } return TilemapComponents.RemoveTileAtWorldXY(worldX, worldY, replaceWithNull, recalculateFaces, camera, layer) }, renderDebug: function(graphics, styleConfig, layer) { layer = this.getLayer(layer); if (layer === null) { return this } TilemapComponents.RenderDebug(graphics, styleConfig, layer); return this }, replaceByIndex: function(findIndex, newIndex, tileX, tileY, width, height, layer) { layer = this.getLayer(layer); if (this._isStaticCall(layer, "replaceByIndex")) { return this } if (layer !== null) { TilemapComponents.ReplaceByIndex(findIndex, newIndex, tileX, tileY, width, height, layer) } return this }, setCollision: function(indexes, collides, recalculateFaces, layer) { layer = this.getLayer(layer); if (layer === null) { return this } TilemapComponents.SetCollision(indexes, collides, recalculateFaces, layer); return this }, setCollisionBetween: function(start, stop, collides, recalculateFaces, layer) { layer = this.getLayer(layer); if (layer === null) { return this } TilemapComponents.SetCollisionBetween(start, stop, collides, recalculateFaces, layer); return this }, setCollisionByProperty: function(properties, collides, recalculateFaces, layer) { layer = this.getLayer(layer); if (layer === null) { return this } TilemapComponents.SetCollisionByProperty(properties, collides, recalculateFaces, layer); return this }, setCollisionByExclusion: function(indexes, collides, recalculateFaces, layer) { layer = this.getLayer(layer); if (layer === null) { return this } TilemapComponents.SetCollisionByExclusion(indexes, collides, recalculateFaces, layer); return this }, setCollisionFromCollisionGroup: function(collides, recalculateFaces, layer) { layer = this.getLayer(layer); if (layer === null) { return this } TilemapComponents.SetCollisionFromCollisionGroup(collides, recalculateFaces, layer); return this }, setTileIndexCallback: function(indexes, callback, callbackContext, layer) { layer = this.getLayer(layer); if (layer === null) { return this } TilemapComponents.SetTileIndexCallback(indexes, callback, callbackContext, layer); return this }, setTileLocationCallback: function(tileX, tileY, width, height, callback, callbackContext, layer) { layer = this.getLayer(layer); if (layer === null) { return this } TilemapComponents.SetTileLocationCallback(tileX, tileY, width, height, callback, callbackContext, layer); return this }, setLayer: function(layer) { var index = this.getLayerIndex(layer); if (index !== null) { this.currentLayerIndex = index } return this }, setBaseTileSize: function(tileWidth, tileHeight) { this.tileWidth = tileWidth; this.tileHeight = tileHeight; this.widthInPixels = this.width * tileWidth; this.heightInPixels = this.height * tileHeight; for (var i = 0; i < this.layers.length; i++) { this.layers[i].baseTileWidth = tileWidth; this.layers[i].baseTileHeight = tileHeight; var mapData = this.layers[i].data; var mapWidth = this.layers[i].width; var mapHeight = this.layers[i].height; for (var row = 0; row < mapHeight; ++row) { for (var col = 0; col < mapWidth; ++col) { var tile = mapData[row][col]; if (tile !== null) { tile.setSize(undefined, undefined, tileWidth, tileHeight) } } } } return this }, setLayerTileSize: function(tileWidth, tileHeight, layer) { layer = this.getLayer(layer); if (layer === null) { return this } layer.tileWidth = tileWidth; layer.tileHeight = tileHeight; var mapData = layer.data; var mapWidth = layer.width; var mapHeight = layer.height; for (var row = 0; row < mapHeight; ++row) { for (var col = 0; col < mapWidth; ++col) { var tile = mapData[row][col]; if (tile !== null) { tile.setSize(tileWidth, tileHeight) } } } return this }, shuffle: function(tileX, tileY, width, height, layer) { layer = this.getLayer(layer); if (this._isStaticCall(layer, "shuffle")) { return this } if (layer !== null) { TilemapComponents.Shuffle(tileX, tileY, width, height, layer) } return this }, swapByIndex: function(indexA, indexB, tileX, tileY, width, height, layer) { layer = this.getLayer(layer); if (this._isStaticCall(layer, "swapByIndex")) { return this } if (layer !== null) { TilemapComponents.SwapByIndex(indexA, indexB, tileX, tileY, width, height, layer) } return this }, tileToWorldX: function(tileX, camera, layer) { layer = this.getLayer(layer); if (layer === null) { return null } return TilemapComponents.TileToWorldX(tileX, camera, layer) }, tileToWorldY: function(tileX, camera, layer) { layer = this.getLayer(layer); if (layer === null) { return null } return TilemapComponents.TileToWorldY(tileX, camera, layer) }, tileToWorldXY: function(tileX, tileY, point, camera, layer) { layer = this.getLayer(layer); if (layer === null) { return null } return TilemapComponents.TileToWorldXY(tileX, tileY, point, camera, layer) }, weightedRandomize: function(tileX, tileY, width, height, weightedIndexes, layer) { layer = this.getLayer(layer); if (this._isStaticCall(layer, "weightedRandomize")) { return this } if (layer !== null) { TilemapComponents.WeightedRandomize(tileX, tileY, width, height, weightedIndexes, layer) } return this }, worldToTileX: function(worldX, snapToFloor, camera, layer) { layer = this.getLayer(layer); if (layer === null) { return null } return TilemapComponents.WorldToTileX(worldX, snapToFloor, camera, layer) }, worldToTileY: function(worldY, snapToFloor, camera, layer) { layer = this.getLayer(layer); if (layer === null) { return null } return TilemapComponents.WorldToTileY(worldY, snapToFloor, camera, layer) }, worldToTileXY: function(worldX, worldY, snapToFloor, point, camera, layer) { layer = this.getLayer(layer); if (layer === null) { return null } return TilemapComponents.WorldToTileXY(worldX, worldY, snapToFloor, point, camera, layer) }, _isStaticCall: function(layer, functionName) { if (layer.tilemapLayer instanceof StaticTilemapLayer) { console.warn(functionName + ": You cannot change the tiles in a static tilemap layer"); return true } else { return false } } }); module.exports = Tilemap }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Components = __webpack_require__(14); var DynamicTilemapLayerRender = __webpack_require__(1130); var GameObject = __webpack_require__(12); var TilemapComponents = __webpack_require__(133); var DynamicTilemapLayer = new Class({ Extends: GameObject, Mixins: [Components.Alpha, Components.BlendMode, Components.ComputedSize, Components.Depth, Components.Flip, Components.GetBounds, Components.Origin, Components.Pipeline, Components.ScaleMode, Components.Transform, Components.Visible, Components.ScrollFactor, DynamicTilemapLayerRender], initialize: function DynamicTilemapLayer(scene, tilemap, layerIndex, tileset, x, y) { GameObject.call(this, scene, "DynamicTilemapLayer"); this.isTilemap = true; this.tilemap = tilemap; this.layerIndex = layerIndex; this.layer = tilemap.layers[layerIndex]; this.layer.tilemapLayer = this; this.tileset = []; this.culledTiles = []; this.skipCull = false; this.tilesDrawn = 0; this.tilesTotal = this.layer.width * this.layer.height; this.cullPaddingX = 1; this.cullPaddingY = 1; this.cullCallback = TilemapComponents.CullTiles; this._renderOrder = 0; this.gidMap = []; this.setTilesets(tileset); this.setAlpha(this.layer.alpha); this.setPosition(x, y); this.setOrigin(); this.setSize(this.layer.tileWidth * this.layer.width, this.layer.tileHeight * this.layer.height); this.initPipeline("TextureTintPipeline") }, setTilesets: function(tilesets) { var gidMap = []; var setList = []; var map = this.tilemap; if (!Array.isArray(tilesets)) { tilesets = [tilesets] } for (var i = 0; i < tilesets.length; i++) { var tileset = tilesets[i]; if (typeof tileset === "string") { tileset = map.getTileset(tileset) } if (tileset) { setList.push(tileset); var s = tileset.firstgid; for (var t = 0; t < tileset.total; t++) { gidMap[s + t] = tileset } } } this.gidMap = gidMap; this.tileset = setList }, setRenderOrder: function(renderOrder) { var orders = ["right-down", "left-down", "right-up", "left-up"]; if (typeof renderOrder === "string") { renderOrder = orders.indexOf(renderOrder) } if (renderOrder >= 0 && renderOrder < 4) { this._renderOrder = renderOrder } return this }, calculateFacesAt: function(tileX, tileY) { TilemapComponents.CalculateFacesAt(tileX, tileY, this.layer); return this }, calculateFacesWithin: function(tileX, tileY, width, height) { TilemapComponents.CalculateFacesWithin(tileX, tileY, width, height, this.layer); return this }, createFromTiles: function(indexes, replacements, spriteConfig, scene, camera) { return TilemapComponents.CreateFromTiles(indexes, replacements, spriteConfig, scene, camera, this.layer) }, cull: function(camera) { return this.cullCallback(this.layer, camera, this.culledTiles, this._renderOrder) }, copy: function(srcTileX, srcTileY, width, height, destTileX, destTileY, recalculateFaces) { TilemapComponents.Copy(srcTileX, srcTileY, width, height, destTileX, destTileY, recalculateFaces, this.layer); return this }, destroy: function() { if (this.layer.tilemapLayer === this) { this.layer.tilemapLayer = undefined } this.tilemap = undefined; this.layer = undefined; this.culledTiles.length = 0; this.cullCallback = null; this.gidMap = []; this.tileset = []; GameObject.prototype.destroy.call(this) }, fill: function(index, tileX, tileY, width, height, recalculateFaces) { TilemapComponents.Fill(index, tileX, tileY, width, height, recalculateFaces, this.layer); return this }, filterTiles: function(callback, context, tileX, tileY, width, height, filteringOptions) { return TilemapComponents.FilterTiles(callback, context, tileX, tileY, width, height, filteringOptions, this.layer) }, findByIndex: function(findIndex, skip, reverse) { return TilemapComponents.FindByIndex(findIndex, skip, reverse, this.layer) }, findTile: function(callback, context, tileX, tileY, width, height, filteringOptions) { return TilemapComponents.FindTile(callback, context, tileX, tileY, width, height, filteringOptions, this.layer) }, forEachTile: function(callback, context, tileX, tileY, width, height, filteringOptions) { TilemapComponents.ForEachTile(callback, context, tileX, tileY, width, height, filteringOptions, this.layer); return this }, getTileAt: function(tileX, tileY, nonNull) { return TilemapComponents.GetTileAt(tileX, tileY, nonNull, this.layer) }, getTileAtWorldXY: function(worldX, worldY, nonNull, camera) { return TilemapComponents.GetTileAtWorldXY(worldX, worldY, nonNull, camera, this.layer) }, getTilesWithin: function(tileX, tileY, width, height, filteringOptions) { return TilemapComponents.GetTilesWithin(tileX, tileY, width, height, filteringOptions, this.layer) }, getTilesWithinShape: function(shape, filteringOptions, camera) { return TilemapComponents.GetTilesWithinShape(shape, filteringOptions, camera, this.layer) }, getTilesWithinWorldXY: function(worldX, worldY, width, height, filteringOptions, camera) { return TilemapComponents.GetTilesWithinWorldXY(worldX, worldY, width, height, filteringOptions, camera, this.layer) }, hasTileAt: function(tileX, tileY) { return TilemapComponents.HasTileAt(tileX, tileY, this.layer) }, hasTileAtWorldXY: function(worldX, worldY, camera) { return TilemapComponents.HasTileAtWorldXY(worldX, worldY, camera, this.layer) }, putTileAt: function(tile, tileX, tileY, recalculateFaces) { return TilemapComponents.PutTileAt(tile, tileX, tileY, recalculateFaces, this.layer) }, putTileAtWorldXY: function(tile, worldX, worldY, recalculateFaces, camera) { return TilemapComponents.PutTileAtWorldXY(tile, worldX, worldY, recalculateFaces, camera, this.layer) }, putTilesAt: function(tilesArray, tileX, tileY, recalculateFaces) { TilemapComponents.PutTilesAt(tilesArray, tileX, tileY, recalculateFaces, this.layer); return this }, randomize: function(tileX, tileY, width, height, indexes) { TilemapComponents.Randomize(tileX, tileY, width, height, indexes, this.layer); return this }, removeTileAt: function(tileX, tileY, replaceWithNull, recalculateFaces) { return TilemapComponents.RemoveTileAt(tileX, tileY, replaceWithNull, recalculateFaces, this.layer) }, removeTileAtWorldXY: function(worldX, worldY, replaceWithNull, recalculateFaces, camera) { return TilemapComponents.RemoveTileAtWorldXY(worldX, worldY, replaceWithNull, recalculateFaces, camera, this.layer) }, renderDebug: function(graphics, styleConfig) { TilemapComponents.RenderDebug(graphics, styleConfig, this.layer); return this }, replaceByIndex: function(findIndex, newIndex, tileX, tileY, width, height) { TilemapComponents.ReplaceByIndex(findIndex, newIndex, tileX, tileY, width, height, this.layer); return this }, setSkipCull: function(value) { if (value === undefined) { value = true } this.skipCull = value; return this }, setCullPadding: function(paddingX, paddingY) { if (paddingX === undefined) { paddingX = 1 } if (paddingY === undefined) { paddingY = 1 } this.cullPaddingX = paddingX; this.cullPaddingY = paddingY; return this }, setCollision: function(indexes, collides, recalculateFaces) { TilemapComponents.SetCollision(indexes, collides, recalculateFaces, this.layer); return this }, setCollisionBetween: function(start, stop, collides, recalculateFaces) { TilemapComponents.SetCollisionBetween(start, stop, collides, recalculateFaces, this.layer); return this }, setCollisionByProperty: function(properties, collides, recalculateFaces) { TilemapComponents.SetCollisionByProperty(properties, collides, recalculateFaces, this.layer); return this }, setCollisionByExclusion: function(indexes, collides, recalculateFaces) { TilemapComponents.SetCollisionByExclusion(indexes, collides, recalculateFaces, this.layer); return this }, setCollisionFromCollisionGroup: function(collides, recalculateFaces) { TilemapComponents.SetCollisionFromCollisionGroup(collides, recalculateFaces, this.layer); return this }, setTileIndexCallback: function(indexes, callback, callbackContext) { TilemapComponents.SetTileIndexCallback(indexes, callback, callbackContext, this.layer); return this }, setTileLocationCallback: function(tileX, tileY, width, height, callback, callbackContext) { TilemapComponents.SetTileLocationCallback(tileX, tileY, width, height, callback, callbackContext, this.layer); return this }, shuffle: function(tileX, tileY, width, height) { TilemapComponents.Shuffle(tileX, tileY, width, height, this.layer); return this }, swapByIndex: function(indexA, indexB, tileX, tileY, width, height) { TilemapComponents.SwapByIndex(indexA, indexB, tileX, tileY, width, height, this.layer); return this }, tileToWorldX: function(tileX, camera) { return TilemapComponents.TileToWorldX(tileX, camera, this.layer) }, tileToWorldY: function(tileY, camera) { return TilemapComponents.TileToWorldY(tileY, camera, this.layer) }, tileToWorldXY: function(tileX, tileY, point, camera) { return TilemapComponents.TileToWorldXY(tileX, tileY, point, camera, this.layer) }, weightedRandomize: function(tileX, tileY, width, height, weightedIndexes) { TilemapComponents.WeightedRandomize(tileX, tileY, width, height, weightedIndexes, this.layer); return this }, worldToTileX: function(worldX, snapToFloor, camera) { return TilemapComponents.WorldToTileX(worldX, snapToFloor, camera, this.layer) }, worldToTileY: function(worldY, snapToFloor, camera) { return TilemapComponents.WorldToTileY(worldY, snapToFloor, camera, this.layer) }, worldToTileXY: function(worldX, worldY, snapToFloor, point, camera) { return TilemapComponents.WorldToTileXY(worldX, worldY, snapToFloor, point, camera, this.layer) } }); module.exports = DynamicTilemapLayer }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Components = __webpack_require__(14); var CONST = __webpack_require__(26); var GameObject = __webpack_require__(12); var StaticTilemapLayerRender = __webpack_require__(1133); var TilemapComponents = __webpack_require__(133); var TransformMatrix = __webpack_require__(48); var Utils = __webpack_require__(10); var StaticTilemapLayer = new Class({ Extends: GameObject, Mixins: [Components.Alpha, Components.BlendMode, Components.ComputedSize, Components.Depth, Components.Flip, Components.GetBounds, Components.Origin, Components.Pipeline, Components.ScaleMode, Components.Transform, Components.Visible, Components.ScrollFactor, StaticTilemapLayerRender], initialize: function StaticTilemapLayer(scene, tilemap, layerIndex, tileset, x, y) { GameObject.call(this, scene, "StaticTilemapLayer"); this.isTilemap = true; this.tilemap = tilemap; this.layerIndex = layerIndex; this.layer = tilemap.layers[layerIndex]; this.layer.tilemapLayer = this; this.tileset = []; this.culledTiles = []; this.skipCull = false; this.tilesDrawn = 0; this.tilesTotal = this.layer.width * this.layer.height; this.cullPaddingX = 1; this.cullPaddingY = 1; this.cullCallback = TilemapComponents.CullTiles; this.renderer = scene.sys.game.renderer; this.vertexBuffer = []; this.bufferData = []; this.vertexViewF32 = []; this.vertexViewU32 = []; this.dirty = []; this.vertexCount = []; this._renderOrder = 0; this._tempMatrix = new TransformMatrix; this.gidMap = []; this.setTilesets(tileset); this.setAlpha(this.layer.alpha); this.setPosition(x, y); this.setOrigin(); this.setSize(this.layer.tileWidth * this.layer.width, this.layer.tileHeight * this.layer.height); this.updateVBOData(); this.initPipeline("TextureTintPipeline"); if (scene.sys.game.config.renderType === CONST.WEBGL) { scene.sys.game.renderer.onContextRestored(function() { this.updateVBOData() }, this) } }, setTilesets: function(tilesets) { var gidMap = []; var setList = []; var map = this.tilemap; if (!Array.isArray(tilesets)) { tilesets = [tilesets] } for (var i = 0; i < tilesets.length; i++) { var tileset = tilesets[i]; if (typeof tileset === "string") { tileset = map.getTileset(tileset) } if (tileset) { setList.push(tileset); var s = tileset.firstgid; for (var t = 0; t < tileset.total; t++) { gidMap[s + t] = tileset } } } this.gidMap = gidMap; this.tileset = setList }, updateVBOData: function() { for (var i = 0; i < this.tileset.length; i++) { this.dirty[i] = true; this.vertexCount[i] = 0; this.vertexBuffer[i] = null; this.bufferData[i] = null; this.vertexViewF32[i] = null; this.vertexViewU32[i] = null } return this }, upload: function(camera, tilesetIndex) { var renderer = this.renderer; var gl = renderer.gl; var pipeline = renderer.pipelines.TextureTintPipeline; if (this.dirty[tilesetIndex]) { var tileset = this.tileset[tilesetIndex]; var mapWidth = this.layer.width; var mapHeight = this.layer.height; var width = tileset.image.source[0].width; var height = tileset.image.source[0].height; var mapData = this.layer.data; var tile; var row; var col; var renderOrder = this._renderOrder; var minTileIndex = tileset.firstgid; var maxTileIndex = tileset.firstgid + tileset.total; var vertexBuffer = this.vertexBuffer[tilesetIndex]; var bufferData = this.bufferData[tilesetIndex]; var vOffset = -1; var bufferSize = mapWidth * mapHeight * pipeline.vertexSize * 6; this.vertexCount[tilesetIndex] = 0; if (bufferData === null) { bufferData = new ArrayBuffer(bufferSize); this.bufferData[tilesetIndex] = bufferData; this.vertexViewF32[tilesetIndex] = new Float32Array(bufferData); this.vertexViewU32[tilesetIndex] = new Uint32Array(bufferData) } if (renderOrder === 0) { for (row = 0; row < mapHeight; row++) { for (col = 0; col < mapWidth; col++) { tile = mapData[row][col]; if (!tile || tile.index < minTileIndex || tile.index > maxTileIndex || !tile.visible) { continue } vOffset = this.batchTile(vOffset, tile, tileset, width, height, camera, tilesetIndex) } } } else if (renderOrder === 1) { for (row = 0; row < mapHeight; row++) { for (col = mapWidth - 1; col >= 0; col--) { tile = mapData[row][col]; if (!tile || tile.index < minTileIndex || tile.index > maxTileIndex || !tile.visible) { continue } vOffset = this.batchTile(vOffset, tile, tileset, width, height, camera, tilesetIndex) } } } else if (renderOrder === 2) { for (row = mapHeight - 1; row >= 0; row--) { for (col = 0; col < mapWidth; col++) { tile = mapData[row][col]; if (!tile || tile.index < minTileIndex || tile.index > maxTileIndex || !tile.visible) { continue } vOffset = this.batchTile(vOffset, tile, tileset, width, height, camera, tilesetIndex) } } } else if (renderOrder === 3) { for (row = mapHeight - 1; row >= 0; row--) { for (col = mapWidth - 1; col >= 0; col--) { tile = mapData[row][col]; if (!tile || tile.index < minTileIndex || tile.index > maxTileIndex || !tile.visible) { continue } vOffset = this.batchTile(vOffset, tile, tileset, width, height, camera, tilesetIndex) } } } this.dirty[tilesetIndex] = false; if (vertexBuffer === null) { vertexBuffer = renderer.createVertexBuffer(bufferData, gl.STATIC_DRAW); this.vertexBuffer[tilesetIndex] = vertexBuffer } else { renderer.setVertexBuffer(vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, bufferData) } } return this }, batchTile: function(vOffset, tile, tileset, width, height, camera, tilesetIndex) { var texCoords = tileset.getTileTextureCoordinates(tile.index); if (!texCoords) { return vOffset } var u0 = texCoords.x / width; var v0 = texCoords.y / height; var u1 = (texCoords.x + tile.width) / width; var v1 = (texCoords.y + tile.height) / height; var matrix = this._tempMatrix; var tileWidth = tile.width; var tileHeight = tile.height; var halfTileWidth = tileWidth / 2; var halfTileHeight = tileHeight / 2; var x = -halfTileWidth; var y = -halfTileHeight; if (tile.flipX) { tileWidth *= -1; x += tile.width } if (tile.flipY) { tileHeight *= -1; y += tile.height } var xw = x + tileWidth; var yh = y + tileHeight; matrix.applyITRS(halfTileWidth + tile.pixelX, halfTileHeight + tile.pixelY, tile.rotation, 1, 1); var tint = Utils.getTintAppendFloatAlpha(16777215, camera.alpha * this.alpha * tile.alpha); var tx0 = matrix.getX(x, y); var ty0 = matrix.getY(x, y); var tx1 = matrix.getX(x, yh); var ty1 = matrix.getY(x, yh); var tx2 = matrix.getX(xw, yh); var ty2 = matrix.getY(xw, yh); var tx3 = matrix.getX(xw, y); var ty3 = matrix.getY(xw, y); if (camera.roundPixels) { tx0 |= 0; ty0 |= 0; tx1 |= 0; ty1 |= 0; tx2 |= 0; ty2 |= 0; tx3 |= 0; ty3 |= 0 } var vertexViewF32 = this.vertexViewF32[tilesetIndex]; var vertexViewU32 = this.vertexViewU32[tilesetIndex]; vertexViewF32[++vOffset] = tx0; vertexViewF32[++vOffset] = ty0; vertexViewF32[++vOffset] = u0; vertexViewF32[++vOffset] = v0; vertexViewF32[++vOffset] = 0; vertexViewU32[++vOffset] = tint; vertexViewF32[++vOffset] = tx1; vertexViewF32[++vOffset] = ty1; vertexViewF32[++vOffset] = u0; vertexViewF32[++vOffset] = v1; vertexViewF32[++vOffset] = 0; vertexViewU32[++vOffset] = tint; vertexViewF32[++vOffset] = tx2; vertexViewF32[++vOffset] = ty2; vertexViewF32[++vOffset] = u1; vertexViewF32[++vOffset] = v1; vertexViewF32[++vOffset] = 0; vertexViewU32[++vOffset] = tint; vertexViewF32[++vOffset] = tx0; vertexViewF32[++vOffset] = ty0; vertexViewF32[++vOffset] = u0; vertexViewF32[++vOffset] = v0; vertexViewF32[++vOffset] = 0; vertexViewU32[++vOffset] = tint; vertexViewF32[++vOffset] = tx2; vertexViewF32[++vOffset] = ty2; vertexViewF32[++vOffset] = u1; vertexViewF32[++vOffset] = v1; vertexViewF32[++vOffset] = 0; vertexViewU32[++vOffset] = tint; vertexViewF32[++vOffset] = tx3; vertexViewF32[++vOffset] = ty3; vertexViewF32[++vOffset] = u1; vertexViewF32[++vOffset] = v0; vertexViewF32[++vOffset] = 0; vertexViewU32[++vOffset] = tint; this.vertexCount[tilesetIndex] += 6; return vOffset }, setRenderOrder: function(renderOrder) { var orders = ["right-down", "left-down", "right-up", "left-up"]; if (typeof renderOrder === "string") { renderOrder = orders.indexOf(renderOrder) } if (renderOrder >= 0 && renderOrder < 4) { this._renderOrder = renderOrder; for (var i = 0; i < this.tileset.length; i++) { this.dirty[i] = true } } return this }, calculateFacesAt: function(tileX, tileY) { TilemapComponents.CalculateFacesAt(tileX, tileY, this.layer); return this }, calculateFacesWithin: function(tileX, tileY, width, height) { TilemapComponents.CalculateFacesWithin(tileX, tileY, width, height, this.layer); return this }, createFromTiles: function(indexes, replacements, spriteConfig, scene, camera) { return TilemapComponents.CreateFromTiles(indexes, replacements, spriteConfig, scene, camera, this.layer) }, cull: function(camera) { return this.cullCallback(this.layer, camera, this.culledTiles) }, setSkipCull: function(value) { if (value === undefined) { value = true } this.skipCull = value; return this }, setCullPadding: function(paddingX, paddingY) { if (paddingX === undefined) { paddingX = 1 } if (paddingY === undefined) { paddingY = 1 } this.cullPaddingX = paddingX; this.cullPaddingY = paddingY; return this }, findByIndex: function(findIndex, skip, reverse) { return TilemapComponents.FindByIndex(findIndex, skip, reverse, this.layer) }, findTile: function(callback, context, tileX, tileY, width, height, filteringOptions) { return TilemapComponents.FindTile(callback, context, tileX, tileY, width, height, filteringOptions, this.layer) }, filterTiles: function(callback, context, tileX, tileY, width, height, filteringOptions) { return TilemapComponents.FilterTiles(callback, context, tileX, tileY, width, height, filteringOptions, this.layer) }, forEachTile: function(callback, context, tileX, tileY, width, height, filteringOptions) { TilemapComponents.ForEachTile(callback, context, tileX, tileY, width, height, filteringOptions, this.layer); return this }, getTileAt: function(tileX, tileY, nonNull) { return TilemapComponents.GetTileAt(tileX, tileY, nonNull, this.layer) }, getTileAtWorldXY: function(worldX, worldY, nonNull, camera) { return TilemapComponents.GetTileAtWorldXY(worldX, worldY, nonNull, camera, this.layer) }, getTilesWithin: function(tileX, tileY, width, height, filteringOptions) { return TilemapComponents.GetTilesWithin(tileX, tileY, width, height, filteringOptions, this.layer) }, getTilesWithinWorldXY: function(worldX, worldY, width, height, filteringOptions, camera) { return TilemapComponents.GetTilesWithinWorldXY(worldX, worldY, width, height, filteringOptions, camera, this.layer) }, getTilesWithinShape: function(shape, filteringOptions, camera) { return TilemapComponents.GetTilesWithinShape(shape, filteringOptions, camera, this.layer) }, hasTileAt: function(tileX, tileY) { return TilemapComponents.HasTileAt(tileX, tileY, this.layer) }, hasTileAtWorldXY: function(worldX, worldY, camera) { return TilemapComponents.HasTileAtWorldXY(worldX, worldY, camera, this.layer) }, renderDebug: function(graphics, styleConfig) { TilemapComponents.RenderDebug(graphics, styleConfig, this.layer); return this }, setCollision: function(indexes, collides, recalculateFaces) { TilemapComponents.SetCollision(indexes, collides, recalculateFaces, this.layer); return this }, setCollisionBetween: function(start, stop, collides, recalculateFaces) { TilemapComponents.SetCollisionBetween(start, stop, collides, recalculateFaces, this.layer); return this }, setCollisionByProperty: function(properties, collides, recalculateFaces) { TilemapComponents.SetCollisionByProperty(properties, collides, recalculateFaces, this.layer); return this }, setCollisionByExclusion: function(indexes, collides, recalculateFaces) { TilemapComponents.SetCollisionByExclusion(indexes, collides, recalculateFaces, this.layer); return this }, setTileIndexCallback: function(indexes, callback, callbackContext) { TilemapComponents.SetTileIndexCallback(indexes, callback, callbackContext, this.layer); return this }, setCollisionFromCollisionGroup: function(collides, recalculateFaces) { TilemapComponents.SetCollisionFromCollisionGroup(collides, recalculateFaces, this.layer); return this }, setTileLocationCallback: function(tileX, tileY, width, height, callback, callbackContext) { TilemapComponents.SetTileLocationCallback(tileX, tileY, width, height, callback, callbackContext, this.layer); return this }, tileToWorldX: function(tileX, camera) { return TilemapComponents.TileToWorldX(tileX, camera, this.layer) }, tileToWorldY: function(tileY, camera) { return TilemapComponents.TileToWorldY(tileY, camera, this.layer) }, tileToWorldXY: function(tileX, tileY, point, camera) { return TilemapComponents.TileToWorldXY(tileX, tileY, point, camera, this.layer) }, worldToTileX: function(worldX, snapToFloor, camera) { return TilemapComponents.WorldToTileX(worldX, snapToFloor, camera, this.layer) }, worldToTileY: function(worldY, snapToFloor, camera) { return TilemapComponents.WorldToTileY(worldY, snapToFloor, camera, this.layer) }, worldToTileXY: function(worldX, worldY, snapToFloor, point, camera) { return TilemapComponents.WorldToTileXY(worldX, worldY, snapToFloor, point, camera, this.layer) }, destroy: function() { if (this.layer.tilemapLayer === this) { this.layer.tilemapLayer = undefined } this.tilemap = undefined; this.layer = undefined; this.culledTiles.length = 0; this.cullCallback = null; for (var i = 0; i < this.tileset.length; i++) { this.dirty[i] = true; this.vertexCount[i] = 0; this.vertexBuffer[i] = null; this.bufferData[i] = null; this.vertexViewF32[i] = null; this.vertexViewU32[i] = null } this.gidMap = []; this.tileset = []; GameObject.prototype.destroy.call(this) } }); module.exports = StaticTilemapLayer }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var GetFastValue = __webpack_require__(1); var TimerEvent = new Class({ initialize: function TimerEvent(config) { this.delay = 0; this.repeat = 0; this.repeatCount = 0; this.loop = false; this.callback; this.callbackScope; this.args; this.timeScale = 1; this.startAt = 0; this.elapsed = 0; this.paused = false; this.hasDispatched = false; this.reset(config) }, reset: function(config) { this.delay = GetFastValue(config, "delay", 0); this.repeat = GetFastValue(config, "repeat", 0); this.loop = GetFastValue(config, "loop", false); this.callback = GetFastValue(config, "callback", undefined); this.callbackScope = GetFastValue(config, "callbackScope", this.callback); this.args = GetFastValue(config, "args", []); this.timeScale = GetFastValue(config, "timeScale", 1); this.startAt = GetFastValue(config, "startAt", 0); this.paused = GetFastValue(config, "paused", false); this.elapsed = this.startAt; this.hasDispatched = false; this.repeatCount = this.repeat === -1 || this.loop ? 999999999999 : this.repeat; return this }, getProgress: function() { return this.elapsed / this.delay }, getOverallProgress: function() { if (this.repeat > 0) { var totalDuration = this.delay + this.delay * this.repeat; var totalElapsed = this.elapsed + this.delay * (this.repeat - this.repeatCount); return totalElapsed / totalDuration } else { return this.getProgress() } }, getRepeatCount: function() { return this.repeatCount }, getElapsed: function() { return this.elapsed }, getElapsedSeconds: function() { return this.elapsed * .001 }, remove: function(dispatchCallback) { if (dispatchCallback === undefined) { dispatchCallback = false } this.elapsed = this.delay; this.hasDispatched = !dispatchCallback; this.repeatCount = 0 }, destroy: function() { this.callback = undefined; this.callbackScope = undefined; this.args = [] } }); module.exports = TimerEvent }, function(module, exports, __webpack_require__) { var RESERVED = __webpack_require__(1142); var GetProps = function(config) { var key; var keys = []; if (config.hasOwnProperty("props")) { for (key in config.props) { if (key.substr(0, 1) !== "_") { keys.push({ key: key, value: config.props[key] }) } } } else { for (key in config) { if (RESERVED.indexOf(key) === -1 && key.substr(0, 1) !== "_") { keys.push({ key: key, value: config[key] }) } } } return keys }; module.exports = GetProps }, function(module, exports, __webpack_require__) { var GetValue = __webpack_require__(4); var GetTweens = function(config) { var tweens = GetValue(config, "tweens", null); if (tweens === null) { return [] } else if (typeof tweens === "function") { tweens = tweens.call() } if (!Array.isArray(tweens)) { tweens = [tweens] } return tweens }; module.exports = GetTweens }, function(module, exports, __webpack_require__) { var Defaults = __webpack_require__(218); var GetAdvancedValue = __webpack_require__(13); var GetBoolean = __webpack_require__(98); var GetEaseFunction = __webpack_require__(97); var GetNewValue = __webpack_require__(138); var GetValue = __webpack_require__(4); var GetValueOp = __webpack_require__(217); var Tween = __webpack_require__(219); var TweenData = __webpack_require__(220); var NumberTweenBuilder = function(parent, config, defaults) { if (defaults === undefined) { defaults = Defaults } var from = GetValue(config, "from", 0); var to = GetValue(config, "to", 1); var targets = [{ value: from }]; var delay = GetNewValue(config, "delay", defaults.delay); var duration = GetNewValue(config, "duration", defaults.duration); var easeParams = GetValue(config, "easeParams", defaults.easeParams); var ease = GetEaseFunction(GetValue(config, "ease", defaults.ease), easeParams); var hold = GetNewValue(config, "hold", defaults.hold); var repeat = GetNewValue(config, "repeat", defaults.repeat); var repeatDelay = GetNewValue(config, "repeatDelay", defaults.repeatDelay); var yoyo = GetBoolean(config, "yoyo", defaults.yoyo); var data = []; var ops = GetValueOp("value", to); var tweenData = TweenData(targets[0], "value", ops.getEnd, ops.getStart, ease, delay, duration, yoyo, hold, repeat, repeatDelay, false, false); tweenData.start = from; tweenData.current = from; tweenData.to = to; data.push(tweenData); var tween = new Tween(parent, data, targets); tween.offset = GetAdvancedValue(config, "offset", null); tween.completeDelay = GetAdvancedValue(config, "completeDelay", 0); tween.loop = Math.round(GetAdvancedValue(config, "loop", 0)); tween.loopDelay = Math.round(GetAdvancedValue(config, "loopDelay", 0)); tween.paused = GetBoolean(config, "paused", false); tween.useFrames = GetBoolean(config, "useFrames", false); var scope = GetValue(config, "callbackScope", tween); var tweenArray = [tween, null]; var callbacks = Tween.TYPES; for (var i = 0; i < callbacks.length; i++) { var type = callbacks[i]; var callback = GetValue(config, type, false); if (callback) { var callbackScope = GetValue(config, type + "Scope", scope); var callbackParams = GetValue(config, type + "Params", []); tween.setCallback(type, callback, tweenArray.concat(callbackParams), callbackScope) } } return tween }; module.exports = NumberTweenBuilder }, function(module, exports, __webpack_require__) { var Clone = __webpack_require__(64); var Defaults = __webpack_require__(218); var GetAdvancedValue = __webpack_require__(13); var GetBoolean = __webpack_require__(98); var GetEaseFunction = __webpack_require__(97); var GetNewValue = __webpack_require__(138); var GetTargets = __webpack_require__(216); var GetTweens = __webpack_require__(464); var GetValue = __webpack_require__(4); var Timeline = __webpack_require__(467); var TweenBuilder = __webpack_require__(139); var TimelineBuilder = function(manager, config) { var timeline = new Timeline(manager); var tweens = GetTweens(config); if (tweens.length === 0) { timeline.paused = true; return timeline } var defaults = Clone(Defaults); defaults.targets = GetTargets(config); var totalDuration = GetAdvancedValue(config, "totalDuration", 0); if (totalDuration > 0) { defaults.duration = Math.floor(totalDuration / tweens.length) } else { defaults.duration = GetNewValue(config, "duration", defaults.duration) } defaults.delay = GetNewValue(config, "delay", defaults.delay); defaults.easeParams = GetValue(config, "easeParams", defaults.easeParams); defaults.ease = GetEaseFunction(GetValue(config, "ease", defaults.ease), defaults.easeParams); defaults.hold = GetNewValue(config, "hold", defaults.hold); defaults.repeat = GetNewValue(config, "repeat", defaults.repeat); defaults.repeatDelay = GetNewValue(config, "repeatDelay", defaults.repeatDelay); defaults.yoyo = GetBoolean(config, "yoyo", defaults.yoyo); defaults.flipX = GetBoolean(config, "flipX", defaults.flipX); defaults.flipY = GetBoolean(config, "flipY", defaults.flipY); for (var i = 0; i < tweens.length; i++) { timeline.queue(TweenBuilder(timeline, tweens[i], defaults)) } timeline.completeDelay = GetAdvancedValue(config, "completeDelay", 0); timeline.loop = Math.round(GetAdvancedValue(config, "loop", 0)); timeline.loopDelay = Math.round(GetAdvancedValue(config, "loopDelay", 0)); timeline.paused = GetBoolean(config, "paused", false); timeline.useFrames = GetBoolean(config, "useFrames", false); var scope = GetValue(config, "callbackScope", timeline); var timelineArray = [timeline]; var onStart = GetValue(config, "onStart", false); if (onStart) { var onStartScope = GetValue(config, "onStartScope", scope); var onStartParams = GetValue(config, "onStartParams", []); timeline.setCallback("onStart", onStart, timelineArray.concat(onStartParams), onStartScope) } var onUpdate = GetValue(config, "onUpdate", false); if (onUpdate) { var onUpdateScope = GetValue(config, "onUpdateScope", scope); var onUpdateParams = GetValue(config, "onUpdateParams", []); timeline.setCallback("onUpdate", onUpdate, timelineArray.concat(onUpdateParams), onUpdateScope) } var onLoop = GetValue(config, "onLoop", false); if (onLoop) { var onLoopScope = GetValue(config, "onLoopScope", scope); var onLoopParams = GetValue(config, "onLoopParams", []); timeline.setCallback("onLoop", onLoop, timelineArray.concat(onLoopParams), onLoopScope) } var onYoyo = GetValue(config, "onYoyo", false); if (onYoyo) { var onYoyoScope = GetValue(config, "onYoyoScope", scope); var onYoyoParams = GetValue(config, "onYoyoParams", []); timeline.setCallback("onYoyo", onYoyo, timelineArray.concat(null, onYoyoParams), onYoyoScope) } var onComplete = GetValue(config, "onComplete", false); if (onComplete) { var onCompleteScope = GetValue(config, "onCompleteScope", scope); var onCompleteParams = GetValue(config, "onCompleteParams", []); timeline.setCallback("onComplete", onComplete, timelineArray.concat(onCompleteParams), onCompleteScope) } return timeline }; module.exports = TimelineBuilder }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var EventEmitter = __webpack_require__(11); var TweenBuilder = __webpack_require__(139); var TWEEN_CONST = __webpack_require__(99); var Timeline = new Class({ Extends: EventEmitter, initialize: function Timeline(manager) { EventEmitter.call(this); this.manager = manager; this.isTimeline = true; this.data = []; this.totalData = 0; this.useFrames = false; this.timeScale = 1; this.loop = 0; this.loopDelay = 0; this.loopCounter = 0; this.completeDelay = 0; this.countdown = 0; this.state = TWEEN_CONST.PENDING_ADD; this._pausedState = TWEEN_CONST.PENDING_ADD; this.paused = false; this.elapsed = 0; this.totalElapsed = 0; this.duration = 0; this.progress = 0; this.totalDuration = 0; this.totalProgress = 0; this.callbacks = { onComplete: null, onLoop: null, onStart: null, onUpdate: null, onYoyo: null }; this.callbackScope }, setTimeScale: function(value) { this.timeScale = value; return this }, getTimeScale: function() { return this.timeScale }, isPlaying: function() { return this.state === TWEEN_CONST.ACTIVE }, add: function(config) { return this.queue(TweenBuilder(this, config)) }, queue: function(tween) { if (!this.isPlaying()) { tween.parent = this; tween.parentIsTimeline = true; this.data.push(tween); this.totalData = this.data.length } return this }, hasOffset: function(tween) { return tween.offset !== null }, isOffsetAbsolute: function(value) { return typeof value === "number" }, isOffsetRelative: function(value) { var t = typeof value; if (t === "string") { var op = value[0]; if (op === "-" || op === "+") { return true } } return false }, getRelativeOffset: function(value, base) { var op = value[0]; var num = parseFloat(value.substr(2)); var result = base; switch (op) { case "+": result += num; break; case "-": result -= num; break } return Math.max(0, result) }, calcDuration: function() { var prevEnd = 0; var totalDuration = 0; var offsetDuration = 0; for (var i = 0; i < this.totalData; i++) { var tween = this.data[i]; tween.init(); if (this.hasOffset(tween)) { if (this.isOffsetAbsolute(tween.offset)) { tween.calculatedOffset = tween.offset; if (tween.offset === 0) { offsetDuration = 0 } } else if (this.isOffsetRelative(tween.offset)) { tween.calculatedOffset = this.getRelativeOffset(tween.offset, prevEnd) } } else { tween.calculatedOffset = offsetDuration } prevEnd = tween.totalDuration + tween.calculatedOffset; totalDuration += tween.totalDuration; offsetDuration += tween.totalDuration } this.duration = totalDuration; this.loopCounter = this.loop === -1 ? 999999999999 : this.loop; if (this.loopCounter > 0) { this.totalDuration = this.duration + this.completeDelay + (this.duration + this.loopDelay) * this.loopCounter } else { this.totalDuration = this.duration + this.completeDelay } }, init: function() { this.calcDuration(); this.progress = 0; this.totalProgress = 0; if (this.paused) { this.state = TWEEN_CONST.PAUSED; return false } else { return true } }, resetTweens: function(resetFromLoop) { for (var i = 0; i < this.totalData; i++) { var tween = this.data[i]; tween.play(resetFromLoop) } }, setCallback: function(type, callback, params, scope) { if (Timeline.TYPES.indexOf(type) !== -1) { this.callbacks[type] = { func: callback, scope: scope, params: params } } return this }, makeActive: function(tween) { return this.manager.makeActive(tween) }, play: function() { if (this.state === TWEEN_CONST.ACTIVE) { return } if (this.paused) { this.paused = false; this.manager.makeActive(this); return } else { this.resetTweens(false); this.state = TWEEN_CONST.ACTIVE } var onStart = this.callbacks.onStart; if (onStart) { onStart.func.apply(onStart.scope, onStart.params) } this.emit("start", this) }, nextState: function() { if (this.loopCounter > 0) { this.elapsed = 0; this.progress = 0; this.loopCounter--; var onLoop = this.callbacks.onLoop; if (onLoop) { onLoop.func.apply(onLoop.scope, onLoop.params) } this.emit("loop", this, this.loopCounter); this.resetTweens(true); if (this.loopDelay > 0) { this.countdown = this.loopDelay; this.state = TWEEN_CONST.LOOP_DELAY } else { this.state = TWEEN_CONST.ACTIVE } } else if (this.completeDelay > 0) { this.countdown = this.completeDelay; this.state = TWEEN_CONST.COMPLETE_DELAY } else { var onComplete = this.callbacks.onComplete; if (onComplete) { onComplete.func.apply(onComplete.scope, onComplete.params) } this.emit("complete", this); this.state = TWEEN_CONST.PENDING_REMOVE } }, update: function(timestamp, delta) { if (this.state === TWEEN_CONST.PAUSED) { return } var rawDelta = delta; if (this.useFrames) { delta = 1 * this.manager.timeScale } delta *= this.timeScale; this.elapsed += delta; this.progress = Math.min(this.elapsed / this.duration, 1); this.totalElapsed += delta; this.totalProgress = Math.min(this.totalElapsed / this.totalDuration, 1); switch (this.state) { case TWEEN_CONST.ACTIVE: var stillRunning = this.totalData; for (var i = 0; i < this.totalData; i++) { var tween = this.data[i]; if (tween.update(timestamp, rawDelta)) { stillRunning-- } } var onUpdate = this.callbacks.onUpdate; if (onUpdate) { onUpdate.func.apply(onUpdate.scope, onUpdate.params) } this.emit("update", this); if (stillRunning === 0) { this.nextState() } break; case TWEEN_CONST.LOOP_DELAY: this.countdown -= delta; if (this.countdown <= 0) { this.state = TWEEN_CONST.ACTIVE } break; case TWEEN_CONST.COMPLETE_DELAY: this.countdown -= delta; if (this.countdown <= 0) { var onComplete = this.callbacks.onComplete; if (onComplete) { onComplete.func.apply(onComplete.scope, onComplete.params) } this.emit("complete", this); this.state = TWEEN_CONST.PENDING_REMOVE } break } return this.state === TWEEN_CONST.PENDING_REMOVE }, stop: function() { this.state = TWEEN_CONST.PENDING_REMOVE }, pause: function() { if (this.state === TWEEN_CONST.PAUSED) { return } this.paused = true; this._pausedState = this.state; this.state = TWEEN_CONST.PAUSED; this.emit("pause", this); return this }, resume: function() { if (this.state === TWEEN_CONST.PAUSED) { this.paused = false; this.state = this._pausedState } this.emit("resume", this); return this }, hasTarget: function(target) { for (var i = 0; i < this.data.length; i++) { if (this.data[i].hasTarget(target)) { return true } } return false }, destroy: function() { for (var i = 0; i < this.data.length; i++) { this.data[i].stop() } } }); Timeline.TYPES = ["onStart", "onUpdate", "onLoop", "onComplete", "onYoyo"]; module.exports = Timeline }, function(module, exports, __webpack_require__) { var Camera = __webpack_require__(221); var Class = __webpack_require__(0); var Vector3 = __webpack_require__(86); var tmpVec3 = new Vector3; var OrthographicCamera = new Class({ Extends: Camera, initialize: function OrthographicCamera(scene, viewportWidth, viewportHeight) { if (viewportWidth === undefined) { viewportWidth = 0 } if (viewportHeight === undefined) { viewportHeight = 0 } Camera.call(this, scene); this.viewportWidth = viewportWidth; this.viewportHeight = viewportHeight; this._zoom = 1; this.near = 0; this.update() }, setToOrtho: function(yDown, viewportWidth, viewportHeight) { if (viewportWidth === undefined) { viewportWidth = this.viewportWidth } if (viewportHeight === undefined) { viewportHeight = this.viewportHeight } var zoom = this.zoom; this.up.set(0, yDown ? -1 : 1, 0); this.direction.set(0, 0, yDown ? 1 : -1); this.position.set(zoom * viewportWidth / 2, zoom * viewportHeight / 2, 0); this.viewportWidth = viewportWidth; this.viewportHeight = viewportHeight; return this.update() }, update: function() { var w = this.viewportWidth; var h = this.viewportHeight; var near = Math.abs(this.near); var far = Math.abs(this.far); var zoom = this.zoom; if (w === 0 || h === 0) { return this } this.projection.ortho(zoom * -w / 2, zoom * w / 2, zoom * -h / 2, zoom * h / 2, near, far); tmpVec3.copy(this.position).add(this.direction); this.view.lookAt(this.position, tmpVec3, this.up); this.combined.copy(this.projection).multiply(this.view); this.invProjectionView.copy(this.combined).invert(); this.billboardMatrixDirty = true; this.updateChildren(); return this }, zoom: { get: function() { return this._zoom }, set: function(value) { this._zoom = value; this.update() } } }); module.exports = OrthographicCamera }, function(module, exports, __webpack_require__) { var Camera = __webpack_require__(221); var Class = __webpack_require__(0); var Vector3 = __webpack_require__(86); var tmpVec3 = new Vector3; var PerspectiveCamera = new Class({ Extends: Camera, initialize: function PerspectiveCamera(scene, fieldOfView, viewportWidth, viewportHeight) { if (fieldOfView === undefined) { fieldOfView = 80 } if (viewportWidth === undefined) { viewportWidth = 0 } if (viewportHeight === undefined) { viewportHeight = 0 } Camera.call(this, scene); this.viewportWidth = viewportWidth; this.viewportHeight = viewportHeight; this.fieldOfView = fieldOfView * Math.PI / 180; this.update() }, setFOV: function(value) { this.fieldOfView = value * Math.PI / 180; return this }, update: function() { var aspect = this.viewportWidth / this.viewportHeight; this.projection.perspective(this.fieldOfView, aspect, Math.abs(this.near), Math.abs(this.far)); tmpVec3.copy(this.position).add(this.direction); this.view.lookAt(this.position, tmpVec3, this.up); this.combined.copy(this.projection).multiply(this.view); this.invProjectionView.copy(this.combined).invert(); this.billboardMatrixDirty = true; this.updateChildren(); return this } }); module.exports = PerspectiveCamera }, , , , , , function(module, exports, __webpack_require__) { __webpack_require__(476); __webpack_require__(477); __webpack_require__(478); __webpack_require__(479); __webpack_require__(480); __webpack_require__(481); __webpack_require__(482); __webpack_require__(483) }, function(module, exports) { if (!Array.prototype.forEach) { Array.prototype.forEach = function(fun) { "use strict"; if (this === void 0 || this === null) { throw new TypeError } var t = Object(this); var len = t.length >>> 0; if (typeof fun !== "function") { throw new TypeError } var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { if (i in t) { fun.call(thisArg, t[i], i, t) } } } } }, function(module, exports) { if (!Array.isArray) { Array.isArray = function(arg) { return Object.prototype.toString.call(arg) === "[object Array]" } } }, function(module, exports) { (function() { function fixSetTarget(param) { if (!param) return; if (!param.setTargetAtTime) param.setTargetAtTime = param.setTargetValueAtTime } if (window.hasOwnProperty("webkitAudioContext") && !window.hasOwnProperty("AudioContext")) { window.AudioContext = webkitAudioContext; if (!AudioContext.prototype.hasOwnProperty("createGain")) AudioContext.prototype.createGain = AudioContext.prototype.createGainNode; if (!AudioContext.prototype.hasOwnProperty("createDelay")) AudioContext.prototype.createDelay = AudioContext.prototype.createDelayNode; if (!AudioContext.prototype.hasOwnProperty("createScriptProcessor")) AudioContext.prototype.createScriptProcessor = AudioContext.prototype.createJavaScriptNode; if (!AudioContext.prototype.hasOwnProperty("createPeriodicWave")) AudioContext.prototype.createPeriodicWave = AudioContext.prototype.createWaveTable; AudioContext.prototype.internal_createGain = AudioContext.prototype.createGain; AudioContext.prototype.createGain = function() { var node = this.internal_createGain(); fixSetTarget(node.gain); return node }; AudioContext.prototype.internal_createDelay = AudioContext.prototype.createDelay; AudioContext.prototype.createDelay = function(maxDelayTime) { var node = maxDelayTime ? this.internal_createDelay(maxDelayTime) : this.internal_createDelay(); fixSetTarget(node.delayTime); return node }; AudioContext.prototype.internal_createBufferSource = AudioContext.prototype.createBufferSource; AudioContext.prototype.createBufferSource = function() { var node = this.internal_createBufferSource(); if (!node.start) { node.start = function(when, offset, duration) { if (offset || duration) this.noteGrainOn(when || 0, offset, duration); else this.noteOn(when || 0) } } else { node.internal_start = node.start; node.start = function(when, offset, duration) { if (typeof duration !== "undefined") node.internal_start(when || 0, offset, duration); else node.internal_start(when || 0, offset || 0) } } if (!node.stop) { node.stop = function(when) { this.noteOff(when || 0) } } else { node.internal_stop = node.stop; node.stop = function(when) { node.internal_stop(when || 0) } } fixSetTarget(node.playbackRate); return node }; AudioContext.prototype.internal_createDynamicsCompressor = AudioContext.prototype.createDynamicsCompressor; AudioContext.prototype.createDynamicsCompressor = function() { var node = this.internal_createDynamicsCompressor(); fixSetTarget(node.threshold); fixSetTarget(node.knee); fixSetTarget(node.ratio); fixSetTarget(node.reduction); fixSetTarget(node.attack); fixSetTarget(node.release); return node }; AudioContext.prototype.internal_createBiquadFilter = AudioContext.prototype.createBiquadFilter; AudioContext.prototype.createBiquadFilter = function() { var node = this.internal_createBiquadFilter(); fixSetTarget(node.frequency); fixSetTarget(node.detune); fixSetTarget(node.Q); fixSetTarget(node.gain); return node }; if (AudioContext.prototype.hasOwnProperty("createOscillator")) { AudioContext.prototype.internal_createOscillator = AudioContext.prototype.createOscillator; AudioContext.prototype.createOscillator = function() { var node = this.internal_createOscillator(); if (!node.start) { node.start = function(when) { this.noteOn(when || 0) } } else { node.internal_start = node.start; node.start = function(when) { node.internal_start(when || 0) } } if (!node.stop) { node.stop = function(when) { this.noteOff(when || 0) } } else { node.internal_stop = node.stop; node.stop = function(when) { node.internal_stop(when || 0) } } if (!node.setPeriodicWave) node.setPeriodicWave = node.setWaveTable; fixSetTarget(node.frequency); fixSetTarget(node.detune); return node } } } if (window.hasOwnProperty("webkitOfflineAudioContext") && !window.hasOwnProperty("OfflineAudioContext")) { window.OfflineAudioContext = webkitOfflineAudioContext } })() }, function(module, exports) { if (!window.console) { window.console = {}; window.console.log = window.console.assert = function() {}; window.console.warn = window.console.assert = function() {} } }, function(module, exports) { if (!Math.trunc) { Math.trunc = function trunc(x) { return x < 0 ? Math.ceil(x) : Math.floor(x) } } }, function(module, exports) { (function() { if ("performance" in window === false) { window.performance = {} } Date.now = Date.now || function() { return (new Date).getTime() }; if ("now" in window.performance === false) { var nowOffset = Date.now(); if (performance.timing && performance.timing.navigationStart) { nowOffset = performance.timing.navigationStart } window.performance.now = function now() { return Date.now() - nowOffset } } })() }, function(module, exports, __webpack_require__) { (function(global) { if (!(Date.now && Date.prototype.getTime)) { Date.now = function now() { return (new Date).getTime() } } if (!(global.performance && global.performance.now)) { var startTime = Date.now(); if (!global.performance) { global.performance = {} } global.performance.now = function() { return Date.now() - startTime } } var lastTime = Date.now(); var vendors = ["ms", "moz", "webkit", "o"]; for (var x = 0; x < vendors.length && !global.requestAnimationFrame; ++x) { global.requestAnimationFrame = global[vendors[x] + "RequestAnimationFrame"]; global.cancelAnimationFrame = global[vendors[x] + "CancelAnimationFrame"] || global[vendors[x] + "CancelRequestAnimationFrame"] } if (!global.requestAnimationFrame) { global.requestAnimationFrame = function(callback) { if (typeof callback !== "function") { throw new TypeError(callback + "is not a function") } var currentTime = Date.now(), delay = 16 + lastTime - currentTime; if (delay < 0) { delay = 0 } lastTime = currentTime; return setTimeout(function() { lastTime = Date.now(); callback(performance.now()) }, delay) } } if (!global.cancelAnimationFrame) { global.cancelAnimationFrame = function(id) { clearTimeout(id) } } }).call(exports, __webpack_require__(142)) }, function(module, exports) { if (typeof window.Uint32Array !== "function" && typeof window.Uint32Array !== "object") { var CheapArray = function(fakeType) { var proto = new Array; window[fakeType] = function(arg) { if (typeof arg === "number") { Array.call(this, arg); this.length = arg; for (var i = 0; i < this.length; i++) { this[i] = 0 } } else { Array.call(this, arg.length); this.length = arg.length; for (var i = 0; i < this.length; i++) { this[i] = arg[i] } } }; window[fakeType].prototype = proto; window[fakeType].constructor = window[fakeType] }; CheapArray("Float32Array"); CheapArray("Uint32Array"); CheapArray("Uint16Array"); CheapArray("Int16Array"); CheapArray("ArrayBuffer") } }, function(module, exports, __webpack_require__) { var PropertyValueInc = __webpack_require__(35); var Angle = function(items, value, step, index, direction) { return PropertyValueInc(items, "angle", value, step, index, direction) }; module.exports = Angle }, function(module, exports) { var Call = function(items, callback, context) { for (var i = 0; i < items.length; i++) { var item = items[i]; callback.call(context, item) } return items }; module.exports = Call }, function(module, exports) { var GetFirst = function(items, compare, index) { if (index === undefined) { index = 0 } for (var i = index; i < items.length; i++) { var item = items[i]; var match = true; for (var property in compare) { if (item[property] !== compare[property]) { match = false } } if (match) { return item } } return null }; module.exports = GetFirst }, function(module, exports) { var GetLast = function(items, compare, index) { if (index === undefined) { index = 0 } for (var i = index; i < items.length; i++) { var item = items[i]; var match = true; for (var property in compare) { if (item[property] !== compare[property]) { match = false } } if (match) { return item } } return null }; module.exports = GetLast }, function(module, exports, __webpack_require__) { var AlignIn = __webpack_require__(226); var CONST = __webpack_require__(143); var GetFastValue = __webpack_require__(1); var NOOP = __webpack_require__(2); var Zone = __webpack_require__(107); var tempZone = new Zone({ sys: { queueDepthSort: NOOP, events: { once: NOOP } } }, 0, 0, 1, 1); var GridAlign = function(items, options) { if (options === undefined) { options = {} } var width = GetFastValue(options, "width", -1); var height = GetFastValue(options, "height", -1); var cellWidth = GetFastValue(options, "cellWidth", 1); var cellHeight = GetFastValue(options, "cellHeight", cellWidth); var position = GetFastValue(options, "position", CONST.TOP_LEFT); var x = GetFastValue(options, "x", 0); var y = GetFastValue(options, "y", 0); var cx = 0; var cy = 0; var w = width * cellWidth; var h = height * cellHeight; tempZone.setPosition(x, y); tempZone.setSize(cellWidth, cellHeight); for (var i = 0; i < items.length; i++) { AlignIn(items[i], tempZone, position); if (width === -1) { cy += cellHeight; tempZone.y += cellHeight; if (cy === h) { cy = 0; tempZone.x += cellWidth; tempZone.y = y } } else if (height === -1) { cx += cellWidth; tempZone.x += cellWidth; if (cx === w) { cx = 0; tempZone.x = x; tempZone.y += cellHeight } } else { cx += cellWidth; tempZone.x += cellWidth; if (cx === w) { cx = 0; cy += cellHeight; tempZone.x = x; tempZone.y += cellHeight; if (cy === h) { break } } } } return items }; module.exports = GridAlign }, function(module, exports) { var ComputedSize = { width: 0, height: 0, displayWidth: { get: function() { return this.scaleX * this.width }, set: function(value) { this.scaleX = value / this.width } }, displayHeight: { get: function() { return this.scaleY * this.height }, set: function(value) { this.scaleY = value / this.height } }, setSize: function(width, height) { this.width = width; this.height = height; return this }, setDisplaySize: function(width, height) { this.displayWidth = width; this.displayHeight = height; return this } }; module.exports = ComputedSize }, function(module, exports) { var Crop = { texture: null, frame: null, isCropped: false, setCrop: function(x, y, width, height) { if (x === undefined) { this.isCropped = false } else if (this.frame) { if (typeof x === "number") { this.frame.setCropUVs(this._crop, x, y, width, height, this.flipX, this.flipY) } else { var rect = x; this.frame.setCropUVs(this._crop, rect.x, rect.y, rect.width, rect.height, this.flipX, this.flipY) } this.isCropped = true } return this }, resetCropObject: function() { return { u0: 0, v0: 0, u1: 0, v1: 0, width: 0, height: 0, x: 0, y: 0, flipX: false, flipY: false, cx: 0, cy: 0, cw: 0, ch: 0 } } }; module.exports = Crop }, function(module, exports) { var Flip = { flipX: false, flipY: false, toggleFlipX: function() { this.flipX = !this.flipX; return this }, toggleFlipY: function() { this.flipY = !this.flipY; return this }, setFlipX: function(value) { this.flipX = value; return this }, setFlipY: function(value) { this.flipY = value; return this }, setFlip: function(x, y) { this.flipX = x; this.flipY = y; return this }, resetFlip: function() { this.flipX = false; this.flipY = false; return this } }; module.exports = Flip }, function(module, exports, __webpack_require__) { var Rectangle = __webpack_require__(9); var RotateAround = __webpack_require__(247); var Vector2 = __webpack_require__(3); var GetBounds = { getCenter: function(output) { if (output === undefined) { output = new Vector2 } output.x = this.x - this.displayWidth * this.originX + this.displayWidth / 2; output.y = this.y - this.displayHeight * this.originY + this.displayHeight / 2; return output }, getTopLeft: function(output, includeParent) { if (!output) { output = new Vector2 } if (includeParent === undefined) { includeParent = false } output.x = this.x - this.displayWidth * this.originX; output.y = this.y - this.displayHeight * this.originY; if (this.rotation !== 0) { RotateAround(output, this.x, this.y, this.rotation) } if (includeParent && this.parentContainer) { var parentMatrix = this.parentContainer.getBoundsTransformMatrix(); parentMatrix.transformPoint(output.x, output.y, output) } return output }, getTopRight: function(output, includeParent) { if (!output) { output = new Vector2 } if (includeParent === undefined) { includeParent = false } output.x = this.x - this.displayWidth * this.originX + this.displayWidth; output.y = this.y - this.displayHeight * this.originY; if (this.rotation !== 0) { RotateAround(output, this.x, this.y, this.rotation) } if (includeParent && this.parentContainer) { var parentMatrix = this.parentContainer.getBoundsTransformMatrix(); parentMatrix.transformPoint(output.x, output.y, output) } return output }, getBottomLeft: function(output, includeParent) { if (!output) { output = new Vector2 } if (includeParent === undefined) { includeParent = false } output.x = this.x - this.displayWidth * this.originX; output.y = this.y - this.displayHeight * this.originY + this.displayHeight; if (this.rotation !== 0) { RotateAround(output, this.x, this.y, this.rotation) } if (includeParent && this.parentContainer) { var parentMatrix = this.parentContainer.getBoundsTransformMatrix(); parentMatrix.transformPoint(output.x, output.y, output) } return output }, getBottomRight: function(output, includeParent) { if (!output) { output = new Vector2 } if (includeParent === undefined) { includeParent = false } output.x = this.x - this.displayWidth * this.originX + this.displayWidth; output.y = this.y - this.displayHeight * this.originY + this.displayHeight; if (this.rotation !== 0) { RotateAround(output, this.x, this.y, this.rotation) } if (includeParent && this.parentContainer) { var parentMatrix = this.parentContainer.getBoundsTransformMatrix(); parentMatrix.transformPoint(output.x, output.y, output) } return output }, getBounds: function(output) { if (output === undefined) { output = new Rectangle } var TLx, TLy, TRx, TRy, BLx, BLy, BRx, BRy; if (this.parentContainer) { var parentMatrix = this.parentContainer.getBoundsTransformMatrix(); this.getTopLeft(output); parentMatrix.transformPoint(output.x, output.y, output); TLx = output.x; TLy = output.y; this.getTopRight(output); parentMatrix.transformPoint(output.x, output.y, output); TRx = output.x; TRy = output.y; this.getBottomLeft(output); parentMatrix.transformPoint(output.x, output.y, output); BLx = output.x; BLy = output.y; this.getBottomRight(output); parentMatrix.transformPoint(output.x, output.y, output); BRx = output.x; BRy = output.y } else { this.getTopLeft(output); TLx = output.x; TLy = output.y; this.getTopRight(output); TRx = output.x; TRy = output.y; this.getBottomLeft(output); BLx = output.x; BLy = output.y; this.getBottomRight(output); BRx = output.x; BRy = output.y } output.x = Math.min(TLx, TRx, BLx, BRx); output.y = Math.min(TLy, TRy, BLy, BRy); output.width = Math.max(TLx, TRx, BLx, BRx) - output.x; output.height = Math.max(TLy, TRy, BLy, BRy) - output.y; return output } }; module.exports = GetBounds }, function(module, exports) { var Origin = { _originComponent: true, originX: .5, originY: .5, _displayOriginX: 0, _displayOriginY: 0, displayOriginX: { get: function() { return this._displayOriginX }, set: function(value) { this._displayOriginX = value; this.originX = value / this.width } }, displayOriginY: { get: function() { return this._displayOriginY }, set: function(value) { this._displayOriginY = value; this.originY = value / this.height } }, setOrigin: function(x, y) { if (x === undefined) { x = .5 } if (y === undefined) { y = x } this.originX = x; this.originY = y; return this.updateDisplayOrigin() }, setOriginFromFrame: function() { if (!this.frame || !this.frame.customPivot) { return this.setOrigin() } else { this.originX = this.frame.pivotX; this.originY = this.frame.pivotY } return this.updateDisplayOrigin() }, setDisplayOrigin: function(x, y) { if (x === undefined) { x = 0 } if (y === undefined) { y = x } this.displayOriginX = x; this.displayOriginY = y; return this }, updateDisplayOrigin: function() { this._displayOriginX = Math.round(this.originX * this.width); this._displayOriginY = Math.round(this.originY * this.height); return this } }; module.exports = Origin }, function(module, exports, __webpack_require__) { var ScaleModes = __webpack_require__(89); var ScaleMode = { _scaleMode: ScaleModes.DEFAULT, scaleMode: { get: function() { return this._scaleMode }, set: function(value) { if (value === ScaleModes.LINEAR || value === ScaleModes.NEAREST) { this._scaleMode = value } } }, setScaleMode: function(value) { this.scaleMode = value; return this } }; module.exports = ScaleMode }, function(module, exports) { var Size = { _sizeComponent: true, width: 0, height: 0, displayWidth: { get: function() { return this.scaleX * this.frame.realWidth }, set: function(value) { this.scaleX = value / this.frame.realWidth } }, displayHeight: { get: function() { return this.scaleY * this.frame.realHeight }, set: function(value) { this.scaleY = value / this.frame.realHeight } }, setSizeToFrame: function(frame) { if (frame === undefined) { frame = this.frame } this.width = frame.realWidth; this.height = frame.realHeight; return this }, setSize: function(width, height) { this.width = width; this.height = height; return this }, setDisplaySize: function(width, height) { this.displayWidth = width; this.displayHeight = height; return this } }; module.exports = Size }, function(module, exports) { var _FLAG = 8; var Texture = { texture: null, frame: null, isCropped: false, setTexture: function(key, frame) { this.texture = this.scene.sys.textures.get(key); return this.setFrame(frame) }, setFrame: function(frame, updateSize, updateOrigin) { if (updateSize === undefined) { updateSize = true } if (updateOrigin === undefined) { updateOrigin = true } this.frame = this.texture.get(frame); if (!this.frame.cutWidth || !this.frame.cutHeight) { this.renderFlags &= ~_FLAG } else { this.renderFlags |= _FLAG } if (this._sizeComponent && updateSize) { this.setSizeToFrame() } if (this._originComponent && updateOrigin) { if (this.frame.customPivot) { this.setOrigin(this.frame.pivotX, this.frame.pivotY) } else { this.updateDisplayOrigin() } } return this } }; module.exports = Texture }, function(module, exports) { var _FLAG = 8; var TextureCrop = { texture: null, frame: null, isCropped: false, setCrop: function(x, y, width, height) { if (x === undefined) { this.isCropped = false } else if (this.frame) { if (typeof x === "number") { this.frame.setCropUVs(this._crop, x, y, width, height, this.flipX, this.flipY) } else { var rect = x; this.frame.setCropUVs(this._crop, rect.x, rect.y, rect.width, rect.height, this.flipX, this.flipY) } this.isCropped = true } return this }, setTexture: function(key, frame) { this.texture = this.scene.sys.textures.get(key); return this.setFrame(frame) }, setFrame: function(frame, updateSize, updateOrigin) { if (updateSize === undefined) { updateSize = true } if (updateOrigin === undefined) { updateOrigin = true } this.frame = this.texture.get(frame); if (!this.frame.cutWidth || !this.frame.cutHeight) { this.renderFlags &= ~_FLAG } else { this.renderFlags |= _FLAG } if (this._sizeComponent && updateSize) { this.setSizeToFrame() } if (this._originComponent && updateOrigin) { if (this.frame.customPivot) { this.setOrigin(this.frame.pivotX, this.frame.pivotY) } else { this.updateDisplayOrigin() } } if (this.isCropped) { this.frame.updateCropUVs(this._crop, this.flipX, this.flipY) } return this }, resetCropObject: function() { return { u0: 0, v0: 0, u1: 0, v1: 0, width: 0, height: 0, x: 0, y: 0, flipX: false, flipY: false, cx: 0, cy: 0, cw: 0, ch: 0 } } }; module.exports = TextureCrop }, function(module, exports) { var GetColor = function(value) { return (value >> 16) + (value & 65280) + ((value & 255) << 16) }; var Tint = { _tintTL: 16777215, _tintTR: 16777215, _tintBL: 16777215, _tintBR: 16777215, _isTinted: false, tintFill: false, clearTint: function() { this.setTint(16777215); this._isTinted = false; return this }, setTint: function(topLeft, topRight, bottomLeft, bottomRight) { if (topLeft === undefined) { topLeft = 16777215 } if (topRight === undefined) { topRight = topLeft; bottomLeft = topLeft; bottomRight = topLeft } this._tintTL = GetColor(topLeft); this._tintTR = GetColor(topRight); this._tintBL = GetColor(bottomLeft); this._tintBR = GetColor(bottomRight); this._isTinted = true; this.tintFill = false; return this }, setTintFill: function(topLeft, topRight, bottomLeft, bottomRight) { this.setTint(topLeft, topRight, bottomLeft, bottomRight); this.tintFill = true; return this }, tintTopLeft: { get: function() { return this._tintTL }, set: function(value) { this._tintTL = GetColor(value); this._isTinted = true } }, tintTopRight: { get: function() { return this._tintTR }, set: function(value) { this._tintTR = GetColor(value); this._isTinted = true } }, tintBottomLeft: { get: function() { return this._tintBL }, set: function(value) { this._tintBL = GetColor(value); this._isTinted = true } }, tintBottomRight: { get: function() { return this._tintBR }, set: function(value) { this._tintBR = GetColor(value); this._isTinted = true } }, tint: { set: function(value) { this.setTint(value, value, value, value) } }, isTinted: { get: function() { return this._isTinted } } }; module.exports = Tint }, function(module, exports, __webpack_require__) { var PropertyValueInc = __webpack_require__(35); var IncAlpha = function(items, value, step, index, direction) { return PropertyValueInc(items, "alpha", value, step, index, direction) }; module.exports = IncAlpha }, function(module, exports, __webpack_require__) { var PropertyValueInc = __webpack_require__(35); var IncX = function(items, value, step, index, direction) { return PropertyValueInc(items, "x", value, step, index, direction) }; module.exports = IncX }, function(module, exports, __webpack_require__) { var PropertyValueInc = __webpack_require__(35); var IncXY = function(items, x, y, stepX, stepY, index, direction) { if (y === undefined || y === null) { y = x } PropertyValueInc(items, "x", x, stepX, index, direction); return PropertyValueInc(items, "y", y, stepY, index, direction) }; module.exports = IncXY }, function(module, exports, __webpack_require__) { var PropertyValueInc = __webpack_require__(35); var IncY = function(items, value, step, index, direction) { return PropertyValueInc(items, "y", value, step, index, direction) }; module.exports = IncY }, function(module, exports) { var PlaceOnCircle = function(items, circle, startAngle, endAngle) { if (startAngle === undefined) { startAngle = 0 } if (endAngle === undefined) { endAngle = 6.28 } var angle = startAngle; var angleStep = (endAngle - startAngle) / items.length; for (var i = 0; i < items.length; i++) { items[i].x = circle.x + circle.radius * Math.cos(angle); items[i].y = circle.y + circle.radius * Math.sin(angle); angle += angleStep } return items }; module.exports = PlaceOnCircle }, function(module, exports) { var PlaceOnEllipse = function(items, ellipse, startAngle, endAngle) { if (startAngle === undefined) { startAngle = 0 } if (endAngle === undefined) { endAngle = 6.28 } var angle = startAngle; var angleStep = (endAngle - startAngle) / items.length; var a = ellipse.width / 2; var b = ellipse.height / 2; for (var i = 0; i < items.length; i++) { items[i].x = ellipse.x + a * Math.cos(angle); items[i].y = ellipse.y + b * Math.sin(angle); angle += angleStep } return items }; module.exports = PlaceOnEllipse }, function(module, exports, __webpack_require__) { var GetPoints = __webpack_require__(147); var PlaceOnLine = function(items, line) { var points = GetPoints(line, items.length); for (var i = 0; i < items.length; i++) { var item = items[i]; var point = points[i]; item.x = point.x; item.y = point.y } return items }; module.exports = PlaceOnLine }, function(module, exports, __webpack_require__) { var MarchingAnts = __webpack_require__(255); var RotateLeft = __webpack_require__(256); var RotateRight = __webpack_require__(257); var PlaceOnRectangle = function(items, rect, shift) { if (shift === undefined) { shift = 0 } var points = MarchingAnts(rect, false, items.length); if (shift > 0) { RotateLeft(points, shift) } else if (shift < 0) { RotateRight(points, Math.abs(shift)) } for (var i = 0; i < items.length; i++) { items[i].x = points[i].x; items[i].y = points[i].y } return items }; module.exports = PlaceOnRectangle }, function(module, exports, __webpack_require__) { var BresenhamPoints = __webpack_require__(258); var PlaceOnTriangle = function(items, triangle, stepRate) { var p1 = BresenhamPoints({ x1: triangle.x1, y1: triangle.y1, x2: triangle.x2, y2: triangle.y2 }, stepRate); var p2 = BresenhamPoints({ x1: triangle.x2, y1: triangle.y2, x2: triangle.x3, y2: triangle.y3 }, stepRate); var p3 = BresenhamPoints({ x1: triangle.x3, y1: triangle.y3, x2: triangle.x1, y2: triangle.y1 }, stepRate); p1.pop(); p2.pop(); p3.pop(); p1 = p1.concat(p2, p3); var step = p1.length / items.length; var p = 0; for (var i = 0; i < items.length; i++) { var item = items[i]; var point = p1[Math.floor(p)]; item.x = point.x; item.y = point.y; p += step } return items }; module.exports = PlaceOnTriangle }, function(module, exports) { var PlayAnimation = function(items, key, startFrame) { for (var i = 0; i < items.length; i++) { items[i].anims.play(key, startFrame) } return items }; module.exports = PlayAnimation }, function(module, exports, __webpack_require__) { var Random = __webpack_require__(145); var RandomCircle = function(items, circle) { for (var i = 0; i < items.length; i++) { Random(circle, items[i]) } return items }; module.exports = RandomCircle }, function(module, exports, __webpack_require__) { var Random = __webpack_require__(152); var RandomEllipse = function(items, ellipse) { for (var i = 0; i < items.length; i++) { Random(ellipse, items[i]) } return items }; module.exports = RandomEllipse }, function(module, exports, __webpack_require__) { var Random = __webpack_require__(148); var RandomLine = function(items, line) { for (var i = 0; i < items.length; i++) { Random(line, items[i]) } return items }; module.exports = RandomLine }, function(module, exports, __webpack_require__) { var Random = __webpack_require__(149); var RandomRectangle = function(items, rect) { for (var i = 0; i < items.length; i++) { Random(rect, items[i]) } return items }; module.exports = RandomRectangle }, function(module, exports, __webpack_require__) { var Random = __webpack_require__(153); var RandomTriangle = function(items, triangle) { for (var i = 0; i < items.length; i++) { Random(triangle, items[i]) } return items }; module.exports = RandomTriangle }, function(module, exports, __webpack_require__) { var PropertyValueInc = __webpack_require__(35); var Rotate = function(items, value, step, index, direction) { return PropertyValueInc(items, "rotation", value, step, index, direction) }; module.exports = Rotate }, function(module, exports, __webpack_require__) { var RotateAroundDistance = __webpack_require__(154); var DistanceBetween = __webpack_require__(56); var RotateAround = function(items, point, angle) { var x = point.x; var y = point.y; for (var i = 0; i < items.length; i++) { var item = items[i]; RotateAroundDistance(item, x, y, angle, Math.max(1, DistanceBetween(item.x, item.y, x, y))) } return items }; module.exports = RotateAround }, function(module, exports, __webpack_require__) { var MathRotateAroundDistance = __webpack_require__(154); var RotateAroundDistance = function(items, point, angle, distance) { var x = point.x; var y = point.y; if (distance === 0) { return items } for (var i = 0; i < items.length; i++) { MathRotateAroundDistance(items[i], x, y, angle, distance) } return items }; module.exports = RotateAroundDistance }, function(module, exports, __webpack_require__) { var PropertyValueInc = __webpack_require__(35); var ScaleX = function(items, value, step, index, direction) { return PropertyValueInc(items, "scaleX", value, step, index, direction) }; module.exports = ScaleX }, function(module, exports, __webpack_require__) { var PropertyValueInc = __webpack_require__(35); var ScaleXY = function(items, scaleX, scaleY, stepX, stepY, index, direction) { if (scaleY === undefined || scaleY === null) { scaleY = scaleX } PropertyValueInc(items, "scaleX", scaleX, stepX, index, direction); return PropertyValueInc(items, "scaleY", scaleY, stepY, index, direction) }; module.exports = ScaleXY }, function(module, exports, __webpack_require__) { var PropertyValueInc = __webpack_require__(35); var ScaleY = function(items, value, step, index, direction) { return PropertyValueInc(items, "scaleY", value, step, index, direction) }; module.exports = ScaleY }, function(module, exports, __webpack_require__) { var PropertyValueSet = __webpack_require__(27); var SetAlpha = function(items, value, step, index, direction) { return PropertyValueSet(items, "alpha", value, step, index, direction) }; module.exports = SetAlpha }, function(module, exports, __webpack_require__) { var PropertyValueSet = __webpack_require__(27); var SetBlendMode = function(items, value, index, direction) { return PropertyValueSet(items, "blendMode", value, 0, index, direction) }; module.exports = SetBlendMode }, function(module, exports, __webpack_require__) { var PropertyValueSet = __webpack_require__(27); var SetDepth = function(items, value, step, index, direction) { return PropertyValueSet(items, "depth", value, step, index, direction) }; module.exports = SetDepth }, function(module, exports) { var SetHitArea = function(items, hitArea, hitAreaCallback) { for (var i = 0; i < items.length; i++) { items[i].setInteractive(hitArea, hitAreaCallback) } return items }; module.exports = SetHitArea }, function(module, exports, __webpack_require__) { var PropertyValueSet = __webpack_require__(27); var SetOrigin = function(items, originX, originY, stepX, stepY, index, direction) { if (originY === undefined || originY === null) { originY = originX } PropertyValueSet(items, "originX", originX, stepX, index, direction); return PropertyValueSet(items, "originY", originY, stepY, index, direction) }; module.exports = SetOrigin }, function(module, exports, __webpack_require__) { var PropertyValueSet = __webpack_require__(27); var SetRotation = function(items, value, step, index, direction) { return PropertyValueSet(items, "rotation", value, step, index, direction) }; module.exports = SetRotation }, function(module, exports, __webpack_require__) { var PropertyValueSet = __webpack_require__(27); var SetScale = function(items, scaleX, scaleY, stepX, stepY, index, direction) { if (scaleY === undefined || scaleY === null) { scaleY = scaleX } PropertyValueSet(items, "scaleX", scaleX, stepX, index, direction); return PropertyValueSet(items, "scaleY", scaleY, stepY, index, direction) }; module.exports = SetScale }, function(module, exports, __webpack_require__) { var PropertyValueSet = __webpack_require__(27); var SetScaleX = function(items, value, step, index, direction) { return PropertyValueSet(items, "scaleX", value, step, index, direction) }; module.exports = SetScaleX }, function(module, exports, __webpack_require__) { var PropertyValueSet = __webpack_require__(27); var SetScaleY = function(items, value, step, index, direction) { return PropertyValueSet(items, "scaleY", value, step, index, direction) }; module.exports = SetScaleY }, function(module, exports) { var SetTint = function(items, topLeft, topRight, bottomLeft, bottomRight) { for (var i = 0; i < items.length; i++) { items[i].setTint(topLeft, topRight, bottomLeft, bottomRight) } return items }; module.exports = SetTint }, function(module, exports, __webpack_require__) { var PropertyValueSet = __webpack_require__(27); var SetVisible = function(items, value, index, direction) { return PropertyValueSet(items, "visible", value, 0, index, direction) }; module.exports = SetVisible }, function(module, exports, __webpack_require__) { var PropertyValueSet = __webpack_require__(27); var SetX = function(items, value, step, index, direction) { return PropertyValueSet(items, "x", value, step, index, direction) }; module.exports = SetX }, function(module, exports, __webpack_require__) { var PropertyValueSet = __webpack_require__(27); var SetXY = function(items, x, y, stepX, stepY, index, direction) { if (y === undefined || y === null) { y = x } PropertyValueSet(items, "x", x, stepX, index, direction); return PropertyValueSet(items, "y", y, stepY, index, direction) }; module.exports = SetXY }, function(module, exports, __webpack_require__) { var PropertyValueSet = __webpack_require__(27); var SetY = function(items, value, step, index, direction) { return PropertyValueSet(items, "y", value, step, index, direction) }; module.exports = SetY }, function(module, exports, __webpack_require__) { var Vector2 = __webpack_require__(3); var ShiftPosition = function(items, x, y, direction, output) { if (direction === undefined) { direction = 0 } if (output === undefined) { output = new Vector2 } var px; var py; if (items.length > 1) { var i; var cx; var cy; var cur; if (direction === 0) { var len = items.length - 1; px = items[len].x; py = items[len].y; for (i = len - 1; i >= 0; i--) { cur = items[i]; cx = cur.x; cy = cur.y; cur.x = px; cur.y = py; px = cx; py = cy } items[len].x = x; items[len].y = y } else { px = items[0].x; py = items[0].y; for (i = 1; i < items.length; i++) { cur = items[i]; cx = cur.x; cy = cur.y; cur.x = px; cur.y = py; px = cx; py = cy } items[0].x = x; items[0].y = y } } else { px = items[0].x; py = items[0].y; items[0].x = x; items[0].y = y } output.x = px; output.y = py; return output }; module.exports = ShiftPosition }, function(module, exports, __webpack_require__) { var ArrayShuffle = __webpack_require__(110); var Shuffle = function(items) { return ArrayShuffle(items) }; module.exports = Shuffle }, function(module, exports, __webpack_require__) { var MathSmootherStep = __webpack_require__(155); var SmootherStep = function(items, property, min, max, inc) { if (inc === undefined) { inc = false } var step = Math.abs(max - min) / items.length; var i; if (inc) { for (i = 0; i < items.length; i++) { items[i][property] += MathSmootherStep(i * step, min, max) } } else { for (i = 0; i < items.length; i++) { items[i][property] = MathSmootherStep(i * step, min, max) } } return items }; module.exports = SmootherStep }, function(module, exports, __webpack_require__) { var MathSmoothStep = __webpack_require__(156); var SmoothStep = function(items, property, min, max, inc) { if (inc === undefined) { inc = false } var step = Math.abs(max - min) / items.length; var i; if (inc) { for (i = 0; i < items.length; i++) { items[i][property] += MathSmoothStep(i * step, min, max) } } else { for (i = 0; i < items.length; i++) { items[i][property] = MathSmoothStep(i * step, min, max) } } return items }; module.exports = SmoothStep }, function(module, exports) { var Spread = function(items, property, min, max, inc) { if (inc === undefined) { inc = false } var step = Math.abs(max - min) / items.length; var i; if (inc) { for (i = 0; i < items.length; i++) { items[i][property] += i * step } } else { for (i = 0; i < items.length; i++) { items[i][property] = i * step } } return items }; module.exports = Spread }, function(module, exports) { var ToggleVisible = function(items) { for (var i = 0; i < items.length; i++) { items[i].visible = !items[i].visible } return items }; module.exports = ToggleVisible }, function(module, exports, __webpack_require__) { var Wrap = __webpack_require__(55); var WrapInRectangle = function(items, rect, padding) { if (padding === undefined) { padding = 0 } for (var i = 0; i < items.length; i++) { var item = items[i]; item.x = Wrap(item.x, rect.left - padding, rect.right + padding); item.y = Wrap(item.y, rect.top - padding, rect.bottom + padding) } return items }; module.exports = WrapInRectangle }, function(module, exports, __webpack_require__) { module.exports = { Animation: __webpack_require__(259), AnimationFrame: __webpack_require__(261), AnimationManager: __webpack_require__(262) } }, function(module, exports, __webpack_require__) { module.exports = { BaseCache: __webpack_require__(263), CacheManager: __webpack_require__(264) } }, function(module, exports, __webpack_require__) { module.exports = { Controls: __webpack_require__(544), Scene2D: __webpack_require__(547) } }, function(module, exports, __webpack_require__) { module.exports = { FixedKeyControl: __webpack_require__(545), SmoothedKeyControl: __webpack_require__(546) } }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var GetValue = __webpack_require__(4); var FixedKeyControl = new Class({ initialize: function FixedKeyControl(config) { this.camera = GetValue(config, "camera", null); this.left = GetValue(config, "left", null); this.right = GetValue(config, "right", null); this.up = GetValue(config, "up", null); this.down = GetValue(config, "down", null); this.zoomIn = GetValue(config, "zoomIn", null); this.zoomOut = GetValue(config, "zoomOut", null); this.zoomSpeed = GetValue(config, "zoomSpeed", .01); this.speedX = 0; this.speedY = 0; var speed = GetValue(config, "speed", null); if (typeof speed === "number") { this.speedX = speed; this.speedY = speed } else { this.speedX = GetValue(config, "speed.x", 0); this.speedY = GetValue(config, "speed.y", 0) } this._zoom = 0; this.active = this.camera !== null }, start: function() { this.active = this.camera !== null; return this }, stop: function() { this.active = false; return this }, setCamera: function(camera) { this.camera = camera; return this }, update: function(delta) { if (!this.active) { return } if (delta === undefined) { delta = 1 } var cam = this.camera; if (this.up && this.up.isDown) { cam.scrollY -= this.speedY * delta | 0 } else if (this.down && this.down.isDown) { cam.scrollY += this.speedY * delta | 0 } if (this.left && this.left.isDown) { cam.scrollX -= this.speedX * delta | 0 } else if (this.right && this.right.isDown) { cam.scrollX += this.speedX * delta | 0 } if (this.zoomIn && this.zoomIn.isDown) { cam.zoom -= this.zoomSpeed; if (cam.zoom < .1) { cam.zoom = .1 } } else if (this.zoomOut && this.zoomOut.isDown) { cam.zoom += this.zoomSpeed } }, destroy: function() { this.camera = null; this.left = null; this.right = null; this.up = null; this.down = null; this.zoomIn = null; this.zoomOut = null } }); module.exports = FixedKeyControl }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var GetValue = __webpack_require__(4); var SmoothedKeyControl = new Class({ initialize: function SmoothedKeyControl(config) { this.camera = GetValue(config, "camera", null); this.left = GetValue(config, "left", null); this.right = GetValue(config, "right", null); this.up = GetValue(config, "up", null); this.down = GetValue(config, "down", null); this.zoomIn = GetValue(config, "zoomIn", null); this.zoomOut = GetValue(config, "zoomOut", null); this.zoomSpeed = GetValue(config, "zoomSpeed", .01); this.accelX = 0; this.accelY = 0; var accel = GetValue(config, "acceleration", null); if (typeof accel === "number") { this.accelX = accel; this.accelY = accel } else { this.accelX = GetValue(config, "acceleration.x", 0); this.accelY = GetValue(config, "acceleration.y", 0) } this.dragX = 0; this.dragY = 0; var drag = GetValue(config, "drag", null); if (typeof drag === "number") { this.dragX = drag; this.dragY = drag } else { this.dragX = GetValue(config, "drag.x", 0); this.dragY = GetValue(config, "drag.y", 0) } this.maxSpeedX = 0; this.maxSpeedY = 0; var maxSpeed = GetValue(config, "maxSpeed", null); if (typeof maxSpeed === "number") { this.maxSpeedX = maxSpeed; this.maxSpeedY = maxSpeed } else { this.maxSpeedX = GetValue(config, "maxSpeed.x", 0); this.maxSpeedY = GetValue(config, "maxSpeed.y", 0) } this._speedX = 0; this._speedY = 0; this._zoom = 0; this.active = this.camera !== null }, start: function() { this.active = this.camera !== null; return this }, stop: function() { this.active = false; return this }, setCamera: function(camera) { this.camera = camera; return this }, update: function(delta) { if (!this.active) { return } if (delta === undefined) { delta = 1 } var cam = this.camera; if (this._speedX > 0) { this._speedX -= this.dragX * delta; if (this._speedX < 0) { this._speedX = 0 } } else if (this._speedX < 0) { this._speedX += this.dragX * delta; if (this._speedX > 0) { this._speedX = 0 } } if (this._speedY > 0) { this._speedY -= this.dragY * delta; if (this._speedY < 0) { this._speedY = 0 } } else if (this._speedY < 0) { this._speedY += this.dragY * delta; if (this._speedY > 0) { this._speedY = 0 } } if (this.up && this.up.isDown) { this._speedY += this.accelY; if (this._speedY > this.maxSpeedY) { this._speedY = this.maxSpeedY } } else if (this.down && this.down.isDown) { this._speedY -= this.accelY; if (this._speedY < -this.maxSpeedY) { this._speedY = -this.maxSpeedY } } if (this.left && this.left.isDown) { this._speedX += this.accelX; if (this._speedX > this.maxSpeedX) { this._speedX = this.maxSpeedX } } else if (this.right && this.right.isDown) { this._speedX -= this.accelX; if (this._speedX < -this.maxSpeedX) { this._speedX = -this.maxSpeedX } } if (this.zoomIn && this.zoomIn.isDown) { this._zoom = -this.zoomSpeed } else if (this.zoomOut && this.zoomOut.isDown) { this._zoom = this.zoomSpeed } else { this._zoom = 0 } if (this._speedX !== 0) { cam.scrollX -= this._speedX * delta | 0 } if (this._speedY !== 0) { cam.scrollY -= this._speedY * delta | 0 } if (this._zoom !== 0) { cam.zoom += this._zoom; if (cam.zoom < .1) { cam.zoom = .1 } } }, destroy: function() { this.camera = null; this.left = null; this.right = null; this.up = null; this.down = null; this.zoomIn = null; this.zoomOut = null } }); module.exports = SmoothedKeyControl }, function(module, exports, __webpack_require__) { module.exports = { Camera: __webpack_require__(265), CameraManager: __webpack_require__(585), Effects: __webpack_require__(273) } }, function(module, exports, __webpack_require__) { var Clamp = __webpack_require__(23); var Class = __webpack_require__(0); var Fade = new Class({ initialize: function Fade(camera) { this.camera = camera; this.isRunning = false; this.isComplete = false; this.direction = true; this.duration = 0; this.red = 0; this.green = 0; this.blue = 0; this.alpha = 0; this.progress = 0; this._elapsed = 0; this._onUpdate; this._onUpdateScope }, start: function(direction, duration, red, green, blue, force, callback, context) { if (direction === undefined) { direction = true } if (duration === undefined) { duration = 1e3 } if (red === undefined) { red = 0 } if (green === undefined) { green = 0 } if (blue === undefined) { blue = 0 } if (force === undefined) { force = false } if (callback === undefined) { callback = null } if (context === undefined) { context = this.camera.scene } if (!force && this.isRunning) { return this.camera } this.isRunning = true; this.isComplete = false; this.duration = duration; this.direction = direction; this.progress = 0; this.red = red; this.green = green; this.blue = blue; this.alpha = direction ? Number.MIN_VALUE : 1; this._elapsed = 0; this._onUpdate = callback; this._onUpdateScope = context; var eventName = direction ? "camerafadeoutstart" : "camerafadeinstart"; this.camera.emit(eventName, this.camera, this, duration, red, green, blue); return this.camera }, update: function(time, delta) { if (!this.isRunning) { return } this._elapsed += delta; this.progress = Clamp(this._elapsed / this.duration, 0, 1); if (this._onUpdate) { this._onUpdate.call(this._onUpdateScope, this.camera, this.progress) } if (this._elapsed < this.duration) { this.alpha = this.direction ? this.progress : 1 - this.progress } else { this.effectComplete() } }, postRenderCanvas: function(ctx) { if (!this.isRunning && !this.isComplete) { return false } var camera = this.camera; ctx.fillStyle = "rgba(" + this.red + "," + this.green + "," + this.blue + "," + this.alpha + ")"; ctx.fillRect(camera._cx, camera._cy, camera._cw, camera._ch); return true }, postRenderWebGL: function(pipeline, getTintFunction) { if (!this.isRunning && !this.isComplete) { return false } var camera = this.camera; var red = this.red / 255; var blue = this.blue / 255; var green = this.green / 255; pipeline.drawFillRect(camera._cx, camera._cy, camera._cw, camera._ch, getTintFunction(red, green, blue, 1), this.alpha); return true }, effectComplete: function() { this._onUpdate = null; this._onUpdateScope = null; this.isRunning = false; this.isComplete = true; var eventName = this.direction ? "camerafadeoutcomplete" : "camerafadeincomplete"; this.camera.emit(eventName, this.camera, this) }, reset: function() { this.isRunning = false; this.isComplete = false; this._onUpdate = null; this._onUpdateScope = null }, destroy: function() { this.reset(); this.camera = null } }); module.exports = Fade }, function(module, exports, __webpack_require__) { var Clamp = __webpack_require__(23); var Class = __webpack_require__(0); var Flash = new Class({ initialize: function Flash(camera) { this.camera = camera; this.isRunning = false; this.duration = 0; this.red = 0; this.green = 0; this.blue = 0; this.alpha = 0; this.progress = 0; this._elapsed = 0; this._onUpdate; this._onUpdateScope }, start: function(duration, red, green, blue, force, callback, context) { if (duration === undefined) { duration = 250 } if (red === undefined) { red = 255 } if (green === undefined) { green = 255 } if (blue === undefined) { blue = 255 } if (force === undefined) { force = false } if (callback === undefined) { callback = null } if (context === undefined) { context = this.camera.scene } if (!force && this.isRunning) { return this.camera } this.isRunning = true; this.duration = duration; this.progress = 0; this.red = red; this.green = green; this.blue = blue; this.alpha = 1; this._elapsed = 0; this._onUpdate = callback; this._onUpdateScope = context; this.camera.emit("cameraflashstart", this.camera, this, duration, red, green, blue); return this.camera }, update: function(time, delta) { if (!this.isRunning) { return } this._elapsed += delta; this.progress = Clamp(this._elapsed / this.duration, 0, 1); if (this._onUpdate) { this._onUpdate.call(this._onUpdateScope, this.camera, this.progress) } if (this._elapsed < this.duration) { this.alpha = 1 - this.progress } else { this.effectComplete() } }, postRenderCanvas: function(ctx) { if (!this.isRunning) { return false } var camera = this.camera; ctx.fillStyle = "rgba(" + this.red + "," + this.green + "," + this.blue + "," + this.alpha + ")"; ctx.fillRect(camera._cx, camera._cy, camera._cw, camera._ch); return true }, postRenderWebGL: function(pipeline, getTintFunction) { if (!this.isRunning) { return false } var camera = this.camera; var red = this.red / 255; var blue = this.blue / 255; var green = this.green / 255; pipeline.drawFillRect(camera._cx, camera._cy, camera._cw, camera._ch, getTintFunction(red, green, blue, 1), this.alpha); return true }, effectComplete: function() { this._onUpdate = null; this._onUpdateScope = null; this.isRunning = false; this.camera.emit("cameraflashcomplete", this.camera, this) }, reset: function() { this.isRunning = false; this._onUpdate = null; this._onUpdateScope = null }, destroy: function() { this.reset(); this.camera = null } }); module.exports = Flash }, function(module, exports, __webpack_require__) { var Clamp = __webpack_require__(23); var Class = __webpack_require__(0); var Vector2 = __webpack_require__(3); var EaseMap = __webpack_require__(163); var Pan = new Class({ initialize: function Pan(camera) { this.camera = camera; this.isRunning = false; this.duration = 0; this.source = new Vector2; this.current = new Vector2; this.destination = new Vector2; this.ease; this.progress = 0; this._elapsed = 0; this._onUpdate; this._onUpdateScope }, start: function(x, y, duration, ease, force, callback, context) { if (duration === undefined) { duration = 1e3 } if (ease === undefined) { ease = EaseMap.Linear } if (force === undefined) { force = false } if (callback === undefined) { callback = null } if (context === undefined) { context = this.camera.scene } var cam = this.camera; if (!force && this.isRunning) { return cam } this.isRunning = true; this.duration = duration; this.progress = 0; this.source.set(cam.scrollX, cam.scrollY); this.destination.set(x, y); cam.getScroll(x, y, this.current); if (typeof ease === "string" && EaseMap.hasOwnProperty(ease)) { this.ease = EaseMap[ease] } else if (typeof ease === "function") { this.ease = ease } this._elapsed = 0; this._onUpdate = callback; this._onUpdateScope = context; this.camera.emit("camerapanstart", this.camera, this, duration, x, y); return cam }, update: function(time, delta) { if (!this.isRunning) { return } this._elapsed += delta; var progress = Clamp(this._elapsed / this.duration, 0, 1); this.progress = progress; var cam = this.camera; if (this._elapsed < this.duration) { var v = this.ease(progress); cam.getScroll(this.destination.x, this.destination.y, this.current); var x = this.source.x + (this.current.x - this.source.x) * v; var y = this.source.y + (this.current.y - this.source.y) * v; cam.setScroll(x, y); if (this._onUpdate) { this._onUpdate.call(this._onUpdateScope, cam, progress, x, y) } } else { cam.centerOn(this.destination.x, this.destination.y); if (this._onUpdate) { this._onUpdate.call(this._onUpdateScope, cam, progress, cam.scrollX, cam.scrollY) } this.effectComplete() } }, effectComplete: function() { this._onUpdate = null; this._onUpdateScope = null; this.isRunning = false; this.camera.emit("camerapancomplete", this.camera, this) }, reset: function() { this.isRunning = false; this._onUpdate = null; this._onUpdateScope = null }, destroy: function() { this.reset(); this.camera = null; this.source = null; this.destination = null } }); module.exports = Pan }, function(module, exports) { var In = function(v, overshoot) { if (overshoot === undefined) { overshoot = 1.70158 } return v * v * ((overshoot + 1) * v - overshoot) }; module.exports = In }, function(module, exports) { var Out = function(v, overshoot) { if (overshoot === undefined) { overshoot = 1.70158 } return --v * v * ((overshoot + 1) * v + overshoot) + 1 }; module.exports = Out }, function(module, exports) { var InOut = function(v, overshoot) { if (overshoot === undefined) { overshoot = 1.70158 } var s = overshoot * 1.525; if ((v *= 2) < 1) { return .5 * (v * v * ((s + 1) * v - s)) } else { return .5 * ((v -= 2) * v * ((s + 1) * v + s) + 2) } }; module.exports = InOut }, function(module, exports) { var In = function(v) { v = 1 - v; if (v < 1 / 2.75) { return 1 - 7.5625 * v * v } else if (v < 2 / 2.75) { return 1 - (7.5625 * (v -= 1.5 / 2.75) * v + .75) } else if (v < 2.5 / 2.75) { return 1 - (7.5625 * (v -= 2.25 / 2.75) * v + .9375) } else { return 1 - (7.5625 * (v -= 2.625 / 2.75) * v + .984375) } }; module.exports = In }, function(module, exports) { var Out = function(v) { if (v < 1 / 2.75) { return 7.5625 * v * v } else if (v < 2 / 2.75) { return 7.5625 * (v -= 1.5 / 2.75) * v + .75 } else if (v < 2.5 / 2.75) { return 7.5625 * (v -= 2.25 / 2.75) * v + .9375 } else { return 7.5625 * (v -= 2.625 / 2.75) * v + .984375 } }; module.exports = Out }, function(module, exports) { var InOut = function(v) { var reverse = false; if (v < .5) { v = 1 - v * 2; reverse = true } else { v = v * 2 - 1 } if (v < 1 / 2.75) { v = 7.5625 * v * v } else if (v < 2 / 2.75) { v = 7.5625 * (v -= 1.5 / 2.75) * v + .75 } else if (v < 2.5 / 2.75) { v = 7.5625 * (v -= 2.25 / 2.75) * v + .9375 } else { v = 7.5625 * (v -= 2.625 / 2.75) * v + .984375 } if (reverse) { return (1 - v) * .5 } else { return v * .5 + .5 } }; module.exports = InOut }, function(module, exports) { var In = function(v) { return 1 - Math.sqrt(1 - v * v) }; module.exports = In }, function(module, exports) { var Out = function(v) { return Math.sqrt(1 - --v * v) }; module.exports = Out }, function(module, exports) { var InOut = function(v) { if ((v *= 2) < 1) { return -.5 * (Math.sqrt(1 - v * v) - 1) } else { return .5 * (Math.sqrt(1 - (v -= 2) * v) + 1) } }; module.exports = InOut }, function(module, exports) { var In = function(v) { return v * v * v }; module.exports = In }, function(module, exports) { var Out = function(v) { return --v * v * v + 1 }; module.exports = Out }, function(module, exports) { var InOut = function(v) { if ((v *= 2) < 1) { return .5 * v * v * v } else { return .5 * ((v -= 2) * v * v + 2) } }; module.exports = InOut }, function(module, exports) { var In = function(v, amplitude, period) { if (amplitude === undefined) { amplitude = .1 } if (period === undefined) { period = .1 } if (v === 0) { return 0 } else if (v === 1) { return 1 } else { var s = period / 4; if (amplitude < 1) { amplitude = 1 } else { s = period * Math.asin(1 / amplitude) / (2 * Math.PI) } return -(amplitude * Math.pow(2, 10 * (v -= 1)) * Math.sin((v - s) * (2 * Math.PI) / period)) } }; module.exports = In }, function(module, exports) { var Out = function(v, amplitude, period) { if (amplitude === undefined) { amplitude = .1 } if (period === undefined) { period = .1 } if (v === 0) { return 0 } else if (v === 1) { return 1 } else { var s = period / 4; if (amplitude < 1) { amplitude = 1 } else { s = period * Math.asin(1 / amplitude) / (2 * Math.PI) } return amplitude * Math.pow(2, -10 * v) * Math.sin((v - s) * (2 * Math.PI) / period) + 1 } }; module.exports = Out }, function(module, exports) { var InOut = function(v, amplitude, period) { if (amplitude === undefined) { amplitude = .1 } if (period === undefined) { period = .1 } if (v === 0) { return 0 } else if (v === 1) { return 1 } else { var s = period / 4; if (amplitude < 1) { amplitude = 1 } else { s = period * Math.asin(1 / amplitude) / (2 * Math.PI) } if ((v *= 2) < 1) { return -.5 * (amplitude * Math.pow(2, 10 * (v -= 1)) * Math.sin((v - s) * (2 * Math.PI) / period)) } else { return amplitude * Math.pow(2, -10 * (v -= 1)) * Math.sin((v - s) * (2 * Math.PI) / period) * .5 + 1 } } }; module.exports = InOut }, function(module, exports) { var In = function(v) { return Math.pow(2, 10 * (v - 1)) - .001 }; module.exports = In }, function(module, exports) { var Out = function(v) { return 1 - Math.pow(2, -10 * v) }; module.exports = Out }, function(module, exports) { var InOut = function(v) { if ((v *= 2) < 1) { return .5 * Math.pow(2, 10 * (v - 1)) } else { return .5 * (2 - Math.pow(2, -10 * (v - 1))) } }; module.exports = InOut }, function(module, exports) { var Linear = function(v) { return v }; module.exports = Linear }, function(module, exports) { var In = function(v) { return v * v }; module.exports = In }, function(module, exports) { var Out = function(v) { return v * (2 - v) }; module.exports = Out }, function(module, exports) { var InOut = function(v) { if ((v *= 2) < 1) { return .5 * v * v } else { return -.5 * (--v * (v - 2) - 1) } }; module.exports = InOut }, function(module, exports) { var In = function(v) { return v * v * v * v }; module.exports = In }, function(module, exports) { var Out = function(v) { return 1 - --v * v * v * v }; module.exports = Out }, function(module, exports) { var InOut = function(v) { if ((v *= 2) < 1) { return .5 * v * v * v * v } else { return -.5 * ((v -= 2) * v * v * v - 2) } }; module.exports = InOut }, function(module, exports) { var In = function(v) { return v * v * v * v * v }; module.exports = In }, function(module, exports) { var Out = function(v) { return --v * v * v * v * v + 1 }; module.exports = Out }, function(module, exports) { var InOut = function(v) { if ((v *= 2) < 1) { return .5 * v * v * v * v * v } else { return .5 * ((v -= 2) * v * v * v * v + 2) } }; module.exports = InOut }, function(module, exports) { var In = function(v) { if (v === 0) { return 0 } else if (v === 1) { return 1 } else { return 1 - Math.cos(v * Math.PI / 2) } }; module.exports = In }, function(module, exports) { var Out = function(v) { if (v === 0) { return 0 } else if (v === 1) { return 1 } else { return Math.sin(v * Math.PI / 2) } }; module.exports = Out }, function(module, exports) { var InOut = function(v) { if (v === 0) { return 0 } else if (v === 1) { return 1 } else { return .5 * (1 - Math.cos(Math.PI * v)) } }; module.exports = InOut }, function(module, exports) { var Stepped = function(v, steps) { if (steps === undefined) { steps = 1 } if (v <= 0) { return 0 } else if (v >= 1) { return 1 } else { return ((steps * v | 0) + 1) * (1 / steps) } }; module.exports = Stepped }, function(module, exports, __webpack_require__) { var Clamp = __webpack_require__(23); var Class = __webpack_require__(0); var Vector2 = __webpack_require__(3); var Shake = new Class({ initialize: function Shake(camera) { this.camera = camera; this.isRunning = false; this.duration = 0; this.intensity = new Vector2; this.progress = 0; this._elapsed = 0; this._offsetX = 0; this._offsetY = 0; this._onUpdate; this._onUpdateScope }, start: function(duration, intensity, force, callback, context) { if (duration === undefined) { duration = 100 } if (intensity === undefined) { intensity = .05 } if (force === undefined) { force = false } if (callback === undefined) { callback = null } if (context === undefined) { context = this.camera.scene } if (!force && this.isRunning) { return this.camera } this.isRunning = true; this.duration = duration; this.progress = 0; if (typeof intensity === "number") { this.intensity.set(intensity) } else { this.intensity.set(intensity.x, intensity.y) } this._elapsed = 0; this._offsetX = 0; this._offsetY = 0; this._onUpdate = callback; this._onUpdateScope = context; this.camera.emit("camerashakestart", this.camera, this, duration, intensity); return this.camera }, preRender: function() { if (this.isRunning) { this.camera.matrix.translate(this._offsetX, this._offsetY) } }, update: function(time, delta) { if (!this.isRunning) { return } this._elapsed += delta; this.progress = Clamp(this._elapsed / this.duration, 0, 1); if (this._onUpdate) { this._onUpdate.call(this._onUpdateScope, this.camera, this.progress) } if (this._elapsed < this.duration) { var intensity = this.intensity; var width = this.camera._cw; var height = this.camera._ch; var zoom = this.camera.zoom; this._offsetX = (Math.random() * intensity.x * width * 2 - intensity.x * width) * zoom; this._offsetY = (Math.random() * intensity.y * height * 2 - intensity.y * height) * zoom; if (this.camera.roundPixels) { this._offsetX |= 0; this._offsetY |= 0 } } else { this.effectComplete() } }, effectComplete: function() { this._offsetX = 0; this._offsetY = 0; this._onUpdate = null; this._onUpdateScope = null; this.isRunning = false; this.camera.emit("camerashakecomplete", this.camera, this) }, reset: function() { this.isRunning = false; this._offsetX = 0; this._offsetY = 0; this._onUpdate = null; this._onUpdateScope = null }, destroy: function() { this.reset(); this.camera = null; this.intensity = null } }); module.exports = Shake }, function(module, exports, __webpack_require__) { var Clamp = __webpack_require__(23); var Class = __webpack_require__(0); var EaseMap = __webpack_require__(163); var Zoom = new Class({ initialize: function Zoom(camera) { this.camera = camera; this.isRunning = false; this.duration = 0; this.source = 1; this.destination = 1; this.ease; this.progress = 0; this._elapsed = 0; this._onUpdate; this._onUpdateScope }, start: function(zoom, duration, ease, force, callback, context) { if (duration === undefined) { duration = 1e3 } if (ease === undefined) { ease = EaseMap.Linear } if (force === undefined) { force = false } if (callback === undefined) { callback = null } if (context === undefined) { context = this.camera.scene } var cam = this.camera; if (!force && this.isRunning) { return cam } this.isRunning = true; this.duration = duration; this.progress = 0; this.source = cam.zoom; this.destination = zoom; if (typeof ease === "string" && EaseMap.hasOwnProperty(ease)) { this.ease = EaseMap[ease] } else if (typeof ease === "function") { this.ease = ease } this._elapsed = 0; this._onUpdate = callback; this._onUpdateScope = context; this.camera.emit("camerazoomstart", this.camera, this, duration, zoom); return cam }, update: function(time, delta) { if (!this.isRunning) { return } this._elapsed += delta; this.progress = Clamp(this._elapsed / this.duration, 0, 1); if (this._elapsed < this.duration) { this.camera.zoom = this.source + (this.destination - this.source) * this.ease(this.progress); if (this._onUpdate) { this._onUpdate.call(this._onUpdateScope, this.camera, this.progress, this.camera.zoom) } } else { this.camera.zoom = this.destination; if (this._onUpdate) { this._onUpdate.call(this._onUpdateScope, this.camera, this.progress, this.destination) } this.effectComplete() } }, effectComplete: function() { this._onUpdate = null; this._onUpdateScope = null; this.isRunning = false; this.camera.emit("camerazoomcomplete", this.camera, this) }, reset: function() { this.isRunning = false; this._onUpdate = null; this._onUpdateScope = null }, destroy: function() { this.reset(); this.camera = null } }); module.exports = Zoom }, function(module, exports, __webpack_require__) { var Camera = __webpack_require__(265); var Class = __webpack_require__(0); var GetFastValue = __webpack_require__(1); var PluginCache = __webpack_require__(15); var RectangleContains = __webpack_require__(47); var CameraManager = new Class({ initialize: function CameraManager(scene) { this.scene = scene; this.systems = scene.sys; this.roundPixels = scene.sys.game.config.roundPixels; this.cameras = []; this.main; this.baseScale = 1; scene.sys.events.once("boot", this.boot, this); scene.sys.events.on("start", this.start, this) }, boot: function() { var sys = this.systems; if (sys.settings.cameras) { this.fromJSON(sys.settings.cameras) } else { this.add() } this.main = this.cameras[0]; this.systems.events.once("destroy", this.destroy, this) }, start: function() { if (!this.main) { var sys = this.systems; if (sys.settings.cameras) { this.fromJSON(sys.settings.cameras) } else { this.add() } this.main = this.cameras[0] } var eventEmitter = this.systems.events; eventEmitter.on("update", this.update, this); eventEmitter.once("shutdown", this.shutdown, this) }, add: function(x, y, width, height, makeMain, name) { if (x === undefined) { x = 0 } if (y === undefined) { y = 0 } if (width === undefined) { width = this.scene.sys.game.config.width } if (height === undefined) { height = this.scene.sys.game.config.height } if (makeMain === undefined) { makeMain = false } if (name === undefined) { name = "" } var camera = new Camera(x, y, width, height); camera.setName(name); camera.setScene(this.scene); camera.setRoundPixels(this.roundPixels); camera.id = this.getNextID(); this.cameras.push(camera); if (makeMain) { this.main = camera } return camera }, addExisting: function(camera, makeMain) { if (makeMain === undefined) { makeMain = false } var index = this.cameras.indexOf(camera); if (index === -1) { camera.id = this.getNextID(); camera.setRoundPixels(this.roundPixels); this.cameras.push(camera); if (makeMain) { this.main = camera } return camera } return null }, getNextID: function() { var cameras = this.cameras; var testID = 1; for (var t = 0; t < 32; t++) { var found = false; for (var i = 0; i < cameras.length; i++) { var camera = cameras[i]; if (camera && camera.id === testID) { found = true; continue } } if (found) { testID = testID << 1 } else { return testID } } return 0 }, getTotal: function(isVisible) { if (isVisible === undefined) { isVisible = false } var total = 0; var cameras = this.cameras; for (var i = 0; i < cameras.length; i++) { var camera = cameras[i]; if (!isVisible || isVisible && camera.visible) { total++ } } return total }, fromJSON: function(config) { if (!Array.isArray(config)) { config = [config] } var gameWidth = this.scene.sys.game.config.width; var gameHeight = this.scene.sys.game.config.height; for (var i = 0; i < config.length; i++) { var cameraConfig = config[i]; var x = GetFastValue(cameraConfig, "x", 0); var y = GetFastValue(cameraConfig, "y", 0); var width = GetFastValue(cameraConfig, "width", gameWidth); var height = GetFastValue(cameraConfig, "height", gameHeight); var camera = this.add(x, y, width, height); camera.name = GetFastValue(cameraConfig, "name", ""); camera.zoom = GetFastValue(cameraConfig, "zoom", 1); camera.rotation = GetFastValue(cameraConfig, "rotation", 0); camera.scrollX = GetFastValue(cameraConfig, "scrollX", 0); camera.scrollY = GetFastValue(cameraConfig, "scrollY", 0); camera.roundPixels = GetFastValue(cameraConfig, "roundPixels", false); camera.visible = GetFastValue(cameraConfig, "visible", true); var backgroundColor = GetFastValue(cameraConfig, "backgroundColor", false); if (backgroundColor) { camera.setBackgroundColor(backgroundColor) } var boundsConfig = GetFastValue(cameraConfig, "bounds", null); if (boundsConfig) { var bx = GetFastValue(boundsConfig, "x", 0); var by = GetFastValue(boundsConfig, "y", 0); var bwidth = GetFastValue(boundsConfig, "width", gameWidth); var bheight = GetFastValue(boundsConfig, "height", gameHeight); camera.setBounds(bx, by, bwidth, bheight) } } return this }, getCamera: function(name) { var cameras = this.cameras; for (var i = 0; i < cameras.length; i++) { if (cameras[i].name === name) { return cameras[i] } } return null }, getCamerasBelowPointer: function(pointer) { var cameras = this.cameras; var x = pointer.x; var y = pointer.y; var output = []; for (var i = 0; i < cameras.length; i++) { var camera = cameras[i]; if (camera.visible && camera.inputEnabled && RectangleContains(camera, x, y)) { output.unshift(camera) } } return output }, remove: function(camera, runDestroy) { if (runDestroy === undefined) { runDestroy = true } if (!Array.isArray(camera)) { camera = [camera] } var total = 0; var cameras = this.cameras; for (var i = 0; i < camera.length; i++) { var index = cameras.indexOf(camera[i]); if (index !== -1) { if (runDestroy) { cameras[index].destroy() } cameras.splice(index, 1); total++ } } if (!this.main && cameras[0]) { this.main = cameras[0] } return total }, render: function(renderer, children, interpolation) { var scene = this.scene; var cameras = this.cameras; var baseScale = this.baseScale; var resolution = renderer.config.resolution; for (var i = 0; i < this.cameras.length; i++) { var camera = cameras[i]; if (camera.visible && camera.alpha > 0) { camera.preRender(baseScale, resolution); renderer.render(scene, children, interpolation, camera) } } }, resetAll: function() { for (var i = 0; i < this.cameras.length; i++) { this.cameras[i].destroy() } this.cameras = []; this.main = this.add(); return this.main }, update: function(timestep, delta) { for (var i = 0; i < this.cameras.length; i++) { this.cameras[i].update(timestep, delta) } }, resize: function(width, height) { for (var i = 0; i < this.cameras.length; i++) { this.cameras[i].setSize(width, height) } }, shutdown: function() { this.main = undefined; for (var i = 0; i < this.cameras.length; i++) { this.cameras[i].destroy() } this.cameras = []; var eventEmitter = this.systems.events; eventEmitter.off("update", this.update, this); eventEmitter.off("shutdown", this.shutdown, this) }, destroy: function() { this.shutdown(); this.scene.sys.events.off("start", this.start, this); this.scene = null; this.systems = null } }); PluginCache.register("CameraManager", CameraManager, "cameras"); module.exports = CameraManager }, function(module, exports, __webpack_require__) { module.exports = { GenerateTexture: __webpack_require__(286), Palettes: __webpack_require__(587) } }, function(module, exports, __webpack_require__) { module.exports = { ARNE16: __webpack_require__(287), C64: __webpack_require__(588), CGA: __webpack_require__(589), JMP: __webpack_require__(590), MSX: __webpack_require__(591) } }, function(module, exports) { module.exports = { 0: "#000", 1: "#fff", 2: "#8b4131", 3: "#7bbdc5", 4: "#8b41ac", 5: "#6aac41", 6: "#3931a4", 7: "#d5de73", 8: "#945a20", 9: "#5a4100", A: "#bd736a", B: "#525252", C: "#838383", D: "#acee8b", E: "#7b73de", F: "#acacac" } }, function(module, exports) { module.exports = { 0: "#000", 1: "#2234d1", 2: "#0c7e45", 3: "#44aacc", 4: "#8a3622", 5: "#5c2e78", 6: "#aa5c3d", 7: "#b5b5b5", 8: "#5e606e", 9: "#4c81fb", A: "#6cd947", B: "#7be2f9", C: "#eb8a60", D: "#e23d69", E: "#ffd93f", F: "#fff" } }, function(module, exports) { module.exports = { 0: "#000", 1: "#191028", 2: "#46af45", 3: "#a1d685", 4: "#453e78", 5: "#7664fe", 6: "#833129", 7: "#9ec2e8", 8: "#dc534b", 9: "#e18d79", A: "#d6b97b", B: "#e9d8a1", C: "#216c4b", D: "#d365c8", E: "#afaab9", F: "#f5f4eb" } }, function(module, exports) { module.exports = { 0: "#000", 1: "#191028", 2: "#46af45", 3: "#a1d685", 4: "#453e78", 5: "#7664fe", 6: "#833129", 7: "#9ec2e8", 8: "#dc534b", 9: "#e18d79", A: "#d6b97b", B: "#e9d8a1", C: "#216c4b", D: "#d365c8", E: "#afaab9", F: "#fff" } }, function(module, exports, __webpack_require__) { module.exports = { Path: __webpack_require__(593), CubicBezier: __webpack_require__(288), Curve: __webpack_require__(79), Ellipse: __webpack_require__(290), Line: __webpack_require__(291), QuadraticBezier: __webpack_require__(292), Spline: __webpack_require__(294) } }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var CubicBezierCurve = __webpack_require__(288); var EllipseCurve = __webpack_require__(290); var GameObjectFactory = __webpack_require__(5); var LineCurve = __webpack_require__(291); var MovePathTo = __webpack_require__(594); var QuadraticBezierCurve = __webpack_require__(292); var Rectangle = __webpack_require__(9); var SplineCurve = __webpack_require__(294); var Vector2 = __webpack_require__(3); var Path = new Class({ initialize: function Path(x, y) { if (x === undefined) { x = 0 } if (y === undefined) { y = 0 } this.name = ""; this.curves = []; this.cacheLengths = []; this.autoClose = false; this.startPoint = new Vector2; this._tmpVec2A = new Vector2; this._tmpVec2B = new Vector2; if (typeof x === "object") { this.fromJSON(x) } else { this.startPoint.set(x, y) } }, add: function(curve) { this.curves.push(curve); return this }, circleTo: function(radius, clockwise, rotation) { if (clockwise === undefined) { clockwise = false } return this.ellipseTo(radius, radius, 0, 360, clockwise, rotation) }, closePath: function() { var startPoint = this.curves[0].getPoint(0); var endPoint = this.curves[this.curves.length - 1].getPoint(1); if (!startPoint.equals(endPoint)) { this.curves.push(new LineCurve(endPoint, startPoint)) } return this }, cubicBezierTo: function(x, y, control1X, control1Y, control2X, control2Y) { var p0 = this.getEndPoint(); var p1; var p2; var p3; if (x instanceof Vector2) { p1 = x; p2 = y; p3 = control1X } else { p1 = new Vector2(control1X, control1Y); p2 = new Vector2(control2X, control2Y); p3 = new Vector2(x, y) } return this.add(new CubicBezierCurve(p0, p1, p2, p3)) }, quadraticBezierTo: function(x, y, controlX, controlY) { var p0 = this.getEndPoint(); var p1; var p2; if (x instanceof Vector2) { p1 = x; p2 = y } else { p1 = new Vector2(controlX, controlY); p2 = new Vector2(x, y) } return this.add(new QuadraticBezierCurve(p0, p1, p2)) }, draw: function(graphics, pointsTotal) { for (var i = 0; i < this.curves.length; i++) { var curve = this.curves[i]; if (!curve.active) { continue } curve.draw(graphics, pointsTotal) } return graphics }, ellipseTo: function(xRadius, yRadius, startAngle, endAngle, clockwise, rotation) { var ellipse = new EllipseCurve(0, 0, xRadius, yRadius, startAngle, endAngle, clockwise, rotation); var end = this.getEndPoint(this._tmpVec2A); var start = ellipse.getStartPoint(this._tmpVec2B); end.subtract(start); ellipse.x = end.x; ellipse.y = end.y; return this.add(ellipse) }, fromJSON: function(data) { this.curves = []; this.cacheLengths = []; this.startPoint.set(data.x, data.y); this.autoClose = data.autoClose; for (var i = 0; i < data.curves.length; i++) { var curve = data.curves[i]; switch (curve.type) { case "LineCurve": this.add(LineCurve.fromJSON(curve)); break; case "EllipseCurve": this.add(EllipseCurve.fromJSON(curve)); break; case "SplineCurve": this.add(SplineCurve.fromJSON(curve)); break; case "CubicBezierCurve": this.add(CubicBezierCurve.fromJSON(curve)); break; case "QuadraticBezierCurve": this.add(QuadraticBezierCurve.fromJSON(curve)); break } } return this }, getBounds: function(out, accuracy) { if (out === undefined) { out = new Rectangle } if (accuracy === undefined) { accuracy = 16 } out.x = Number.MAX_VALUE; out.y = Number.MAX_VALUE; var bounds = new Rectangle; var maxRight = Number.MIN_SAFE_INTEGER; var maxBottom = Number.MIN_SAFE_INTEGER; for (var i = 0; i < this.curves.length; i++) { var curve = this.curves[i]; if (!curve.active) { continue } curve.getBounds(bounds, accuracy); out.x = Math.min(out.x, bounds.x); out.y = Math.min(out.y, bounds.y); maxRight = Math.max(maxRight, bounds.right); maxBottom = Math.max(maxBottom, bounds.bottom) } out.right = maxRight; out.bottom = maxBottom; return out }, getCurveLengths: function() { if (this.cacheLengths.length === this.curves.length) { return this.cacheLengths } var lengths = []; var sums = 0; for (var i = 0; i < this.curves.length; i++) { sums += this.curves[i].getLength(); lengths.push(sums) } this.cacheLengths = lengths; return lengths }, getEndPoint: function(out) { if (out === undefined) { out = new Vector2 } if (this.curves.length > 0) { this.curves[this.curves.length - 1].getPoint(1, out) } else { out.copy(this.startPoint) } return out }, getLength: function() { var lens = this.getCurveLengths(); return lens[lens.length - 1] }, getPoint: function(t, out) { if (out === undefined) { out = new Vector2 } var d = t * this.getLength(); var curveLengths = this.getCurveLengths(); var i = 0; while (i < curveLengths.length) { if (curveLengths[i] >= d) { var diff = curveLengths[i] - d; var curve = this.curves[i]; var segmentLength = curve.getLength(); var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength; return curve.getPointAt(u, out) } i++ } return null }, getPoints: function(divisions) { if (divisions === undefined) { divisions = 12 } var points = []; var last; for (var i = 0; i < this.curves.length; i++) { var curve = this.curves[i]; if (!curve.active) { continue } var resolution = curve.getResolution(divisions); var pts = curve.getPoints(resolution); for (var j = 0; j < pts.length; j++) { var point = pts[j]; if (last && last.equals(point)) { continue } points.push(point); last = point } } if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) { points.push(points[0]) } return points }, getRandomPoint: function(out) { if (out === undefined) { out = new Vector2 } return this.getPoint(Math.random(), out) }, getSpacedPoints: function(divisions) { if (divisions === undefined) { divisions = 40 } var points = []; for (var i = 0; i <= divisions; i++) { points.push(this.getPoint(i / divisions)) } if (this.autoClose) { points.push(points[0]) } return points }, getStartPoint: function(out) { if (out === undefined) { out = new Vector2 } return out.copy(this.startPoint) }, lineTo: function(x, y) { if (x instanceof Vector2) { this._tmpVec2B.copy(x) } else { this._tmpVec2B.set(x, y) } var end = this.getEndPoint(this._tmpVec2A); return this.add(new LineCurve([end.x, end.y, this._tmpVec2B.x, this._tmpVec2B.y])) }, splineTo: function(points) { points.unshift(this.getEndPoint()); return this.add(new SplineCurve(points)) }, moveTo: function(x, y) { return this.add(new MovePathTo(x, y)) }, toJSON: function() { var out = []; for (var i = 0; i < this.curves.length; i++) { out.push(this.curves[i].toJSON()) } return { type: "Path", x: this.startPoint.x, y: this.startPoint.y, autoClose: this.autoClose, curves: out } }, updateArcLengths: function() { this.cacheLengths = []; this.getCurveLengths() }, destroy: function() { this.curves.length = 0; this.cacheLengths.length = 0; this.startPoint = undefined } }); GameObjectFactory.register("path", function(x, y) { return new Path(x, y) }); module.exports = Path }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Vector2 = __webpack_require__(3); var MoveTo = new Class({ initialize: function MoveTo(x, y) { this.active = false; this.p0 = new Vector2(x, y) }, getPoint: function(t, out) { if (out === undefined) { out = new Vector2 } return out.copy(this.p0) }, getPointAt: function(u, out) { return this.getPoint(u, out) }, getResolution: function() { return 1 }, getLength: function() { return 0 }, toJSON: function() { return { type: "MoveTo", points: [this.p0.x, this.p0.y] } } }); module.exports = MoveTo }, function(module, exports, __webpack_require__) { module.exports = { DataManager: __webpack_require__(91), DataManagerPlugin: __webpack_require__(596) } }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var DataManager = __webpack_require__(91); var PluginCache = __webpack_require__(15); var DataManagerPlugin = new Class({ Extends: DataManager, initialize: function DataManagerPlugin(scene) { DataManager.call(this, scene, scene.sys.events); this.scene = scene; this.systems = scene.sys; scene.sys.events.once("boot", this.boot, this); scene.sys.events.on("start", this.start, this) }, boot: function() { this.events = this.systems.events; this.events.once("destroy", this.destroy, this) }, start: function() { this.events.once("shutdown", this.shutdown, this) }, shutdown: function() { this.systems.events.off("shutdown", this.shutdown, this) }, destroy: function() { DataManager.prototype.destroy.call(this); this.events.off("start", this.start, this); this.scene = null; this.systems = null } }); PluginCache.register("DataManagerPlugin", DataManagerPlugin, "data"); module.exports = DataManagerPlugin }, function(module, exports, __webpack_require__) { module.exports = { Align: __webpack_require__(598), Bounds: __webpack_require__(613), Canvas: __webpack_require__(616), Color: __webpack_require__(296), Masks: __webpack_require__(625) } }, function(module, exports, __webpack_require__) { var CONST = __webpack_require__(143); var Extend = __webpack_require__(19); var Align = { In: __webpack_require__(599), To: __webpack_require__(600) }; Align = Extend(false, Align, CONST); module.exports = Align }, function(module, exports, __webpack_require__) { module.exports = { BottomCenter: __webpack_require__(227), BottomLeft: __webpack_require__(228), BottomRight: __webpack_require__(229), Center: __webpack_require__(230), LeftCenter: __webpack_require__(232), QuickSet: __webpack_require__(226), RightCenter: __webpack_require__(233), TopCenter: __webpack_require__(234), TopLeft: __webpack_require__(235), TopRight: __webpack_require__(236) } }, function(module, exports, __webpack_require__) { module.exports = { BottomCenter: __webpack_require__(601), BottomLeft: __webpack_require__(602), BottomRight: __webpack_require__(603), LeftBottom: __webpack_require__(604), LeftCenter: __webpack_require__(605), LeftTop: __webpack_require__(606), RightBottom: __webpack_require__(607), RightCenter: __webpack_require__(608), RightTop: __webpack_require__(609), TopCenter: __webpack_require__(610), TopLeft: __webpack_require__(611), TopRight: __webpack_require__(612) } }, function(module, exports, __webpack_require__) { var GetBottom = __webpack_require__(38); var GetCenterX = __webpack_require__(74); var SetCenterX = __webpack_require__(75); var SetTop = __webpack_require__(45); var BottomCenter = function(gameObject, alignTo, offsetX, offsetY) { if (offsetX === undefined) { offsetX = 0 } if (offsetY === undefined) { offsetY = 0 } SetCenterX(gameObject, GetCenterX(alignTo) + offsetX); SetTop(gameObject, GetBottom(alignTo) + offsetY); return gameObject }; module.exports = BottomCenter }, function(module, exports, __webpack_require__) { var GetBottom = __webpack_require__(38); var GetLeft = __webpack_require__(40); var SetLeft = __webpack_require__(41); var SetTop = __webpack_require__(45); var BottomLeft = function(gameObject, alignTo, offsetX, offsetY) { if (offsetX === undefined) { offsetX = 0 } if (offsetY === undefined) { offsetY = 0 } SetLeft(gameObject, GetLeft(alignTo) - offsetX); SetTop(gameObject, GetBottom(alignTo) + offsetY); return gameObject }; module.exports = BottomLeft }, function(module, exports, __webpack_require__) { var GetBottom = __webpack_require__(38); var GetRight = __webpack_require__(42); var SetRight = __webpack_require__(43); var SetTop = __webpack_require__(45); var BottomRight = function(gameObject, alignTo, offsetX, offsetY) { if (offsetX === undefined) { offsetX = 0 } if (offsetY === undefined) { offsetY = 0 } SetRight(gameObject, GetRight(alignTo) + offsetX); SetTop(gameObject, GetBottom(alignTo) + offsetY); return gameObject }; module.exports = BottomRight }, function(module, exports, __webpack_require__) { var GetBottom = __webpack_require__(38); var GetLeft = __webpack_require__(40); var SetBottom = __webpack_require__(39); var SetRight = __webpack_require__(43); var LeftBottom = function(gameObject, alignTo, offsetX, offsetY) { if (offsetX === undefined) { offsetX = 0 } if (offsetY === undefined) { offsetY = 0 } SetRight(gameObject, GetLeft(alignTo) - offsetX); SetBottom(gameObject, GetBottom(alignTo) + offsetY); return gameObject }; module.exports = LeftBottom }, function(module, exports, __webpack_require__) { var GetCenterY = __webpack_require__(77); var GetLeft = __webpack_require__(40); var SetCenterY = __webpack_require__(76); var SetRight = __webpack_require__(43); var LeftCenter = function(gameObject, alignTo, offsetX, offsetY) { if (offsetX === undefined) { offsetX = 0 } if (offsetY === undefined) { offsetY = 0 } SetRight(gameObject, GetLeft(alignTo) - offsetX); SetCenterY(gameObject, GetCenterY(alignTo) + offsetY); return gameObject }; module.exports = LeftCenter }, function(module, exports, __webpack_require__) { var GetLeft = __webpack_require__(40); var GetTop = __webpack_require__(44); var SetRight = __webpack_require__(43); var SetTop = __webpack_require__(45); var LeftTop = function(gameObject, alignTo, offsetX, offsetY) { if (offsetX === undefined) { offsetX = 0 } if (offsetY === undefined) { offsetY = 0 } SetRight(gameObject, GetLeft(alignTo) - offsetX); SetTop(gameObject, GetTop(alignTo) - offsetY); return gameObject }; module.exports = LeftTop }, function(module, exports, __webpack_require__) { var GetBottom = __webpack_require__(38); var GetRight = __webpack_require__(42); var SetBottom = __webpack_require__(39); var SetLeft = __webpack_require__(41); var RightBottom = function(gameObject, alignTo, offsetX, offsetY) { if (offsetX === undefined) { offsetX = 0 } if (offsetY === undefined) { offsetY = 0 } SetLeft(gameObject, GetRight(alignTo) + offsetX); SetBottom(gameObject, GetBottom(alignTo) + offsetY); return gameObject }; module.exports = RightBottom }, function(module, exports, __webpack_require__) { var GetCenterY = __webpack_require__(77); var GetRight = __webpack_require__(42); var SetCenterY = __webpack_require__(76); var SetLeft = __webpack_require__(41); var RightCenter = function(gameObject, alignTo, offsetX, offsetY) { if (offsetX === undefined) { offsetX = 0 } if (offsetY === undefined) { offsetY = 0 } SetLeft(gameObject, GetRight(alignTo) + offsetX); SetCenterY(gameObject, GetCenterY(alignTo) + offsetY); return gameObject }; module.exports = RightCenter }, function(module, exports, __webpack_require__) { var GetRight = __webpack_require__(42); var GetTop = __webpack_require__(44); var SetLeft = __webpack_require__(41); var SetTop = __webpack_require__(45); var RightTop = function(gameObject, alignTo, offsetX, offsetY) { if (offsetX === undefined) { offsetX = 0 } if (offsetY === undefined) { offsetY = 0 } SetLeft(gameObject, GetRight(alignTo) + offsetX); SetTop(gameObject, GetTop(alignTo) - offsetY); return gameObject }; module.exports = RightTop }, function(module, exports, __webpack_require__) { var GetCenterX = __webpack_require__(74); var GetTop = __webpack_require__(44); var SetBottom = __webpack_require__(39); var SetCenterX = __webpack_require__(75); var TopCenter = function(gameObject, alignTo, offsetX, offsetY) { if (offsetX === undefined) { offsetX = 0 } if (offsetY === undefined) { offsetY = 0 } SetCenterX(gameObject, GetCenterX(alignTo) + offsetX); SetBottom(gameObject, GetTop(alignTo) - offsetY); return gameObject }; module.exports = TopCenter }, function(module, exports, __webpack_require__) { var GetLeft = __webpack_require__(40); var GetTop = __webpack_require__(44); var SetBottom = __webpack_require__(39); var SetLeft = __webpack_require__(41); var TopLeft = function(gameObject, alignTo, offsetX, offsetY) { if (offsetX === undefined) { offsetX = 0 } if (offsetY === undefined) { offsetY = 0 } SetLeft(gameObject, GetLeft(alignTo) - offsetX); SetBottom(gameObject, GetTop(alignTo) - offsetY); return gameObject }; module.exports = TopLeft }, function(module, exports, __webpack_require__) { var GetRight = __webpack_require__(42); var GetTop = __webpack_require__(44); var SetBottom = __webpack_require__(39); var SetRight = __webpack_require__(43); var TopRight = function(gameObject, alignTo, offsetX, offsetY) { if (offsetX === undefined) { offsetX = 0 } if (offsetY === undefined) { offsetY = 0 } SetRight(gameObject, GetRight(alignTo) + offsetX); SetBottom(gameObject, GetTop(alignTo) - offsetY); return gameObject }; module.exports = TopRight }, function(module, exports, __webpack_require__) { module.exports = { CenterOn: __webpack_require__(231), GetBottom: __webpack_require__(38), GetCenterX: __webpack_require__(74), GetCenterY: __webpack_require__(77), GetLeft: __webpack_require__(40), GetOffsetX: __webpack_require__(614), GetOffsetY: __webpack_require__(615), GetRight: __webpack_require__(42), GetTop: __webpack_require__(44), SetBottom: __webpack_require__(39), SetCenterX: __webpack_require__(75), SetCenterY: __webpack_require__(76), SetLeft: __webpack_require__(41), SetRight: __webpack_require__(43), SetTop: __webpack_require__(45) } }, function(module, exports) { var GetOffsetX = function(gameObject) { return gameObject.width * gameObject.originX }; module.exports = GetOffsetX }, function(module, exports) { var GetOffsetY = function(gameObject) { return gameObject.height * gameObject.originY }; module.exports = GetOffsetY }, function(module, exports, __webpack_require__) { module.exports = { CanvasInterpolation: __webpack_require__(295), CanvasPool: __webpack_require__(28), Smoothing: __webpack_require__(112), TouchAction: __webpack_require__(617), UserSelect: __webpack_require__(618) } }, function(module, exports) { var TouchAction = function(canvas, value) { if (value === undefined) { value = "none" } canvas.style["msTouchAction"] = value; canvas.style["ms-touch-action"] = value; canvas.style["touch-action"] = value; return canvas }; module.exports = TouchAction }, function(module, exports) { var UserSelect = function(canvas, value) { if (value === undefined) { value = "none" } var vendors = ["-webkit-", "-khtml-", "-moz-", "-ms-", ""]; vendors.forEach(function(vendor) { canvas.style[vendor + "user-select"] = value }); canvas.style["-webkit-touch-callout"] = value; canvas.style["-webkit-tap-highlight-color"] = "rgba(0, 0, 0, 0)"; return canvas }; module.exports = UserSelect }, function(module, exports) { var ColorToRGBA = function(color) { var output = { r: color >> 16 & 255, g: color >> 8 & 255, b: color & 255, a: 255 }; if (color > 16777215) { output.a = color >>> 24 } return output }; module.exports = ColorToRGBA }, function(module, exports, __webpack_require__) { var Color = __webpack_require__(49); var HueToComponent = __webpack_require__(298); var HSLToColor = function(h, s, l) { var r = l; var g = l; var b = l; if (s !== 0) { var q = l < .5 ? l * (1 + s) : l + s - l * s; var p = 2 * l - q; r = HueToComponent(p, q, h + 1 / 3); g = HueToComponent(p, q, h); b = HueToComponent(p, q, h - 1 / 3) } var color = new Color; return color.setGLTo(r, g, b, 1) }; module.exports = HSLToColor }, function(module, exports, __webpack_require__) { var HSVToRGB = __webpack_require__(161); var HSVColorWheel = function(s, v) { if (s === undefined) { s = 1 } if (v === undefined) { v = 1 } var colors = []; for (var c = 0; c <= 359; c++) { colors.push(HSVToRGB(c / 359, s, v)) } return colors }; module.exports = HSVColorWheel }, function(module, exports, __webpack_require__) { var Linear = __webpack_require__(113); var RGBWithRGB = function(r1, g1, b1, r2, g2, b2, length, index) { if (length === undefined) { length = 100 } if (index === undefined) { index = 0 } var t = index / length; return { r: Linear(r1, r2, t), g: Linear(g1, g2, t), b: Linear(b1, b2, t) } }; var ColorWithColor = function(color1, color2, length, index) { if (length === undefined) { length = 100 } if (index === undefined) { index = 0 } return RGBWithRGB(color1.r, color1.g, color1.b, color2.r, color2.g, color2.b, length, index) }; var ColorWithRGB = function(color, r, g, b, length, index) { if (length === undefined) { length = 100 } if (index === undefined) { index = 0 } return RGBWithRGB(color.r, color.g, color.b, r, g, b, length, index) }; module.exports = { RGBWithRGB: RGBWithRGB, ColorWithRGB: ColorWithRGB, ColorWithColor: ColorWithColor } }, function(module, exports, __webpack_require__) { var Between = __webpack_require__(167); var Color = __webpack_require__(49); var RandomRGB = function(min, max) { if (min === undefined) { min = 0 } if (max === undefined) { max = 255 } return new Color(Between(min, max), Between(min, max), Between(min, max)) }; module.exports = RandomRGB }, function(module, exports, __webpack_require__) { var ComponentToHex = __webpack_require__(297); var RGBToString = function(r, g, b, a, prefix) { if (a === undefined) { a = 255 } if (prefix === undefined) { prefix = "#" } if (prefix === "#") { return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1) } else { return "0x" + ComponentToHex(a) + ComponentToHex(r) + ComponentToHex(g) + ComponentToHex(b) } }; module.exports = RGBToString }, function(module, exports, __webpack_require__) { module.exports = { BitmapMask: __webpack_require__(249), GeometryMask: __webpack_require__(250) } }, function(module, exports, __webpack_require__) { var Dom = { AddToDOM: __webpack_require__(114), DOMContentLoaded: __webpack_require__(299), ParseXML: __webpack_require__(300), RemoveFromDOM: __webpack_require__(168), RequestAnimationFrame: __webpack_require__(301) }; module.exports = Dom }, function(module, exports) { var process = module.exports = {}; var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error("setTimeout has not been defined") } function defaultClearTimeout() { throw new Error("clearTimeout has not been defined") }(function() { try { if (typeof setTimeout === "function") { cachedSetTimeout = setTimeout } else { cachedSetTimeout = defaultSetTimout } } catch (e) { cachedSetTimeout = defaultSetTimout } try { if (typeof clearTimeout === "function") { cachedClearTimeout = clearTimeout } else { cachedClearTimeout = defaultClearTimeout } } catch (e) { cachedClearTimeout = defaultClearTimeout } })(); function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { return setTimeout(fun, 0) } if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0) } try { return cachedSetTimeout(fun, 0) } catch (e) { try { return cachedSetTimeout.call(null, fun, 0) } catch (e) { return cachedSetTimeout.call(this, fun, 0) } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { return clearTimeout(marker) } if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker) } try { return cachedClearTimeout(marker) } catch (e) { try { return cachedClearTimeout.call(null, marker) } catch (e) { return cachedClearTimeout.call(this, marker) } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue) } else { queueIndex = -1 } if (queue.length) { drainQueue() } } function drainQueue() { if (draining) { return } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while (len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run() } } queueIndex = -1; len = queue.length } currentQueue = null; draining = false; runClearTimeout(timeout) } process.nextTick = function(fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i] } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue) } }; function Item(fun, array) { this.fun = fun; this.array = array } Item.prototype.run = function() { this.fun.apply(null, this.array) }; process.title = "browser"; process.browser = true; process.env = {}; process.argv = []; process.version = ""; process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.prependListener = noop; process.prependOnceListener = noop; process.listeners = function(name) { return [] }; process.binding = function(name) { throw new Error("process.binding is not supported") }; process.cwd = function() { return "/" }; process.chdir = function(dir) { throw new Error("process.chdir is not supported") }; process.umask = function() { return 0 } }, function(module, exports, __webpack_require__) { module.exports = { EventEmitter: __webpack_require__(629) } }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var EE = __webpack_require__(11); var PluginCache = __webpack_require__(15); var EventEmitter = new Class({ Extends: EE, initialize: function EventEmitter() { EE.call(this) }, shutdown: function() { this.removeAllListeners() }, destroy: function() { this.removeAllListeners() } }); PluginCache.register("EventEmitter", EventEmitter, "events"); module.exports = EventEmitter }, function(module, exports, __webpack_require__) { var AddToDOM = __webpack_require__(114); var AnimationManager = __webpack_require__(262); var CacheManager = __webpack_require__(264); var CanvasPool = __webpack_require__(28); var Class = __webpack_require__(0); var Config = __webpack_require__(631); var CreateRenderer = __webpack_require__(636); var DataManager = __webpack_require__(91); var DebugHeader = __webpack_require__(643); var Device = __webpack_require__(302); var DOMContentLoaded = __webpack_require__(299); var EventEmitter = __webpack_require__(11); var InputManager = __webpack_require__(311); var PluginCache = __webpack_require__(15); var PluginManager = __webpack_require__(318); var SceneManager = __webpack_require__(320); var SoundManagerCreator = __webpack_require__(324); var TextureManager = __webpack_require__(331); var TimeStep = __webpack_require__(656); var VisibilityHandler = __webpack_require__(657); if (typeof EXPERIMENTAL) { var CreateDOMContainer = __webpack_require__(658) } if (typeof PLUGIN_FBINSTANT) { var FacebookInstantGamesPlugin = __webpack_require__(334) } var Game = new Class({ initialize: function Game(config) { this.config = new Config(config); this.renderer = null; if (typeof EXPERIMENTAL) { this.domContainer = null } this.canvas = null; this.context = null; this.isBooted = false; this.isRunning = false; this.events = new EventEmitter; this.anims = new AnimationManager(this); this.textures = new TextureManager(this); this.cache = new CacheManager(this); this.registry = new DataManager(this); this.input = new InputManager(this, this.config); this.scene = new SceneManager(this, this.config.sceneConfig); this.device = Device; this.sound = SoundManagerCreator.create(this); this.loop = new TimeStep(this, this.config.fps); this.plugins = new PluginManager(this, this.config); if (typeof PLUGIN_FBINSTANT) { this.facebook = new FacebookInstantGamesPlugin(this) } this.pendingDestroy = false; this.removeCanvas = false; this.noReturn = false; this.hasFocus = false; this.isOver = true; DOMContentLoaded(this.boot.bind(this)) }, boot: function() { if (!PluginCache.hasCore("EventEmitter")) { console.warn("Aborting. Core Plugins missing."); return } this.isBooted = true; this.config.preBoot(this); CreateRenderer(this); if (typeof EXPERIMENTAL) { CreateDOMContainer(this) } DebugHeader(this); AddToDOM(this.canvas, this.config.parent); this.events.emit("boot"); this.events.once("texturesready", this.texturesReady, this) }, texturesReady: function() { this.events.emit("ready"); this.start() }, start: function() { this.isRunning = true; this.config.postBoot(this); if (this.renderer) { this.loop.start(this.step.bind(this)) } else { this.loop.start(this.headlessStep.bind(this)) } VisibilityHandler(this); var eventEmitter = this.events; eventEmitter.on("hidden", this.onHidden, this); eventEmitter.on("visible", this.onVisible, this); eventEmitter.on("blur", this.onBlur, this); eventEmitter.on("focus", this.onFocus, this) }, step: function(time, delta) { if (this.pendingDestroy) { return this.runDestroy() } var eventEmitter = this.events; eventEmitter.emit("prestep", time, delta); eventEmitter.emit("step", time, delta); this.scene.update(time, delta); eventEmitter.emit("poststep", time, delta); var renderer = this.renderer; renderer.preRender(); eventEmitter.emit("prerender", renderer, time, delta); this.scene.render(renderer); renderer.postRender(); eventEmitter.emit("postrender", renderer, time, delta) }, headlessStep: function(time, delta) { var eventEmitter = this.events; eventEmitter.emit("prestep", time, delta); eventEmitter.emit("step", time, delta); this.scene.update(time, delta); eventEmitter.emit("poststep", time, delta); eventEmitter.emit("prerender"); eventEmitter.emit("postrender") }, onHidden: function() { this.loop.pause(); this.events.emit("pause") }, onVisible: function() { this.loop.resume(); this.events.emit("resume") }, onBlur: function() { this.hasFocus = false; this.loop.blur() }, onFocus: function() { this.hasFocus = true; this.loop.focus() }, resize: function(width, height) { this.config.width = width; this.config.height = height; if (typeof EXPERIMENTAL) { if (this.domContainer) { this.domContainer.style.width = width + "px"; this.domContainer.style.height = height + "px" } } this.renderer.resize(width, height); this.input.resize(); this.scene.resize(width, height); this.events.emit("resize", width, height) }, destroy: function(removeCanvas, noReturn) { if (noReturn === undefined) { noReturn = false } this.pendingDestroy = true; this.removeCanvas = removeCanvas; this.noReturn = noReturn }, runDestroy: function() { this.events.emit("destroy"); this.events.removeAllListeners(); this.scene.destroy(); if (this.renderer) { this.renderer.destroy() } if (this.removeCanvas && this.canvas) { CanvasPool.remove(this.canvas); if (this.canvas.parentNode) { this.canvas.parentNode.removeChild(this.canvas) } } if (typeof EXPERIMENTAL) { if (this.domContainer) { this.domContainer.parentNode.removeChild(this.domContainer) } } this.loop.destroy(); this.pendingDestroy = false } }); module.exports = Game }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var CONST = __webpack_require__(26); var Device = __webpack_require__(302); var GetFastValue = __webpack_require__(1); var GetValue = __webpack_require__(4); var IsPlainObject = __webpack_require__(7); var MATH = __webpack_require__(18); var NOOP = __webpack_require__(2); var DefaultPlugins = __webpack_require__(170); var ValueToColor = __webpack_require__(159); var Config = new Class({ initialize: function Config(config) { if (config === undefined) { config = {} } var defaultBannerColor = ["#ff0000", "#ffff00", "#00ff00", "#00ffff", "#000000"]; var defaultBannerTextColor = "#ffffff"; this.width = GetValue(config, "width", 1024); this.height = GetValue(config, "height", 768); this.zoom = GetValue(config, "zoom", 1); this.resolution = GetValue(config, "resolution", 1); this.parent = GetValue(config, "parent", null); this.scaleMode = GetValue(config, "scaleMode", 0); this.expandParent = GetValue(config, "expandParent", false); this.minWidth = GetValue(config, "minWidth", 0); this.maxWidth = GetValue(config, "maxWidth", 0); this.minHeight = GetValue(config, "minHeight", 0); this.maxHeight = GetValue(config, "maxHeight", 0); var scaleConfig = GetValue(config, "scale", null); if (scaleConfig) { this.width = GetValue(scaleConfig, "width", this.width); this.height = GetValue(scaleConfig, "height", this.height); this.zoom = GetValue(scaleConfig, "zoom", this.zoom); this.resolution = GetValue(scaleConfig, "resolution", this.resolution); this.parent = GetValue(scaleConfig, "parent", this.parent); this.scaleMode = GetValue(scaleConfig, "mode", this.scaleMode); this.expandParent = GetValue(scaleConfig, "mode", this.expandParent); this.minWidth = GetValue(scaleConfig, "min.width", this.minWidth); this.maxWidth = GetValue(scaleConfig, "max.width", this.maxWidth); this.minHeight = GetValue(scaleConfig, "min.height", this.minHeight); this.maxHeight = GetValue(scaleConfig, "max.height", this.maxHeight) } this.renderType = GetValue(config, "type", CONST.AUTO); this.canvas = GetValue(config, "canvas", null); this.context = GetValue(config, "context", null); this.canvasStyle = GetValue(config, "canvasStyle", null); this.sceneConfig = GetValue(config, "scene", null); this.seed = GetValue(config, "seed", [(Date.now() * Math.random()).toString()]); MATH.RND.init(this.seed); this.gameTitle = GetValue(config, "title", ""); this.gameURL = GetValue(config, "url", "https://phaser.io"); this.gameVersion = GetValue(config, "version", ""); this.autoFocus = GetValue(config, "autoFocus", true); this.domCreateContainer = GetValue(config, "dom.createContainer", false); this.domBehindCanvas = GetValue(config, "dom.behindCanvas", false); this.inputKeyboard = GetValue(config, "input.keyboard", true); this.inputKeyboardEventTarget = GetValue(config, "input.keyboard.target", window); this.inputMouse = GetValue(config, "input.mouse", true); this.inputMouseEventTarget = GetValue(config, "input.mouse.target", null); this.inputMouseCapture = GetValue(config, "input.mouse.capture", true); this.inputTouch = GetValue(config, "input.touch", Device.input.touch); this.inputTouchEventTarget = GetValue(config, "input.touch.target", null); this.inputTouchCapture = GetValue(config, "input.touch.capture", true); this.inputActivePointers = GetValue(config, "input.activePointers", 1); this.inputGamepad = GetValue(config, "input.gamepad", false); this.inputGamepadEventTarget = GetValue(config, "input.gamepad.target", window); this.disableContextMenu = GetValue(config, "disableContextMenu", false); this.audio = GetValue(config, "audio"); this.hideBanner = GetValue(config, "banner", null) === false; this.hidePhaser = GetValue(config, "banner.hidePhaser", false); this.bannerTextColor = GetValue(config, "banner.text", defaultBannerTextColor); this.bannerBackgroundColor = GetValue(config, "banner.background", defaultBannerColor); if (this.gameTitle === "" && this.hidePhaser) { this.hideBanner = true } this.fps = GetValue(config, "fps", null); var renderConfig = GetValue(config, "render", config); this.autoResize = GetValue(renderConfig, "autoResize", true); this.antialias = GetValue(renderConfig, "antialias", true); this.roundPixels = GetValue(renderConfig, "roundPixels", false); this.pixelArt = GetValue(renderConfig, "pixelArt", false); if (this.pixelArt) { this.antialias = false; this.roundPixels = true } this.transparent = GetValue(renderConfig, "transparent", false); this.clearBeforeRender = GetValue(renderConfig, "clearBeforeRender", true); this.premultipliedAlpha = GetValue(renderConfig, "premultipliedAlpha", true); this.preserveDrawingBuffer = GetValue(renderConfig, "preserveDrawingBuffer", false); this.failIfMajorPerformanceCaveat = GetValue(renderConfig, "failIfMajorPerformanceCaveat", false); this.powerPreference = GetValue(renderConfig, "powerPreference", "default"); this.batchSize = GetValue(renderConfig, "batchSize", 2e3); this.maxLights = GetValue(renderConfig, "maxLights", 10); var bgc = GetValue(config, "backgroundColor", 0); this.backgroundColor = ValueToColor(bgc); if (bgc === 0 && this.transparent) { this.backgroundColor.alpha = 0 } this.preBoot = GetValue(config, "callbacks.preBoot", NOOP); this.postBoot = GetValue(config, "callbacks.postBoot", NOOP); this.physics = GetValue(config, "physics", {}); this.defaultPhysicsSystem = GetValue(this.physics, "default", false); this.loaderBaseURL = GetValue(config, "loader.baseURL", ""); this.loaderPath = GetValue(config, "loader.path", ""); this.loaderMaxParallelDownloads = GetValue(config, "loader.maxParallelDownloads", 32); this.loaderCrossOrigin = GetValue(config, "loader.crossOrigin", undefined); this.loaderResponseType = GetValue(config, "loader.responseType", ""); this.loaderAsync = GetValue(config, "loader.async", true); this.loaderUser = GetValue(config, "loader.user", ""); this.loaderPassword = GetValue(config, "loader.password", ""); this.loaderTimeout = GetValue(config, "loader.timeout", 0); this.installGlobalPlugins = []; this.installScenePlugins = []; var plugins = GetValue(config, "plugins", null); var defaultPlugins = DefaultPlugins.DefaultScene; if (plugins) { if (Array.isArray(plugins)) { this.defaultPlugins = plugins } else if (IsPlainObject(plugins)) { this.installGlobalPlugins = GetFastValue(plugins, "global", []); this.installScenePlugins = GetFastValue(plugins, "scene", []); if (Array.isArray(plugins.default)) { defaultPlugins = plugins.default } else if (Array.isArray(plugins.defaultMerge)) { defaultPlugins = defaultPlugins.concat(plugins.defaultMerge) } } } this.defaultPlugins = defaultPlugins; var pngPrefix = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAg"; this.defaultImage = GetValue(config, "images.default", pngPrefix + "AQMAAABJtOi3AAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAABVJREFUeF7NwIEAAAAAgKD9qdeocAMAoAABm3DkcAAAAABJRU5ErkJggg=="); this.missingImage = GetValue(config, "images.missing", pngPrefix + "CAIAAAD8GO2jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJ9JREFUeNq01ssOwyAMRFG46v//Mt1ESmgh+DFmE2GPOBARKb2NVjo+17PXLD8a1+pl5+A+wSgFygymWYHBb0FtsKhJDdZlncG2IzJ4ayoMDv20wTmSMzClEgbWYNTAkQ0Z+OJ+A/eWnAaR9+oxCF4Os0H8htsMUp+pwcgBBiMNnAwF8GqIgL2hAzaGFFgZauDPKABmowZ4GL369/0rwACp2yA/ttmvsQAAAABJRU5ErkJggg=="); if (window) { if (window.FORCE_WEBGL) { this.renderType = CONST.WEBGL } else if (window.FORCE_CANVAS) { this.renderType = CONST.CANVAS } } } }); module.exports = Config }, function(module, exports, __webpack_require__) { var OS = __webpack_require__(92); var Browser = __webpack_require__(115); var Input = { gamepads: false, mspointer: false, touch: false, wheelEvent: null }; function init() { if ("ontouchstart" in document.documentElement || navigator.maxTouchPoints && navigator.maxTouchPoints >= 1) { Input.touch = true } if (navigator.msPointerEnabled || navigator.pointerEnabled) { Input.mspointer = true } if (navigator.getGamepads) { Input.gamepads = true } if (!OS.cocoonJS) { if ("onwheel" in window || Browser.ie && "WheelEvent" in window) { Input.wheelEvent = "wheel" } else if ("onmousewheel" in window) { Input.wheelEvent = "mousewheel" } else if (Browser.firefox && "MouseScrollEvent" in window) { Input.wheelEvent = "DOMMouseScroll" } } return Input } module.exports = init() }, function(module, exports, __webpack_require__) { var Browser = __webpack_require__(115); var Audio = { audioData: false, dolby: false, m4a: false, mp3: false, ogg: false, opus: false, wav: false, webAudio: false, webm: false }; function init() { Audio.audioData = !!window["Audio"]; Audio.webAudio = !!(window["AudioContext"] || window["webkitAudioContext"]); var audioElement = document.createElement("audio"); var result = !!audioElement.canPlayType; try { if (result) { if (audioElement.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, "")) { Audio.ogg = true } if (audioElement.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/, "") || audioElement.canPlayType("audio/opus;").replace(/^no$/, "")) { Audio.opus = true } if (audioElement.canPlayType("audio/mpeg;").replace(/^no$/, "")) { Audio.mp3 = true } if (audioElement.canPlayType('audio/wav; codecs="1"').replace(/^no$/, "")) { Audio.wav = true } if (audioElement.canPlayType("audio/x-m4a;") || audioElement.canPlayType("audio/aac;").replace(/^no$/, "")) { Audio.m4a = true } if (audioElement.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, "")) { Audio.webm = true } if (audioElement.canPlayType('audio/mp4;codecs="ec-3"') !== "") { if (Browser.edge) { Audio.dolby = true } else if (Browser.safari && Browser.safariVersion >= 9) { if (/Mac OS X (\d+)_(\d+)/.test(navigator.userAgent)) { var major = parseInt(RegExp.$1, 10); var minor = parseInt(RegExp.$2, 10); if (major === 10 && minor >= 11 || major > 10) { Audio.dolby = true } } } } } } catch (e) {} return Audio } module.exports = init() }, function(module, exports) { var Video = { h264Video: false, hlsVideo: false, mp4Video: false, oggVideo: false, vp9Video: false, webmVideo: false }; function init() { var videoElement = document.createElement("video"); var result = !!videoElement.canPlayType; try { if (result) { if (videoElement.canPlayType('video/ogg; codecs="theora"').replace(/^no$/, "")) { Video.oggVideo = true } if (videoElement.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/, "")) { Video.h264Video = true; Video.mp4Video = true } if (videoElement.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/, "")) { Video.webmVideo = true } if (videoElement.canPlayType('video/webm; codecs="vp9"').replace(/^no$/, "")) { Video.vp9Video = true } if (videoElement.canPlayType('application/x-mpegURL; codecs="avc1.42E01E"').replace(/^no$/, "")) { Video.hlsVideo = true } } } catch (e) {} return Video } module.exports = init() }, function(module, exports) { var Fullscreen = { available: false, cancel: "", keyboard: false, request: "" }; function init() { var i; var fs = ["requestFullscreen", "requestFullScreen", "webkitRequestFullscreen", "webkitRequestFullScreen", "msRequestFullscreen", "msRequestFullScreen", "mozRequestFullScreen", "mozRequestFullscreen"]; var element = document.createElement("div"); for (i = 0; i < fs.length; i++) { if (element[fs[i]]) { Fullscreen.available = true; Fullscreen.request = fs[i]; break } } var cfs = ["cancelFullScreen", "exitFullscreen", "webkitCancelFullScreen", "webkitExitFullscreen", "msCancelFullScreen", "msExitFullscreen", "mozCancelFullScreen", "mozExitFullscreen"]; if (Fullscreen.available) { for (i = 0; i < cfs.length; i++) { if (document[cfs[i]]) { Fullscreen.cancel = cfs[i]; break } } } if (window["Element"] && Element["ALLOW_KEYBOARD_INPUT"]) { Fullscreen.keyboard = true } return Fullscreen } module.exports = init() }, function(module, exports, __webpack_require__) { var CanvasInterpolation = __webpack_require__(295); var CanvasPool = __webpack_require__(28); var CONST = __webpack_require__(26); var Features = __webpack_require__(169); var CreateRenderer = function(game) { var config = game.config; if (config.renderType !== CONST.HEADLESS) { if (config.renderType === CONST.CANVAS || config.renderType !== CONST.CANVAS && !Features.webGL) { if (Features.canvas) { config.renderType = CONST.CANVAS } else { throw new Error("Cannot create Canvas or WebGL context, aborting.") } } else { config.renderType = CONST.WEBGL } } if (!config.antialias) { CanvasPool.disableSmoothing() } if (config.canvas) { game.canvas = config.canvas; game.canvas.width = game.config.width; game.canvas.height = game.config.height } else { game.canvas = CanvasPool.create(game, config.width * config.resolution, config.height * config.resolution, config.renderType) } if (config.canvasStyle) { game.canvas.style = config.canvasStyle } if (!config.antialias) { CanvasInterpolation.setCrisp(game.canvas) } game.canvas.style.width = (config.width * config.zoom).toString() + "px"; game.canvas.style.height = (config.height * config.zoom).toString() + "px"; if (config.renderType === CONST.HEADLESS) { return } var CanvasRenderer; var WebGLRenderer; if (true) { CanvasRenderer = __webpack_require__(304); WebGLRenderer = __webpack_require__(307); if (config.renderType === CONST.WEBGL) { game.renderer = new WebGLRenderer(game) } else { game.renderer = new CanvasRenderer(game); game.context = game.renderer.gameContext } } if (false) { WebGLRenderer = require("../renderer/webgl/WebGLRenderer"); config.renderType = CONST.WEBGL; game.renderer = new WebGLRenderer(game) } if (false) { CanvasRenderer = require("../renderer/canvas/CanvasRenderer"); config.renderType = CONST.CANVAS; game.renderer = new CanvasRenderer(game); game.context = game.renderer.gameContext } }; module.exports = CreateRenderer }, function(module, exports) { module.exports = ["#define SHADER_NAME PHASER_BITMAP_MASK_FS", "", "precision mediump float;", "", "uniform vec2 uResolution;", "uniform sampler2D uMainSampler;", "uniform sampler2D uMaskSampler;", "uniform bool uInvertMaskAlpha;", "", "void main()", "{", " vec2 uv = gl_FragCoord.xy / uResolution;", " vec4 mainColor = texture2D(uMainSampler, uv);", " vec4 maskColor = texture2D(uMaskSampler, uv);", " float alpha = mainColor.a;", "", " if (!uInvertMaskAlpha)", " {", " alpha *= (maskColor.a);", " }", " else", " {", " alpha *= (1.0 - maskColor.a);", " }", "", " gl_FragColor = vec4(mainColor.rgb * alpha, alpha);", "}", ""].join("\n") }, function(module, exports) { module.exports = ["#define SHADER_NAME PHASER_BITMAP_MASK_VS", "", "precision mediump float;", "", "attribute vec2 inPosition;", "", "void main()", "{", " gl_Position = vec4(inPosition, 0.0, 1.0);", "}", ""].join("\n") }, function(module, exports) { module.exports = ["#define SHADER_NAME PHASER_FORWARD_DIFFUSE_FS", "", "precision mediump float;", "", "struct Light", "{", " vec2 position;", " vec3 color;", " float intensity;", " float radius;", "};", "", "const int kMaxLights = %LIGHT_COUNT%;", "", "uniform vec4 uCamera; /* x, y, rotation, zoom */", "uniform vec2 uResolution;", "uniform sampler2D uMainSampler;", "uniform sampler2D uNormSampler;", "uniform vec3 uAmbientLightColor;", "uniform Light uLights[kMaxLights];", "", "varying vec2 outTexCoord;", "varying vec4 outTint;", "", "void main()", "{", " vec3 finalColor = vec3(0.0, 0.0, 0.0);", " vec4 color = texture2D(uMainSampler, outTexCoord) * vec4(outTint.rgb * outTint.a, outTint.a);", " vec3 normalMap = texture2D(uNormSampler, outTexCoord).rgb;", " vec3 normal = normalize(vec3(normalMap * 2.0 - 1.0));", " vec2 res = vec2(min(uResolution.x, uResolution.y)) * uCamera.w;", "", " for (int index = 0; index < kMaxLights; ++index)", " {", " Light light = uLights[index];", " vec3 lightDir = vec3((light.position.xy / res) - (gl_FragCoord.xy / res), 0.1);", " vec3 lightNormal = normalize(lightDir);", " float distToSurf = length(lightDir) * uCamera.w;", " float diffuseFactor = max(dot(normal, lightNormal), 0.0);", " float radius = (light.radius / res.x * uCamera.w) * uCamera.w;", " float attenuation = clamp(1.0 - distToSurf * distToSurf / (radius * radius), 0.0, 1.0);", " vec3 diffuse = light.color * diffuseFactor;", " finalColor += (attenuation * diffuse) * light.intensity;", " }", "", " vec4 colorOutput = vec4(uAmbientLightColor + finalColor, 1.0);", " gl_FragColor = color * vec4(colorOutput.rgb * colorOutput.a, colorOutput.a);", "", "}", ""].join("\n") }, function(module, exports) { var ModelViewProjection = { modelMatrixDirty: false, viewMatrixDirty: false, projectionMatrixDirty: false, modelMatrix: null, viewMatrix: null, projectionMatrix: null, mvpInit: function() { this.modelMatrixDirty = true; this.viewMatrixDirty = true; this.projectionMatrixDirty = true; this.modelMatrix = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]); this.viewMatrix = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]); this.projectionMatrix = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]); return this }, mvpUpdate: function() { var program = this.program; if (this.modelMatrixDirty) { this.renderer.setMatrix4(program, "uModelMatrix", false, this.modelMatrix); this.modelMatrixDirty = false } if (this.viewMatrixDirty) { this.renderer.setMatrix4(program, "uViewMatrix", false, this.viewMatrix); this.viewMatrixDirty = false } if (this.projectionMatrixDirty) { this.renderer.setMatrix4(program, "uProjectionMatrix", false, this.projectionMatrix); this.projectionMatrixDirty = false } return this }, modelIdentity: function() { var modelMatrix = this.modelMatrix; modelMatrix[0] = 1; modelMatrix[1] = 0; modelMatrix[2] = 0; modelMatrix[3] = 0; modelMatrix[4] = 0; modelMatrix[5] = 1; modelMatrix[6] = 0; modelMatrix[7] = 0; modelMatrix[8] = 0; modelMatrix[9] = 0; modelMatrix[10] = 1; modelMatrix[11] = 0; modelMatrix[12] = 0; modelMatrix[13] = 0; modelMatrix[14] = 0; modelMatrix[15] = 1; this.modelMatrixDirty = true; return this }, modelScale: function(x, y, z) { var modelMatrix = this.modelMatrix; modelMatrix[0] = modelMatrix[0] * x; modelMatrix[1] = modelMatrix[1] * x; modelMatrix[2] = modelMatrix[2] * x; modelMatrix[3] = modelMatrix[3] * x; modelMatrix[4] = modelMatrix[4] * y; modelMatrix[5] = modelMatrix[5] * y; modelMatrix[6] = modelMatrix[6] * y; modelMatrix[7] = modelMatrix[7] * y; modelMatrix[8] = modelMatrix[8] * z; modelMatrix[9] = modelMatrix[9] * z; modelMatrix[10] = modelMatrix[10] * z; modelMatrix[11] = modelMatrix[11] * z; this.modelMatrixDirty = true; return this }, modelTranslate: function(x, y, z) { var modelMatrix = this.modelMatrix; modelMatrix[12] = modelMatrix[0] * x + modelMatrix[4] * y + modelMatrix[8] * z + modelMatrix[12]; modelMatrix[13] = modelMatrix[1] * x + modelMatrix[5] * y + modelMatrix[9] * z + modelMatrix[13]; modelMatrix[14] = modelMatrix[2] * x + modelMatrix[6] * y + modelMatrix[10] * z + modelMatrix[14]; modelMatrix[15] = modelMatrix[3] * x + modelMatrix[7] * y + modelMatrix[11] * z + modelMatrix[15]; this.modelMatrixDirty = true; return this }, modelRotateX: function(radians) { var modelMatrix = this.modelMatrix; var s = Math.sin(radians); var c = Math.cos(radians); var a10 = modelMatrix[4]; var a11 = modelMatrix[5]; var a12 = modelMatrix[6]; var a13 = modelMatrix[7]; var a20 = modelMatrix[8]; var a21 = modelMatrix[9]; var a22 = modelMatrix[10]; var a23 = modelMatrix[11]; modelMatrix[4] = a10 * c + a20 * s; modelMatrix[5] = a11 * c + a21 * s; modelMatrix[6] = a12 * c + a22 * s; modelMatrix[7] = a13 * c + a23 * s; modelMatrix[8] = a20 * c - a10 * s; modelMatrix[9] = a21 * c - a11 * s; modelMatrix[10] = a22 * c - a12 * s; modelMatrix[11] = a23 * c - a13 * s; this.modelMatrixDirty = true; return this }, modelRotateY: function(radians) { var modelMatrix = this.modelMatrix; var s = Math.sin(radians); var c = Math.cos(radians); var a00 = modelMatrix[0]; var a01 = modelMatrix[1]; var a02 = modelMatrix[2]; var a03 = modelMatrix[3]; var a20 = modelMatrix[8]; var a21 = modelMatrix[9]; var a22 = modelMatrix[10]; var a23 = modelMatrix[11]; modelMatrix[0] = a00 * c - a20 * s; modelMatrix[1] = a01 * c - a21 * s; modelMatrix[2] = a02 * c - a22 * s; modelMatrix[3] = a03 * c - a23 * s; modelMatrix[8] = a00 * s + a20 * c; modelMatrix[9] = a01 * s + a21 * c; modelMatrix[10] = a02 * s + a22 * c; modelMatrix[11] = a03 * s + a23 * c; this.modelMatrixDirty = true; return this }, modelRotateZ: function(radians) { var modelMatrix = this.modelMatrix; var s = Math.sin(radians); var c = Math.cos(radians); var a00 = modelMatrix[0]; var a01 = modelMatrix[1]; var a02 = modelMatrix[2]; var a03 = modelMatrix[3]; var a10 = modelMatrix[4]; var a11 = modelMatrix[5]; var a12 = modelMatrix[6]; var a13 = modelMatrix[7]; modelMatrix[0] = a00 * c + a10 * s; modelMatrix[1] = a01 * c + a11 * s; modelMatrix[2] = a02 * c + a12 * s; modelMatrix[3] = a03 * c + a13 * s; modelMatrix[4] = a10 * c - a00 * s; modelMatrix[5] = a11 * c - a01 * s; modelMatrix[6] = a12 * c - a02 * s; modelMatrix[7] = a13 * c - a03 * s; this.modelMatrixDirty = true; return this }, viewIdentity: function() { var viewMatrix = this.viewMatrix; viewMatrix[0] = 1; viewMatrix[1] = 0; viewMatrix[2] = 0; viewMatrix[3] = 0; viewMatrix[4] = 0; viewMatrix[5] = 1; viewMatrix[6] = 0; viewMatrix[7] = 0; viewMatrix[8] = 0; viewMatrix[9] = 0; viewMatrix[10] = 1; viewMatrix[11] = 0; viewMatrix[12] = 0; viewMatrix[13] = 0; viewMatrix[14] = 0; viewMatrix[15] = 1; this.viewMatrixDirty = true; return this }, viewScale: function(x, y, z) { var viewMatrix = this.viewMatrix; viewMatrix[0] = viewMatrix[0] * x; viewMatrix[1] = viewMatrix[1] * x; viewMatrix[2] = viewMatrix[2] * x; viewMatrix[3] = viewMatrix[3] * x; viewMatrix[4] = viewMatrix[4] * y; viewMatrix[5] = viewMatrix[5] * y; viewMatrix[6] = viewMatrix[6] * y; viewMatrix[7] = viewMatrix[7] * y; viewMatrix[8] = viewMatrix[8] * z; viewMatrix[9] = viewMatrix[9] * z; viewMatrix[10] = viewMatrix[10] * z; viewMatrix[11] = viewMatrix[11] * z; this.viewMatrixDirty = true; return this }, viewTranslate: function(x, y, z) { var viewMatrix = this.viewMatrix; viewMatrix[12] = viewMatrix[0] * x + viewMatrix[4] * y + viewMatrix[8] * z + viewMatrix[12]; viewMatrix[13] = viewMatrix[1] * x + viewMatrix[5] * y + viewMatrix[9] * z + viewMatrix[13]; viewMatrix[14] = viewMatrix[2] * x + viewMatrix[6] * y + viewMatrix[10] * z + viewMatrix[14]; viewMatrix[15] = viewMatrix[3] * x + viewMatrix[7] * y + viewMatrix[11] * z + viewMatrix[15]; this.viewMatrixDirty = true; return this }, viewRotateX: function(radians) { var viewMatrix = this.viewMatrix; var s = Math.sin(radians); var c = Math.cos(radians); var a10 = viewMatrix[4]; var a11 = viewMatrix[5]; var a12 = viewMatrix[6]; var a13 = viewMatrix[7]; var a20 = viewMatrix[8]; var a21 = viewMatrix[9]; var a22 = viewMatrix[10]; var a23 = viewMatrix[11]; viewMatrix[4] = a10 * c + a20 * s; viewMatrix[5] = a11 * c + a21 * s; viewMatrix[6] = a12 * c + a22 * s; viewMatrix[7] = a13 * c + a23 * s; viewMatrix[8] = a20 * c - a10 * s; viewMatrix[9] = a21 * c - a11 * s; viewMatrix[10] = a22 * c - a12 * s; viewMatrix[11] = a23 * c - a13 * s; this.viewMatrixDirty = true; return this }, viewRotateY: function(radians) { var viewMatrix = this.viewMatrix; var s = Math.sin(radians); var c = Math.cos(radians); var a00 = viewMatrix[0]; var a01 = viewMatrix[1]; var a02 = viewMatrix[2]; var a03 = viewMatrix[3]; var a20 = viewMatrix[8]; var a21 = viewMatrix[9]; var a22 = viewMatrix[10]; var a23 = viewMatrix[11]; viewMatrix[0] = a00 * c - a20 * s; viewMatrix[1] = a01 * c - a21 * s; viewMatrix[2] = a02 * c - a22 * s; viewMatrix[3] = a03 * c - a23 * s; viewMatrix[8] = a00 * s + a20 * c; viewMatrix[9] = a01 * s + a21 * c; viewMatrix[10] = a02 * s + a22 * c; viewMatrix[11] = a03 * s + a23 * c; this.viewMatrixDirty = true; return this }, viewRotateZ: function(radians) { var viewMatrix = this.viewMatrix; var s = Math.sin(radians); var c = Math.cos(radians); var a00 = viewMatrix[0]; var a01 = viewMatrix[1]; var a02 = viewMatrix[2]; var a03 = viewMatrix[3]; var a10 = viewMatrix[4]; var a11 = viewMatrix[5]; var a12 = viewMatrix[6]; var a13 = viewMatrix[7]; viewMatrix[0] = a00 * c + a10 * s; viewMatrix[1] = a01 * c + a11 * s; viewMatrix[2] = a02 * c + a12 * s; viewMatrix[3] = a03 * c + a13 * s; viewMatrix[4] = a10 * c - a00 * s; viewMatrix[5] = a11 * c - a01 * s; viewMatrix[6] = a12 * c - a02 * s; viewMatrix[7] = a13 * c - a03 * s; this.viewMatrixDirty = true; return this }, viewLoad2D: function(matrix2D) { var vm = this.viewMatrix; vm[0] = matrix2D[0]; vm[1] = matrix2D[1]; vm[2] = 0; vm[3] = 0; vm[4] = matrix2D[2]; vm[5] = matrix2D[3]; vm[6] = 0; vm[7] = 0; vm[8] = matrix2D[4]; vm[9] = matrix2D[5]; vm[10] = 1; vm[11] = 0; vm[12] = 0; vm[13] = 0; vm[14] = 0; vm[15] = 1; this.viewMatrixDirty = true; return this }, viewLoad: function(matrix) { var vm = this.viewMatrix; vm[0] = matrix[0]; vm[1] = matrix[1]; vm[2] = matrix[2]; vm[3] = matrix[3]; vm[4] = matrix[4]; vm[5] = matrix[5]; vm[6] = matrix[6]; vm[7] = matrix[7]; vm[8] = matrix[8]; vm[9] = matrix[9]; vm[10] = matrix[10]; vm[11] = matrix[11]; vm[12] = matrix[12]; vm[13] = matrix[13]; vm[14] = matrix[14]; vm[15] = matrix[15]; this.viewMatrixDirty = true; return this }, projIdentity: function() { var projectionMatrix = this.projectionMatrix; projectionMatrix[0] = 1; projectionMatrix[1] = 0; projectionMatrix[2] = 0; projectionMatrix[3] = 0; projectionMatrix[4] = 0; projectionMatrix[5] = 1; projectionMatrix[6] = 0; projectionMatrix[7] = 0; projectionMatrix[8] = 0; projectionMatrix[9] = 0; projectionMatrix[10] = 1; projectionMatrix[11] = 0; projectionMatrix[12] = 0; projectionMatrix[13] = 0; projectionMatrix[14] = 0; projectionMatrix[15] = 1; this.projectionMatrixDirty = true; return this }, projOrtho: function(left, right, bottom, top, near, far) { var projectionMatrix = this.projectionMatrix; var leftRight = 1 / (left - right); var bottomTop = 1 / (bottom - top); var nearFar = 1 / (near - far); projectionMatrix[0] = -2 * leftRight; projectionMatrix[1] = 0; projectionMatrix[2] = 0; projectionMatrix[3] = 0; projectionMatrix[4] = 0; projectionMatrix[5] = -2 * bottomTop; projectionMatrix[6] = 0; projectionMatrix[7] = 0; projectionMatrix[8] = 0; projectionMatrix[9] = 0; projectionMatrix[10] = 2 * nearFar; projectionMatrix[11] = 0; projectionMatrix[12] = (left + right) * leftRight; projectionMatrix[13] = (top + bottom) * bottomTop; projectionMatrix[14] = (far + near) * nearFar; projectionMatrix[15] = 1; this.projectionMatrixDirty = true; return this }, projPersp: function(fovy, aspectRatio, near, far) { var projectionMatrix = this.projectionMatrix; var fov = 1 / Math.tan(fovy / 2); var nearFar = 1 / (near - far); projectionMatrix[0] = fov / aspectRatio; projectionMatrix[1] = 0; projectionMatrix[2] = 0; projectionMatrix[3] = 0; projectionMatrix[4] = 0; projectionMatrix[5] = fov; projectionMatrix[6] = 0; projectionMatrix[7] = 0; projectionMatrix[8] = 0; projectionMatrix[9] = 0; projectionMatrix[10] = (far + near) * nearFar; projectionMatrix[11] = -1; projectionMatrix[12] = 0; projectionMatrix[13] = 0; projectionMatrix[14] = 2 * far * near * nearFar; projectionMatrix[15] = 0; this.projectionMatrixDirty = true; return this } }; module.exports = ModelViewProjection }, function(module, exports) { module.exports = ["#define SHADER_NAME PHASER_TEXTURE_TINT_FS", "", "precision mediump float;", "", "uniform sampler2D uMainSampler;", "", "varying vec2 outTexCoord;", "varying float outTintEffect;", "varying vec4 outTint;", "", "void main()", "{", " vec4 texture = texture2D(uMainSampler, outTexCoord);", " vec4 texel = vec4(outTint.rgb * outTint.a, outTint.a);", " vec4 color = texture;", "", " if (outTintEffect == 0.0)", " {", " // Multiply texture tint", " color = texture * texel;", " }", " else if (outTintEffect == 1.0)", " {", " // Solid color + texture alpha", " color.rgb = mix(texture.rgb, outTint.rgb * outTint.a, texture.a);", " color.a = texture.a * texel.a;", " }", " else if (outTintEffect == 2.0)", " {", " // Solid color, no texture", " color = texel;", " }", "", " gl_FragColor = color;", "}", ""].join("\n") }, function(module, exports) { module.exports = ["#define SHADER_NAME PHASER_TEXTURE_TINT_VS", "", "precision mediump float;", "", "uniform mat4 uProjectionMatrix;", "uniform mat4 uViewMatrix;", "uniform mat4 uModelMatrix;", "", "attribute vec2 inPosition;", "attribute vec2 inTexCoord;", "attribute float inTintEffect;", "attribute vec4 inTint;", "", "varying vec2 outTexCoord;", "varying float outTintEffect;", "varying vec4 outTint;", "", "void main ()", "{", " gl_Position = uProjectionMatrix * uViewMatrix * uModelMatrix * vec4(inPosition, 1.0, 1.0);", "", " outTexCoord = inTexCoord;", " outTint = inTint;", " outTintEffect = inTintEffect;", "}", "", ""].join("\n") }, function(module, exports, __webpack_require__) { var CONST = __webpack_require__(26); var DebugHeader = function(game) { var config = game.config; if (config.hideBanner) { return } var renderType = "WebGL"; if (config.renderType === CONST.CANVAS) { renderType = "Canvas" } else if (config.renderType === CONST.HEADLESS) { renderType = "Headless" } var audioConfig = config.audio; var deviceAudio = game.device.audio; var audioType; if (deviceAudio.webAudio && !(audioConfig && audioConfig.disableWebAudio)) { audioType = "Web Audio" } else if (audioConfig && audioConfig.noAudio || !deviceAudio.webAudio && !deviceAudio.audioData) { audioType = "No Audio" } else { audioType = "HTML5 Audio" } if (!game.device.browser.ie) { var c = ""; var args = [c]; if (Array.isArray(config.bannerBackgroundColor)) { var lastColor; config.bannerBackgroundColor.forEach(function(color) { c = c.concat("%c "); args.push("background: " + color); lastColor = color }); args[args.length - 1] = "color: " + config.bannerTextColor + "; background: " + lastColor } else { c = c.concat("%c "); args.push("color: " + config.bannerTextColor + "; background: " + config.bannerBackgroundColor) } args.push("background: #fff"); if (config.gameTitle) { c = c.concat(config.gameTitle); if (config.gameVersion) { c = c.concat(" v" + config.gameVersion) } if (!config.hidePhaser) { c = c.concat(" / ") } } var fb = typeof PLUGIN_FBINSTANT ? "-FB" : ""; if (!config.hidePhaser) { c = c.concat("Phaser v" + CONST.VERSION + fb + " (" + renderType + " | " + audioType + ")") } c = c.concat(" %c " + config.gameURL); args[0] = c; console.log.apply(console, args) } else if (window["console"]) { console.log("Phaser v" + CONST.VERSION + " / https://phaser.io") } }; module.exports = DebugHeader }, function(module, exports, __webpack_require__) { var GetFastValue = __webpack_require__(1); var UppercaseFirst = __webpack_require__(322); var GetPhysicsPlugins = function(sys) { var defaultSystem = sys.game.config.defaultPhysicsSystem; var sceneSystems = GetFastValue(sys.settings, "physics", false); if (!defaultSystem && !sceneSystems) { return } var output = []; if (defaultSystem) { output.push(UppercaseFirst(defaultSystem + "Physics")) } if (sceneSystems) { for (var key in sceneSystems) { key = UppercaseFirst(key.concat("Physics")); if (output.indexOf(key) === -1) { output.push(key) } } } return output }; module.exports = GetPhysicsPlugins }, function(module, exports, __webpack_require__) { var GetFastValue = __webpack_require__(1); var GetScenePlugins = function(sys) { var defaultPlugins = sys.plugins.getDefaultScenePlugins(); var scenePlugins = GetFastValue(sys.settings, "plugins", false); if (Array.isArray(scenePlugins)) { return scenePlugins } else if (defaultPlugins) { return defaultPlugins } else { return [] } }; module.exports = GetScenePlugins }, function(module, exports) { var InjectionMap = { game: "game", anims: "anims", cache: "cache", plugins: "plugins", registry: "registry", sound: "sound", textures: "textures", events: "events", cameras: "cameras", add: "add", make: "make", scenePlugin: "scene", displayList: "children", lights: "lights", data: "data", input: "input", load: "load", time: "time", tweens: "tweens", arcadePhysics: "physics", impactPhysics: "impact", matterPhysics: "matter" }; if (typeof PLUGIN_CAMERA3D) { InjectionMap.cameras3d = "cameras3d" } if (typeof PLUGIN_FBINSTANT) { InjectionMap.facebook = "facebook" } module.exports = InjectionMap }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Color = __webpack_require__(49); var IsSizePowerOfTwo = __webpack_require__(116); var Texture = __webpack_require__(174); var CanvasTexture = new Class({ Extends: Texture, initialize: function CanvasTexture(manager, key, source, width, height) { Texture.call(this, manager, key, source, width, height); this.add("__BASE", 0, 0, 0, width, height); this._source = this.frames["__BASE"].source; this.canvas = this._source.image; this.context = this.canvas.getContext("2d"); this.width = width; this.height = height; this.imageData = this.context.getImageData(0, 0, width, height); this.data = null; if (this.imageData) { this.data = this.imageData.data } this.pixels = null; this.buffer; if (this.data) { if (this.imageData.data.buffer) { this.buffer = this.imageData.data.buffer; this.pixels = new Uint32Array(this.buffer) } else if (window.ArrayBuffer) { this.buffer = new ArrayBuffer(this.imageData.data.length); this.pixels = new Uint32Array(this.buffer) } else { this.pixels = this.imageData.data } } }, update: function() { this.imageData = this.context.getImageData(0, 0, this.width, this.height); this.data = this.imageData.data; if (this.imageData.data.buffer) { this.buffer = this.imageData.data.buffer; this.pixels = new Uint32Array(this.buffer) } else if (window.ArrayBuffer) { this.buffer = new ArrayBuffer(this.imageData.data.length); this.pixels = new Uint32Array(this.buffer) } else { this.pixels = this.imageData.data } return this }, draw: function(x, y, source) { this.context.drawImage(source, x, y); return this.update() }, getPixel: function(x, y, out) { if (!out) { out = new Color } var index = ~~(x + y * this.width); index *= 4; var r = this.data[index]; var g = this.data[++index]; var b = this.data[++index]; var a = this.data[++index]; return out.setTo(r, g, b, a) }, refresh: function() { this._source.update(); return this }, getCanvas: function() { return this.canvas }, getContext: function() { return this.context }, clear: function() { this.context.clearRect(0, 0, this.width, this.height); return this.update() }, setSize: function(width, height) { if (height === undefined) { height = width } if (width !== this.width || height !== this.height) { this.canvas.width = width; this.canvas.height = height; this._source.width = width; this._source.height = height; this._source.isPowerOf2 = IsSizePowerOfTwo(width, height); this.frames["__BASE"].setSize(width, height, 0, 0); this.refresh() } return this } }); module.exports = CanvasTexture }, function(module, exports) { var AtlasXML = function(texture, sourceIndex, xml) { if (!xml.getElementsByTagName("TextureAtlas")) { console.warn("Invalid Texture Atlas XML given"); return } var source = texture.source[sourceIndex]; texture.add("__BASE", sourceIndex, 0, 0, source.width, source.height); var frames = xml.getElementsByTagName("SubTexture"); var newFrame; for (var i = 0; i < frames.length; i++) { var frame = frames[i].attributes; var name = frame.name.value; var x = parseInt(frame.x.value, 10); var y = parseInt(frame.y.value, 10); var width = parseInt(frame.width.value, 10); var height = parseInt(frame.height.value, 10); newFrame = texture.add(name, sourceIndex, x, y, width, height); if (frame.frameX) { var frameX = Math.abs(parseInt(frame.frameX.value, 10)); var frameY = Math.abs(parseInt(frame.frameY.value, 10)); var frameWidth = parseInt(frame.frameWidth.value, 10); var frameHeight = parseInt(frame.frameHeight.value, 10); newFrame.setTrim(width, height, frameX, frameY, frameWidth, frameHeight) } } return texture }; module.exports = AtlasXML }, function(module, exports) { var Canvas = function(texture, sourceIndex) { var source = texture.source[sourceIndex]; texture.add("__BASE", sourceIndex, 0, 0, source.width, source.height); return texture }; module.exports = Canvas }, function(module, exports) { var Image = function(texture, sourceIndex) { var source = texture.source[sourceIndex]; texture.add("__BASE", sourceIndex, 0, 0, source.width, source.height); return texture }; module.exports = Image }, function(module, exports, __webpack_require__) { var Clone = __webpack_require__(64); var JSONArray = function(texture, sourceIndex, json) { if (!json["frames"] && !json["textures"]) { console.warn("Invalid Texture Atlas JSON Array"); return } var source = texture.source[sourceIndex]; texture.add("__BASE", sourceIndex, 0, 0, source.width, source.height); var frames = Array.isArray(json.textures) ? json.textures[sourceIndex].frames : json.frames; var newFrame; for (var i = 0; i < frames.length; i++) { var src = frames[i]; newFrame = texture.add(src.filename, sourceIndex, src.frame.x, src.frame.y, src.frame.w, src.frame.h); if (src.trimmed) { newFrame.setTrim(src.sourceSize.w, src.sourceSize.h, src.spriteSourceSize.x, src.spriteSourceSize.y, src.spriteSourceSize.w, src.spriteSourceSize.h) } if (src.rotated) { newFrame.rotated = true; newFrame.updateUVsInverted() } if (src.anchor) { newFrame.customPivot = true; newFrame.pivotX = src.anchor.x; newFrame.pivotY = src.anchor.y } newFrame.customData = Clone(src) } for (var dataKey in json) { if (dataKey === "frames") { continue } if (Array.isArray(json[dataKey])) { texture.customData[dataKey] = json[dataKey].slice(0) } else { texture.customData[dataKey] = json[dataKey] } } return texture }; module.exports = JSONArray }, function(module, exports, __webpack_require__) { var Clone = __webpack_require__(64); var JSONHash = function(texture, sourceIndex, json) { if (!json["frames"]) { console.warn("Invalid Texture Atlas JSON Hash given, missing 'frames' Object"); return } var source = texture.source[sourceIndex]; texture.add("__BASE", sourceIndex, 0, 0, source.width, source.height); var frames = json["frames"]; var newFrame; for (var key in frames) { var src = frames[key]; newFrame = texture.add(key, sourceIndex, src.frame.x, src.frame.y, src.frame.w, src.frame.h); if (src.trimmed) { newFrame.setTrim(src.sourceSize.w, src.sourceSize.h, src.spriteSourceSize.x, src.spriteSourceSize.y, src.spriteSourceSize.w, src.spriteSourceSize.h) } if (src.rotated) { newFrame.rotated = true; newFrame.updateUVsInverted() } newFrame.customData = Clone(src) } for (var dataKey in json) { if (dataKey === "frames") { continue } if (Array.isArray(json[dataKey])) { texture.customData[dataKey] = json[dataKey].slice(0) } else { texture.customData[dataKey] = json[dataKey] } } return texture }; module.exports = JSONHash }, function(module, exports, __webpack_require__) { var GetFastValue = __webpack_require__(1); var SpriteSheet = function(texture, sourceIndex, x, y, width, height, config) { var frameWidth = GetFastValue(config, "frameWidth", null); var frameHeight = GetFastValue(config, "frameHeight", frameWidth); if (frameWidth === null) { throw new Error("TextureManager.SpriteSheet: Invalid frameWidth given.") } var source = texture.source[sourceIndex]; texture.add("__BASE", sourceIndex, 0, 0, source.width, source.height); var startFrame = GetFastValue(config, "startFrame", 0); var endFrame = GetFastValue(config, "endFrame", -1); var margin = GetFastValue(config, "margin", 0); var spacing = GetFastValue(config, "spacing", 0); var row = Math.floor((width - margin + spacing) / (frameWidth + spacing)); var column = Math.floor((height - margin + spacing) / (frameHeight + spacing)); var total = row * column; if (total === 0) { console.warn("SpriteSheet frame dimensions will result in zero frames.") } if (startFrame > total || startFrame < -total) { startFrame = 0 } if (startFrame < 0) { startFrame = total + startFrame } if (endFrame !== -1) { total = startFrame + (endFrame + 1) } var fx = margin; var fy = margin; var ax = 0; var ay = 0; for (var i = 0; i < total; i++) { ax = 0; ay = 0; var w = fx + frameWidth; var h = fy + frameHeight; if (w > width) { ax = w - width } if (h > height) { ay = h - height } texture.add(i, sourceIndex, x + fx, y + fy, frameWidth - ax, frameHeight - ay); fx += frameWidth + spacing; if (fx + frameWidth > width) { fx = margin; fy += frameHeight + spacing } } return texture }; module.exports = SpriteSheet }, function(module, exports, __webpack_require__) { var GetFastValue = __webpack_require__(1); var SpriteSheetFromAtlas = function(texture, frame, config) { var frameWidth = GetFastValue(config, "frameWidth", null); var frameHeight = GetFastValue(config, "frameHeight", frameWidth); if (!frameWidth) { throw new Error("TextureManager.SpriteSheetFromAtlas: Invalid frameWidth given.") } var startFrame = GetFastValue(config, "startFrame", 0); var endFrame = GetFastValue(config, "endFrame", -1); var margin = GetFastValue(config, "margin", 0); var spacing = GetFastValue(config, "spacing", 0); var x = frame.cutX; var y = frame.cutY; var cutWidth = frame.cutWidth; var cutHeight = frame.cutHeight; var sheetWidth = frame.realWidth; var sheetHeight = frame.realHeight; var row = Math.floor((sheetWidth - margin + spacing) / (frameWidth + spacing)); var column = Math.floor((sheetHeight - margin + spacing) / (frameHeight + spacing)); var total = row * column; var leftPad = frame.x; var leftWidth = frameWidth - leftPad; var rightWidth = frameWidth - (sheetWidth - cutWidth - leftPad); var topPad = frame.y; var topHeight = frameHeight - topPad; var bottomHeight = frameHeight - (sheetHeight - cutHeight - topPad); if (startFrame > total || startFrame < -total) { startFrame = 0 } if (startFrame < 0) { startFrame = total + startFrame } if (endFrame !== -1) { total = startFrame + (endFrame + 1) } var sheetFrame; var frameX = margin; var frameY = margin; var frameIndex = 0; var sourceIndex = frame.sourceIndex; for (var sheetY = 0; sheetY < column; sheetY++) { var topRow = sheetY === 0; var bottomRow = sheetY === column - 1; for (var sheetX = 0; sheetX < row; sheetX++) { var leftRow = sheetX === 0; var rightRow = sheetX === row - 1; sheetFrame = texture.add(frameIndex, sourceIndex, x + frameX, y + frameY, frameWidth, frameHeight); if (leftRow || topRow || rightRow || bottomRow) { var destX = leftRow ? leftPad : 0; var destY = topRow ? topPad : 0; var destWidth = frameWidth; var destHeight = frameHeight; if (leftRow) { destWidth = leftWidth } else if (rightRow) { destWidth = rightWidth } if (topRow) { destHeight = topHeight } else if (bottomRow) { destHeight = bottomHeight } sheetFrame.cutWidth = destWidth; sheetFrame.cutHeight = destHeight; sheetFrame.setTrim(frameWidth, frameHeight, destX, destY, destWidth, destHeight) } frameX += spacing; if (leftRow) { frameX += leftWidth } else if (rightRow) { frameX += rightRow } else { frameX += frameWidth } frameIndex++ } frameX = margin; frameY += spacing; if (topRow) { frameY += topHeight } else if (bottomRow) { frameY += bottomHeight } else { frameY += frameHeight } } return texture }; module.exports = SpriteSheetFromAtlas }, function(module, exports) { var imageHeight = 0; var addFrame = function(texture, sourceIndex, name, frame) { var y = imageHeight - frame.y - frame.height; texture.add(name, sourceIndex, frame.x, y, frame.width, frame.height) }; var UnityYAML = function(texture, sourceIndex, yaml) { var source = texture.source[sourceIndex]; texture.add("__BASE", sourceIndex, 0, 0, source.width, source.height); imageHeight = source.height; var data = yaml.split("\n"); var lineRegExp = /^[ ]*(- )*(\w+)+[: ]+(.*)/; var prevSprite = ""; var currentSprite = ""; var rect = { x: 0, y: 0, width: 0, height: 0 }; for (var i = 0; i < data.length; i++) { var results = data[i].match(lineRegExp); if (!results) { continue } var isList = results[1] === "- "; var key = results[2]; var value = results[3]; if (isList) { if (currentSprite !== prevSprite) { addFrame(texture, sourceIndex, currentSprite, rect); prevSprite = currentSprite } rect = { x: 0, y: 0, width: 0, height: 0 } } if (key === "name") { currentSprite = value; continue } switch (key) { case "x": case "y": case "width": case "height": rect[key] = parseInt(value, 10); break } } if (currentSprite !== prevSprite) { addFrame(texture, sourceIndex, currentSprite, rect) } return texture }; module.exports = UnityYAML }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var GetValue = __webpack_require__(4); var NOOP = __webpack_require__(2); var RequestAnimationFrame = __webpack_require__(301); var TimeStep = new Class({ initialize: function TimeStep(game, config) { this.game = game; this.raf = new RequestAnimationFrame; this.started = false; this.running = false; this.minFps = GetValue(config, "min", 5); this.targetFps = GetValue(config, "target", 60); this._min = 1e3 / this.minFps; this._target = 1e3 / this.targetFps; this.actualFps = this.targetFps; this.nextFpsUpdate = 0; this.framesThisSecond = 0; this.callback = NOOP; this.forceSetTimeOut = GetValue(config, "forceSetTimeOut", false); this.time = 0; this.startTime = 0; this.lastTime = 0; this.frame = 0; this.inFocus = true; this._pauseTime = 0; this._coolDown = 0; this.delta = 0; this.deltaIndex = 0; this.deltaHistory = []; this.deltaSmoothingMax = GetValue(config, "deltaHistory", 10); this.panicMax = GetValue(config, "panicMax", 120); this.rawDelta = 0 }, blur: function() { this.inFocus = false }, focus: function() { this.inFocus = true; this.resetDelta() }, pause: function() { this._pauseTime = window.performance.now() }, resume: function() { this.resetDelta(); this.startTime += this.time - this._pauseTime }, resetDelta: function() { var now = window.performance.now(); this.time = now; this.lastTime = now; this.nextFpsUpdate = now + 1e3; this.framesThisSecond = 0; this.frame = 0; for (var i = 0; i < this.deltaSmoothingMax; i++) { this.deltaHistory[i] = Math.min(this._target, this.deltaHistory[i]) } this.delta = 0; this.deltaIndex = 0; this._coolDown = this.panicMax }, start: function(callback) { if (this.started) { return this } this.started = true; this.running = true; for (var i = 0; i < this.deltaSmoothingMax; i++) { this.deltaHistory[i] = this._target } this.resetDelta(); this.startTime = window.performance.now(); this.callback = callback; this.raf.start(this.step.bind(this), this.forceSetTimeOut) }, step: function(time) { this.frame++; var before = time - this.lastTime; if (before < 0) { before = 0 } this.rawDelta = before; var idx = this.deltaIndex; var history = this.deltaHistory; var max = this.deltaSmoothingMax; var dt = before; if (this._coolDown > 0 || !this.inFocus) { this._coolDown--; dt = Math.min(dt, this._target) } if (dt > this._min) { dt = history[idx]; dt = Math.min(dt, this._min) } history[idx] = dt; this.deltaIndex++; if (this.deltaIndex > max) { this.deltaIndex = 0 } var avg = 0; for (var i = 0; i < max; i++) { avg += history[i] } avg /= max; this.delta = avg; this.time += this.rawDelta; if (time > this.nextFpsUpdate) { this.actualFps = .25 * this.framesThisSecond + .75 * this.actualFps; this.nextFpsUpdate = time + 1e3; this.framesThisSecond = 0 } this.framesThisSecond++; var interpolation = avg / this._target; this.callback(time, avg, interpolation); this.lastTime = time }, tick: function() { this.step(window.performance.now()) }, sleep: function() { if (this.running) { this.raf.stop(); this.running = false } }, wake: function(seamless) { if (this.running) { this.sleep() } else if (seamless) { this.startTime += -this.lastTime + (this.lastTime = window.performance.now()) } this.raf.start(this.step.bind(this), this.useRAF); this.running = true; this.step(window.performance.now()) }, stop: function() { this.running = false; this.started = false; this.raf.stop(); return this }, destroy: function() { this.stop(); this.callback = NOOP; this.raf = null; this.game = null } }); module.exports = TimeStep }, function(module, exports) { var VisibilityHandler = function(game) { var hiddenVar; var eventEmitter = game.events; if (document.hidden !== undefined) { hiddenVar = "visibilitychange" } else { var vendors = ["webkit", "moz", "ms"]; vendors.forEach(function(prefix) { if (document[prefix + "Hidden"] !== undefined) { document.hidden = function() { return document[prefix + "Hidden"] }; hiddenVar = prefix + "visibilitychange" } }) } var onChange = function(event) { if (document.hidden || event.type === "pause") { eventEmitter.emit("hidden") } else { eventEmitter.emit("visible") } }; if (hiddenVar) { document.addEventListener(hiddenVar, onChange, false) } window.onblur = function() { eventEmitter.emit("blur") }; window.onfocus = function() { eventEmitter.emit("focus") }; if (window.focus && game.config.autoFocus) { window.focus(); game.canvas.addEventListener("mousedown", function() { window.focus() }, { passive: true }) } if (game.canvas) { game.canvas.onmouseout = function() { game.isOver = false; eventEmitter.emit("mouseout") }; game.canvas.onmouseover = function() { game.isOver = true; eventEmitter.emit("mouseover") } } }; module.exports = VisibilityHandler }, function(module, exports, __webpack_require__) { var AddToDOM = __webpack_require__(114); var CreateDOMContainer = function(game) { var config = game.config; if (!config.parent || !config.domCreateContainer) { return } var div = document.createElement("div"); div.style = ["display: block;", "width: " + game.canvas.width + "px;", "height: " + game.canvas.height + "px;", "padding: 0; margin: 0;", "position: absolute;", "overflow: hidden;", "pointer-events: none;"].join(" "); game.domContainer = div; AddToDOM(div, config.parent) }; module.exports = CreateDOMContainer }, function(module, exports) { var AdInstance = function(instance, video) { return { instance: instance, placementID: instance.getPlacementID(), shown: false, video: video } }; module.exports = AdInstance }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var EventEmitter = __webpack_require__(11); var LeaderboardScore = __webpack_require__(661); var Leaderboard = new Class({ Extends: EventEmitter, initialize: function Leaderboard(plugin, data) { EventEmitter.call(this); this.plugin = plugin; this.ref = data; this.name = data.getName(); this.contextID = data.getContextID(); this.entryCount = 0; this.playerScore = null; this.scores = []; this.getEntryCount() }, getEntryCount: function() { var _this = this; this.ref.getEntryCountAsync().then(function(count) { _this.entryCount = count; _this.emit("getentrycount", count, _this.name) }).catch(function(e) { console.warn(e) }); return this }, setScore: function(score, data) { if (data === undefined) { data = "" } var _this = this; this.ref.setScoreAsync(score, data).then(function(entry) { _this.emit("setscore", entry.getScore(), entry.getExtraData(), _this.name) }).catch(function(e) { console.warn(e) }); return this }, getPlayerScore: function() { var _this = this; this.ref.getPlayerEntryAsync().then(function(entry) { var score = LeaderboardScore(entry); _this.playerScore = score; _this.emit("getplayerscore", score, _this.name) }).catch(function(e) { console.warn(e) }); return this }, getScores: function(count, offset) { if (count === undefined) { count = 10 } if (offset === undefined) { offset = 0 } var _this = this; this.ref.getEntriesAsync().then(function(entries) { _this.scores = []; entries.forEach(function(entry) { _this.scores.push(LeaderboardScore(entry)) }); _this.emit("getscores", _this.scores, _this.name) }).catch(function(e) { console.warn(e) }); return this } }); module.exports = Leaderboard }, function(module, exports) { var LeaderboardScore = function(entry) { return { score: entry.getScore(), scoreFormatted: entry.getFormattedScore(), timestamp: entry.getTimestamp(), rank: entry.getRank(), data: entry.getExtraData(), playerName: entry.getPlayer().getName(), playerPhotoURL: entry.getPlayer().getPhoto(), playerID: entry.getPlayer().getID() } }; module.exports = LeaderboardScore }, function(module, exports, __webpack_require__) { var GetFastValue = __webpack_require__(1); var Product = function(data) { return { title: GetFastValue(data, "title", ""), productID: GetFastValue(data, "productID", ""), description: GetFastValue(data, "description", ""), imageURI: GetFastValue(data, "imageURI", ""), price: GetFastValue(data, "price", ""), priceCurrencyCode: GetFastValue(data, "priceCurrencyCode", "") } }; module.exports = Product }, function(module, exports, __webpack_require__) { var GetFastValue = __webpack_require__(1); var Purchase = function(data) { return { developerPayload: GetFastValue(data, "developerPayload", ""), paymentID: GetFastValue(data, "paymentID", ""), productID: GetFastValue(data, "productID", ""), purchaseTime: GetFastValue(data, "purchaseTime", ""), purchaseToken: GetFastValue(data, "purchaseToken", ""), signedRequest: GetFastValue(data, "signedRequest", "") } }; module.exports = Purchase }, function(module, exports, __webpack_require__) { var GameObjects = { DisplayList: __webpack_require__(665), GameObjectCreator: __webpack_require__(16), GameObjectFactory: __webpack_require__(5), UpdateList: __webpack_require__(693), Components: __webpack_require__(14), BuildGameObject: __webpack_require__(29), BuildGameObjectAnimation: __webpack_require__(178), GameObject: __webpack_require__(12), BitmapText: __webpack_require__(124), Blitter: __webpack_require__(179), Container: __webpack_require__(180), DynamicBitmapText: __webpack_require__(181), Graphics: __webpack_require__(182), Group: __webpack_require__(96), Image: __webpack_require__(82), Particles: __webpack_require__(717), PathFollower: __webpack_require__(353), RenderTexture: __webpack_require__(186), RetroFont: __webpack_require__(726), Sprite: __webpack_require__(50), Text: __webpack_require__(187), TileSprite: __webpack_require__(188), Zone: __webpack_require__(107), Shape: __webpack_require__(30), Arc: __webpack_require__(356), Curve: __webpack_require__(357), Ellipse: __webpack_require__(358), Grid: __webpack_require__(359), IsoBox: __webpack_require__(360), IsoTriangle: __webpack_require__(361), Line: __webpack_require__(362), Polygon: __webpack_require__(363), Rectangle: __webpack_require__(368), Star: __webpack_require__(369), Triangle: __webpack_require__(370), Factories: { Blitter: __webpack_require__(771), Container: __webpack_require__(772), DynamicBitmapText: __webpack_require__(773), Graphics: __webpack_require__(774), Group: __webpack_require__(775), Image: __webpack_require__(776), Particles: __webpack_require__(777), PathFollower: __webpack_require__(778), RenderTexture: __webpack_require__(779), Sprite: __webpack_require__(780), StaticBitmapText: __webpack_require__(781), Text: __webpack_require__(782), TileSprite: __webpack_require__(783), Zone: __webpack_require__(784), Arc: __webpack_require__(785), Curve: __webpack_require__(786), Ellipse: __webpack_require__(787), Grid: __webpack_require__(788), IsoBox: __webpack_require__(789), IsoTriangle: __webpack_require__(790), Line: __webpack_require__(791), Polygon: __webpack_require__(792), Rectangle: __webpack_require__(793), Star: __webpack_require__(794), Triangle: __webpack_require__(795) }, Creators: { Blitter: __webpack_require__(796), Container: __webpack_require__(797), DynamicBitmapText: __webpack_require__(798), Graphics: __webpack_require__(799), Group: __webpack_require__(800), Image: __webpack_require__(801), Particles: __webpack_require__(802), RenderTexture: __webpack_require__(803), Sprite: __webpack_require__(804), StaticBitmapText: __webpack_require__(805), Text: __webpack_require__(806), TileSprite: __webpack_require__(807), Zone: __webpack_require__(808) } }; if (typeof EXPERIMENTAL) { GameObjects.DOMElement = __webpack_require__(373); GameObjects.Factories.DOMElement = __webpack_require__(811) } if (true) { GameObjects.Mesh = __webpack_require__(126); GameObjects.Quad = __webpack_require__(191); GameObjects.Factories.Mesh = __webpack_require__(815); GameObjects.Factories.Quad = __webpack_require__(816); GameObjects.Creators.Mesh = __webpack_require__(817); GameObjects.Creators.Quad = __webpack_require__(818); GameObjects.Light = __webpack_require__(375); __webpack_require__(376); __webpack_require__(819) } module.exports = GameObjects }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var List = __webpack_require__(121); var PluginCache = __webpack_require__(15); var StableSort = __webpack_require__(123); var DisplayList = new Class({ Extends: List, initialize: function DisplayList(scene) { List.call(this, scene); this.sortChildrenFlag = false; this.scene = scene; this.systems = scene.sys; scene.sys.events.once("boot", this.boot, this); scene.sys.events.on("start", this.start, this) }, boot: function() { this.systems.events.once("destroy", this.destroy, this) }, start: function() { this.systems.events.once("shutdown", this.shutdown, this) }, queueDepthSort: function() { this.sortChildrenFlag = true }, depthSort: function() { if (this.sortChildrenFlag) { StableSort.inplace(this.list, this.sortByDepth); this.sortChildrenFlag = false } }, sortByDepth: function(childA, childB) { return childA._depth - childB._depth }, sortGameObjects: function(gameObjects) { if (gameObjects === undefined) { gameObjects = this.list } this.scene.sys.depthSort(); return gameObjects.sort(this.sortIndexHandler.bind(this)) }, getTopGameObject: function(gameObjects) { this.sortGameObjects(gameObjects); return gameObjects[gameObjects.length - 1] }, getChildren: function() { return this.list }, shutdown: function() { var i = this.list.length; while (i--) { this.list[i].destroy(true) } this.list.length = 0; this.systems.events.off("shutdown", this.shutdown, this) }, destroy: function() { this.shutdown(); this.scene.sys.events.off("start", this.start, this); this.scene = null; this.systems = null } }); PluginCache.register("DisplayList", DisplayList, "displayList"); module.exports = DisplayList }, function(module, exports, __webpack_require__) { module.exports = { CheckMatrix: __webpack_require__(176), MatrixToString: __webpack_require__(667), ReverseColumns: __webpack_require__(668), ReverseRows: __webpack_require__(669), Rotate180: __webpack_require__(670), RotateLeft: __webpack_require__(671), RotateMatrix: __webpack_require__(122), RotateRight: __webpack_require__(672), TransposeMatrix: __webpack_require__(335) } }, function(module, exports, __webpack_require__) { var Pad = __webpack_require__(158); var CheckMatrix = __webpack_require__(176); var MatrixToString = function(matrix) { var str = ""; if (!CheckMatrix(matrix)) { return str } for (var r = 0; r < matrix.length; r++) { for (var c = 0; c < matrix[r].length; c++) { var cell = matrix[r][c].toString(); if (cell !== "undefined") { str += Pad(cell, 2) } else { str += "?" } if (c < matrix[r].length - 1) { str += " |" } } if (r < matrix.length - 1) { str += "\n"; for (var i = 0; i < matrix[r].length; i++) { str += "---"; if (i < matrix[r].length - 1) { str += "+" } } str += "\n" } } return str }; module.exports = MatrixToString }, function(module, exports) { var ReverseColumns = function(matrix) { for (var i = 0; i < matrix.length; i++) { matrix[i].reverse() } return matrix }; module.exports = ReverseColumns }, function(module, exports) { var ReverseRows = function(matrix) { return matrix.reverse() }; module.exports = ReverseRows }, function(module, exports, __webpack_require__) { var RotateMatrix = __webpack_require__(122); var Rotate180 = function(matrix) { return RotateMatrix(matrix, 180) }; module.exports = Rotate180 }, function(module, exports, __webpack_require__) { var RotateMatrix = __webpack_require__(122); var RotateLeft = function(matrix) { return RotateMatrix(matrix, 90) }; module.exports = RotateLeft }, function(module, exports, __webpack_require__) { var RotateMatrix = __webpack_require__(122); var RotateRight = function(matrix) { return RotateMatrix(matrix, -90) }; module.exports = RotateRight }, function(module, exports) { var Add = function(array, item, limit, callback, context) { if (context === undefined) { context = array } if (limit > 0) { var remaining = limit - array.length; if (remaining <= 0) { return null } } if (!Array.isArray(item)) { if (array.indexOf(item) === -1) { array.push(item); if (callback) { callback.call(context, item) } return item } else { return null } } var itemLength = item.length - 1; while (itemLength >= 0) { if (array.indexOf(item[itemLength]) !== -1) { item.pop() } itemLength-- } itemLength = item.length; if (itemLength === 0) { return null } if (limit > 0 && itemLength > remaining) { item.splice(remaining); itemLength = remaining } for (var i = 0; i < itemLength; i++) { var entry = item[i]; array.push(entry); if (callback) { callback.call(context, entry) } } return item }; module.exports = Add }, function(module, exports) { var AddAt = function(array, item, index, limit, callback, context) { if (index === undefined) { index = 0 } if (context === undefined) { context = array } if (limit > 0) { var remaining = limit - array.length; if (remaining <= 0) { return null } } if (!Array.isArray(item)) { if (array.indexOf(item) === -1) { array.splice(index, 0, item); if (callback) { callback.call(context, item) } return item } else { return null } } var itemLength = item.length - 1; while (itemLength >= 0) { if (array.indexOf(item[itemLength]) !== -1) { item.pop() } itemLength-- } itemLength = item.length; if (itemLength === 0) { return null } if (limit > 0 && itemLength > remaining) { item.splice(remaining); itemLength = remaining } for (var i = itemLength - 1; i >= 0; i--) { var entry = item[i]; array.splice(index, 0, entry); if (callback) { callback.call(context, entry) } } return item }; module.exports = AddAt }, function(module, exports) { var BringToTop = function(array, item) { var currentIndex = array.indexOf(item); if (currentIndex !== -1 && currentIndex < array.length) { array.splice(currentIndex, 1); array.push(item) } return item }; module.exports = BringToTop }, function(module, exports, __webpack_require__) { var SafeRange = __webpack_require__(65); var CountAllMatching = function(array, property, value, startIndex, endIndex) { if (startIndex === undefined) { startIndex = 0 } if (endIndex === undefined) { endIndex = array.length } var total = 0; if (SafeRange(array, startIndex, endIndex)) { for (var i = startIndex; i < endIndex; i++) { var child = array[i]; if (child[property] === value) { total++ } } } return total }; module.exports = CountAllMatching }, function(module, exports) { var Each = function(array, callback, context) { var i; var args = [null]; for (i = 3; i < arguments.length; i++) { args.push(arguments[i]) } for (i = 0; i < array.length; i++) { args[0] = array[i]; callback.apply(context, args) } return array }; module.exports = Each }, function(module, exports, __webpack_require__) { var SafeRange = __webpack_require__(65); var EachInRange = function(array, callback, context, startIndex, endIndex) { if (startIndex === undefined) { startIndex = 0 } if (endIndex === undefined) { endIndex = array.length } if (SafeRange(array, startIndex, endIndex)) { var i; var args = [null]; for (i = 5; i < arguments.length; i++) { args.push(arguments[i]) } for (i = startIndex; i < endIndex; i++) { args[0] = array[i]; callback.apply(context, args) } } return array }; module.exports = EachInRange }, function(module, exports, __webpack_require__) { var SafeRange = __webpack_require__(65); var GetAll = function(array, property, value, startIndex, endIndex) { if (startIndex === undefined) { startIndex = 0 } if (endIndex === undefined) { endIndex = array.length } var output = []; if (SafeRange(array, startIndex, endIndex)) { for (var i = startIndex; i < endIndex; i++) { var child = array[i]; if (!property || property && value === undefined && child.hasOwnProperty(property) || property && value !== undefined && child[property] === value) { output.push(child) } } } return output }; module.exports = GetAll }, function(module, exports, __webpack_require__) { var SafeRange = __webpack_require__(65); var GetFirst = function(array, property, value, startIndex, endIndex) { if (startIndex === undefined) { startIndex = 0 } if (endIndex === undefined) { endIndex = array.length } if (SafeRange(array, startIndex, endIndex)) { for (var i = startIndex; i < endIndex; i++) { var child = array[i]; if (!property || property && value === undefined && child.hasOwnProperty(property) || property && value !== undefined && child[property] === value) { return child } } } return null }; module.exports = GetFirst }, function(module, exports) { var MoveDown = function(array, item) { var currentIndex = array.indexOf(item); if (currentIndex > 0) { var item2 = array[currentIndex - 1]; var index2 = array.indexOf(item2); array[currentIndex] = item2; array[index2] = item } return array }; module.exports = MoveDown }, function(module, exports) { var MoveTo = function(array, item, index) { var currentIndex = array.indexOf(item); if (currentIndex === -1 || index < 0 || index >= array.length) { throw new Error("Supplied index out of bounds") } if (currentIndex !== index) { array.splice(currentIndex, 1); array.splice(index, 0, item) } return item }; module.exports = MoveTo }, function(module, exports) { var MoveUp = function(array, item) { var currentIndex = array.indexOf(item); if (currentIndex !== -1 && currentIndex < array.length - 2) { var item2 = array[currentIndex + 1]; var index2 = array.indexOf(item2); array[currentIndex] = item2; array[index2] = item } return array }; module.exports = MoveUp }, function(module, exports) { var NumberArray = function(start, end, prefix, suffix) { var result = []; for (var i = start; i <= end; i++) { if (prefix || suffix) { var key = prefix ? prefix + i.toString() : i.toString(); if (suffix) { key = key.concat(suffix) } result.push(key) } else { result.push(i) } } return result }; module.exports = NumberArray }, function(module, exports, __webpack_require__) { var RoundAwayFromZero = __webpack_require__(336); var NumberArrayStep = function(start, end, step) { if (start === undefined) { start = 0 } if (end === undefined) { end = null } if (step === undefined) { step = 1 } if (end === null) { end = start; start = 0 } var result = []; var total = Math.max(RoundAwayFromZero((end - start) / (step || 1)), 0); for (var i = 0; i < total; i++) { result.push(start); start += step } return result }; module.exports = NumberArrayStep }, function(module, exports, __webpack_require__) { var SpliceOne = __webpack_require__(93); var RemoveAt = function(array, index, callback, context) { if (context === undefined) { context = array } if (index < 0 || index > array.length - 1) { throw new Error("Index out of bounds") } var item = SpliceOne(array, index); if (callback) { callback.call(context, item) } return item }; module.exports = RemoveAt }, function(module, exports, __webpack_require__) { var SafeRange = __webpack_require__(65); var RemoveBetween = function(array, startIndex, endIndex, callback, context) { if (startIndex === undefined) { startIndex = 0 } if (endIndex === undefined) { endIndex = array.length } if (context === undefined) { context = array } if (SafeRange(array, startIndex, endIndex)) { var size = endIndex - startIndex; var removed = array.splice(startIndex, size); if (callback) { for (var i = 0; i < removed.length; i++) { var entry = removed[i]; callback.call(context, entry) } } return removed } else { return [] } }; module.exports = RemoveBetween }, function(module, exports, __webpack_require__) { var SpliceOne = __webpack_require__(93); var RemoveRandomElement = function(array, start, length) { if (start === undefined) { start = 0 } if (length === undefined) { length = array.length } var randomIndex = start + Math.floor(Math.random() * length); return SpliceOne(array, randomIndex) }; module.exports = RemoveRandomElement }, function(module, exports) { var Replace = function(array, oldChild, newChild) { var index1 = array.indexOf(oldChild); var index2 = array.indexOf(newChild); if (index1 !== -1 && index2 === -1) { array[index1] = newChild; return true } else { return false } }; module.exports = Replace }, function(module, exports) { var SendToBack = function(array, item) { var currentIndex = array.indexOf(item); if (currentIndex !== -1 && currentIndex > 0) { array.splice(currentIndex, 1); array.unshift(item) } return item }; module.exports = SendToBack }, function(module, exports, __webpack_require__) { var SafeRange = __webpack_require__(65); var SetAll = function(array, property, value, startIndex, endIndex) { if (startIndex === undefined) { startIndex = 0 } if (endIndex === undefined) { endIndex = array.length } if (SafeRange(array, startIndex, endIndex)) { for (var i = startIndex; i < endIndex; i++) { var entry = array[i]; if (entry.hasOwnProperty(property)) { entry[property] = value } } } return array }; module.exports = SetAll }, function(module, exports) { var Swap = function(array, item1, item2) { if (item1 === item2) { return } var index1 = array.indexOf(item1); var index2 = array.indexOf(item2); if (index1 < 0 || index2 < 0) { throw new Error("Supplied items must be elements of the same array") } array[index1] = item2; array[index2] = item1; return array }; module.exports = Swap }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var PluginCache = __webpack_require__(15); var UpdateList = new Class({ initialize: function UpdateList(scene) { this.scene = scene; this.systems = scene.sys; this._list = []; this._pendingInsertion = []; this._pendingRemoval = []; scene.sys.events.once("boot", this.boot, this); scene.sys.events.on("start", this.start, this) }, boot: function() { this.systems.events.once("destroy", this.destroy, this) }, start: function() { var eventEmitter = this.systems.events; eventEmitter.on("preupdate", this.preUpdate, this); eventEmitter.on("update", this.update, this); eventEmitter.once("shutdown", this.shutdown, this) }, add: function(child) { if (this._list.indexOf(child) === -1 && this._pendingInsertion.indexOf(child) === -1) { this._pendingInsertion.push(child) } return child }, preUpdate: function() { var toRemove = this._pendingRemoval.length; var toInsert = this._pendingInsertion.length; if (toRemove === 0 && toInsert === 0) { return } var i; var gameObject; for (i = 0; i < toRemove; i++) { gameObject = this._pendingRemoval[i]; var index = this._list.indexOf(gameObject); if (index > -1) { this._list.splice(index, 1) } } this._list = this._list.concat(this._pendingInsertion.splice(0)); this._pendingRemoval.length = 0; this._pendingInsertion.length = 0 }, update: function(time, delta) { for (var i = 0; i < this._list.length; i++) { var gameObject = this._list[i]; if (gameObject.active) { gameObject.preUpdate.call(gameObject, time, delta) } } }, remove: function(child) { var index = this._list.indexOf(child); if (index !== -1) { this._list.splice(index, 1) } return child }, removeAll: function() { var i = this._list.length; while (i--) { this.remove(this._list[i]) } return this }, shutdown: function() { var i = this._list.length; while (i--) { this._list[i].destroy(true) } i = this._pendingRemoval.length; while (i--) { this._pendingRemoval[i].destroy(true) } i = this._pendingInsertion.length; while (i--) { this._pendingInsertion[i].destroy(true) } this._list.length = 0; this._pendingRemoval.length = 0; this._pendingInsertion.length = 0; var eventEmitter = this.systems.events; eventEmitter.off("preupdate", this.preUpdate, this); eventEmitter.off("update", this.update, this); eventEmitter.off("shutdown", this.shutdown, this) }, destroy: function() { this.shutdown(); this.scene.sys.events.off("start", this.start, this); this.scene = null; this.systems = null }, length: { get: function() { return this._list.length } } }); PluginCache.register("UpdateList", UpdateList, "updateList"); module.exports = UpdateList }, function(module, exports) { var GetBitmapTextSize = function(src, round, out) { if (out === undefined) { out = { local: { x: 0, y: 0, width: 0, height: 0 }, global: { x: 0, y: 0, width: 0, height: 0 }, lines: { shortest: 0, longest: 0, lengths: null } } } var text = src.text; var textLength = text.length; var bx = Number.MAX_VALUE; var by = Number.MAX_VALUE; var bw = 0; var bh = 0; var chars = src.fontData.chars; var lineHeight = src.fontData.lineHeight; var letterSpacing = src.letterSpacing; var xAdvance = 0; var yAdvance = 0; var charCode = 0; var glyph = null; var x = 0; var y = 0; var scale = src.fontSize / src.fontData.size; var sx = scale * src.scaleX; var sy = scale * src.scaleY; var lastGlyph = null; var lastCharCode = 0; var lineWidths = []; var shortestLine = Number.MAX_VALUE; var longestLine = 0; var currentLine = 0; var currentLineWidth = 0; for (var i = 0; i < textLength; i++) { charCode = text.charCodeAt(i); if (charCode === 10) { xAdvance = 0; yAdvance += lineHeight; lastGlyph = null; lineWidths[currentLine] = currentLineWidth; if (currentLineWidth > longestLine) { longestLine = currentLineWidth } if (currentLineWidth < shortestLine) { shortestLine = currentLineWidth } currentLine++; currentLineWidth = 0; continue } glyph = chars[charCode]; if (!glyph) { continue } x = xAdvance; y = yAdvance; if (lastGlyph !== null) { var kerningOffset = glyph.kerning[lastCharCode]; x += kerningOffset !== undefined ? kerningOffset : 0 } if (bx > x) { bx = x } if (by > y) { by = y } var gw = x + glyph.xAdvance; var gh = y + lineHeight; if (bw < gw) { bw = gw } if (bh < gh) { bh = gh } xAdvance += glyph.xAdvance + letterSpacing; lastGlyph = glyph; lastCharCode = charCode; currentLineWidth = gw * scale } lineWidths[currentLine] = currentLineWidth; if (currentLineWidth > longestLine) { longestLine = currentLineWidth } if (currentLineWidth < shortestLine) { shortestLine = currentLineWidth } var local = out.local; var global = out.global; var lines = out.lines; local.x = bx * scale; local.y = by * scale; local.width = bw * scale; local.height = bh * scale; global.x = src.x - src.displayOriginX + bx * sx; global.y = src.y - src.displayOriginY + by * sy; global.width = bw * sx; global.height = bh * sy; lines.shortest = shortestLine; lines.longest = longestLine; lines.lengths = lineWidths; if (round) { local.x = Math.round(local.x); local.y = Math.round(local.y); local.width = Math.round(local.width); local.height = Math.round(local.height); global.x = Math.round(global.x); global.y = Math.round(global.y); global.width = Math.round(global.width); global.height = Math.round(global.height); lines.shortest = Math.round(shortestLine); lines.longest = Math.round(longestLine) } return out }; module.exports = GetBitmapTextSize }, function(module, exports, __webpack_require__) { var ParseXMLBitmapFont = __webpack_require__(339); var ParseFromAtlas = function(scene, fontName, textureKey, frameKey, xmlKey, xSpacing, ySpacing) { var frame = scene.sys.textures.getFrame(textureKey, frameKey); var xml = scene.sys.cache.xml.get(xmlKey); if (frame && xml) { var data = ParseXMLBitmapFont(xml, xSpacing, ySpacing, frame); scene.sys.cache.bitmapFont.add(fontName, { data: data, texture: textureKey, frame: frameKey }); return true } else { return false } }; module.exports = ParseFromAtlas }, function(module, exports, __webpack_require__) { var renderWebGL = __webpack_require__(2); var renderCanvas = __webpack_require__(2); if (true) { renderWebGL = __webpack_require__(697) } if (true) { renderCanvas = __webpack_require__(698) } module.exports = { renderWebGL: renderWebGL, renderCanvas: renderCanvas } }, function(module, exports, __webpack_require__) { var Utils = __webpack_require__(10); var BitmapTextWebGLRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix) { var text = src._text; var textLength = text.length; if (textLength === 0) { return } var pipeline = this.pipeline; renderer.setPipeline(pipeline, src); var camMatrix = pipeline._tempMatrix1; var spriteMatrix = pipeline._tempMatrix2; var calcMatrix = pipeline._tempMatrix3; spriteMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); camMatrix.copyFrom(camera.matrix); if (parentMatrix) { camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); spriteMatrix.e = src.x; spriteMatrix.f = src.y; camMatrix.multiply(spriteMatrix, calcMatrix) } else { spriteMatrix.e -= camera.scrollX * src.scrollFactorX; spriteMatrix.f -= camera.scrollY * src.scrollFactorY; camMatrix.multiply(spriteMatrix, calcMatrix) } var frame = src.frame; var texture = frame.glTexture; var textureX = frame.cutX; var textureY = frame.cutY; var textureWidth = texture.width; var textureHeight = texture.height; var tintEffect = src._isTinted && src.tintFill; var tintTL = Utils.getTintAppendFloatAlpha(src._tintTL, camera.alpha * src._alphaTL); var tintTR = Utils.getTintAppendFloatAlpha(src._tintTR, camera.alpha * src._alphaTR); var tintBL = Utils.getTintAppendFloatAlpha(src._tintBL, camera.alpha * src._alphaBL); var tintBR = Utils.getTintAppendFloatAlpha(src._tintBR, camera.alpha * src._alphaBR); pipeline.setTexture2D(texture, 0); var xAdvance = 0; var yAdvance = 0; var charCode = 0; var lastCharCode = 0; var letterSpacing = src._letterSpacing; var glyph; var glyphX = 0; var glyphY = 0; var glyphW = 0; var glyphH = 0; var lastGlyph; var fontData = src.fontData; var chars = fontData.chars; var lineHeight = fontData.lineHeight; var scale = src._fontSize / fontData.size; var align = src._align; var currentLine = 0; var lineOffsetX = 0; src.getTextBounds(false); var lineData = src._bounds.lines; if (align === 1) { lineOffsetX = (lineData.longest - lineData.lengths[0]) / 2 } else if (align === 2) { lineOffsetX = lineData.longest - lineData.lengths[0] } var roundPixels = camera.roundPixels; for (var i = 0; i < textLength; i++) { charCode = text.charCodeAt(i); if (charCode === 10) { currentLine++; if (align === 1) { lineOffsetX = (lineData.longest - lineData.lengths[currentLine]) / 2 } else if (align === 2) { lineOffsetX = lineData.longest - lineData.lengths[currentLine] } xAdvance = 0; yAdvance += lineHeight; lastGlyph = null; continue } glyph = chars[charCode]; if (!glyph) { continue } glyphX = textureX + glyph.x; glyphY = textureY + glyph.y; glyphW = glyph.width; glyphH = glyph.height; var x = glyph.xOffset + xAdvance; var y = glyph.yOffset + yAdvance; if (lastGlyph !== null) { var kerningOffset = glyph.kerning[lastCharCode]; x += kerningOffset !== undefined ? kerningOffset : 0 } xAdvance += glyph.xAdvance + letterSpacing; lastGlyph = glyph; lastCharCode = charCode; if (glyphW === 0 || glyphH === 0 || charCode === 32) { continue } x *= scale; y *= scale; x -= src.displayOriginX; y -= src.displayOriginY; x += lineOffsetX; var u0 = glyphX / textureWidth; var v0 = glyphY / textureHeight; var u1 = (glyphX + glyphW) / textureWidth; var v1 = (glyphY + glyphH) / textureHeight; var xw = x + glyphW * scale; var yh = y + glyphH * scale; var tx0 = calcMatrix.getX(x, y); var ty0 = calcMatrix.getY(x, y); var tx1 = calcMatrix.getX(x, yh); var ty1 = calcMatrix.getY(x, yh); var tx2 = calcMatrix.getX(xw, yh); var ty2 = calcMatrix.getY(xw, yh); var tx3 = calcMatrix.getX(xw, y); var ty3 = calcMatrix.getY(xw, y); if (roundPixels) { tx0 |= 0; ty0 |= 0; tx1 |= 0; ty1 |= 0; tx2 |= 0; ty2 |= 0; tx3 |= 0; ty3 |= 0 } pipeline.batchQuad(tx0, ty0, tx1, ty1, tx2, ty2, tx3, ty3, u0, v0, u1, v1, tintTL, tintTR, tintBL, tintBR, tintEffect) } }; module.exports = BitmapTextWebGLRenderer }, function(module, exports, __webpack_require__) { var SetTransform = __webpack_require__(24); var BitmapTextCanvasRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix) { var text = src._text; var textLength = text.length; var ctx = renderer.currentContext; if (textLength === 0 || !SetTransform(renderer, ctx, src, camera, parentMatrix)) { return } var textureFrame = src.frame; var chars = src.fontData.chars; var lineHeight = src.fontData.lineHeight; var letterSpacing = src._letterSpacing; var xAdvance = 0; var yAdvance = 0; var charCode = 0; var glyph = null; var glyphX = 0; var glyphY = 0; var glyphW = 0; var glyphH = 0; var x = 0; var y = 0; var lastGlyph = null; var lastCharCode = 0; var image = src.frame.source.image; var textureX = textureFrame.cutX; var textureY = textureFrame.cutY; var scale = src._fontSize / src.fontData.size; var align = src._align; var currentLine = 0; var lineOffsetX = 0; src.getTextBounds(false); var lineData = src._bounds.lines; if (align === 1) { lineOffsetX = (lineData.longest - lineData.lengths[0]) / 2 } else if (align === 2) { lineOffsetX = lineData.longest - lineData.lengths[0] } ctx.translate(-src.displayOriginX, -src.displayOriginY); var roundPixels = camera.roundPixels; for (var i = 0; i < textLength; i++) { charCode = text.charCodeAt(i); if (charCode === 10) { currentLine++; if (align === 1) { lineOffsetX = (lineData.longest - lineData.lengths[currentLine]) / 2 } else if (align === 2) { lineOffsetX = lineData.longest - lineData.lengths[currentLine] } xAdvance = 0; yAdvance += lineHeight; lastGlyph = null; continue } glyph = chars[charCode]; if (!glyph) { continue } glyphX = textureX + glyph.x; glyphY = textureY + glyph.y; glyphW = glyph.width; glyphH = glyph.height; x = glyph.xOffset + xAdvance; y = glyph.yOffset + yAdvance; if (lastGlyph !== null) { var kerningOffset = glyph.kerning[lastCharCode]; x += kerningOffset !== undefined ? kerningOffset : 0 } x *= scale; y *= scale; x += lineOffsetX; xAdvance += glyph.xAdvance + letterSpacing; lastGlyph = glyph; lastCharCode = charCode; if (glyphW === 0 || glyphH === 0 || charCode === 32) { continue } if (roundPixels) { x |= 0; y |= 0 } ctx.save(); ctx.translate(x, y); ctx.scale(scale, scale); ctx.drawImage(image, glyphX, glyphY, glyphW, glyphH, 0, 0, glyphW, glyphH); ctx.restore() } ctx.restore() }; module.exports = BitmapTextCanvasRenderer }, function(module, exports, __webpack_require__) { var renderWebGL = __webpack_require__(2); var renderCanvas = __webpack_require__(2); if (true) { renderWebGL = __webpack_require__(700) } if (true) { renderCanvas = __webpack_require__(701) } module.exports = { renderWebGL: renderWebGL, renderCanvas: renderCanvas } }, function(module, exports, __webpack_require__) { var Utils = __webpack_require__(10); var BlitterWebGLRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix) { var list = src.getRenderList(); if (list.length === 0) { return } var pipeline = this.pipeline; renderer.setPipeline(pipeline, src); var cameraScrollX = camera.scrollX * src.scrollFactorX; var cameraScrollY = camera.scrollY * src.scrollFactorY; var calcMatrix = pipeline._tempMatrix1; calcMatrix.copyFrom(camera.matrix); if (parentMatrix) { calcMatrix.multiplyWithOffset(parentMatrix, -cameraScrollX, -cameraScrollY); cameraScrollX = 0; cameraScrollY = 0 } var blitterX = src.x - cameraScrollX; var blitterY = src.y - cameraScrollY; var prevTextureSourceIndex = -1; var tintEffect = false; var alpha = camera.alpha * src.alpha; var roundPixels = camera.roundPixels; for (var index = 0; index < list.length; index++) { var bob = list[index]; var frame = bob.frame; var bobAlpha = bob.alpha * alpha; if (bobAlpha === 0) { continue } var width = frame.width; var height = frame.height; var x = blitterX + bob.x + frame.x; var y = blitterY + bob.y + frame.y; if (bob.flipX) { width *= -1; x += frame.width } if (bob.flipY) { height *= -1; y += frame.height } var xw = x + width; var yh = y + height; var tx0 = calcMatrix.getX(x, y); var ty0 = calcMatrix.getY(x, y); var tx1 = calcMatrix.getX(xw, yh); var ty1 = calcMatrix.getY(xw, yh); var tint = Utils.getTintAppendFloatAlpha(16777215, bobAlpha); if (frame.sourceIndex !== prevTextureSourceIndex) { pipeline.setTexture2D(frame.glTexture, 0); prevTextureSourceIndex = frame.sourceIndex } if (roundPixels) { tx0 |= 0; ty0 |= 0; tx1 |= 0; ty1 |= 0 } if (pipeline.batchQuad(tx0, ty0, tx0, ty1, tx1, ty1, tx1, ty0, frame.u0, frame.v0, frame.u1, frame.v1, tint, tint, tint, tint, tintEffect)) { prevTextureSourceIndex = -1 } } }; module.exports = BlitterWebGLRenderer }, function(module, exports) { var BlitterCanvasRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix) { var list = src.getRenderList(); if (list.length === 0) { return } var ctx = renderer.currentContext; var alpha = camera.alpha * src.alpha; if (alpha === 0) { return } ctx.globalCompositeOperation = renderer.blendModes[src.blendMode]; var cameraScrollX = src.x - camera.scrollX * src.scrollFactorX; var cameraScrollY = src.y - camera.scrollY * src.scrollFactorY; ctx.save(); if (parentMatrix) { parentMatrix.copyToContext(ctx) } var roundPixels = camera.roundPixels; for (var i = 0; i < list.length; i++) { var bob = list[i]; var flip = bob.flipX || bob.flipY; var frame = bob.frame; var cd = frame.canvasData; var dx = frame.x; var dy = frame.y; var fx = 1; var fy = 1; var bobAlpha = bob.alpha * alpha; if (bobAlpha === 0) { continue } ctx.globalAlpha = bobAlpha; if (!flip) { if (roundPixels) { dx |= 0; dy |= 0 } ctx.drawImage(frame.source.image, cd.x, cd.y, cd.width, cd.height, dx + bob.x + cameraScrollX, dy + bob.y + cameraScrollY, cd.width, cd.height) } else { if (bob.flipX) { fx = -1; dx -= cd.width } if (bob.flipY) { fy = -1; dy -= cd.height } ctx.save(); ctx.translate(bob.x + cameraScrollX, bob.y + cameraScrollY); ctx.scale(fx, fy); ctx.drawImage(frame.source.image, cd.x, cd.y, cd.width, cd.height, dx, dy, cd.width, cd.height); ctx.restore() } } ctx.restore() }; module.exports = BlitterCanvasRenderer }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Bob = new Class({ initialize: function Bob(blitter, x, y, frame, visible) { this.parent = blitter; this.x = x; this.y = y; this.frame = frame; this.data = {}; this._visible = visible; this._alpha = 1; this.flipX = false; this.flipY = false }, setFrame: function(frame) { if (frame === undefined) { this.frame = this.parent.frame } else { this.frame = this.parent.texture.get(frame) } return this }, resetFlip: function() { this.flipX = false; this.flipY = false; return this }, reset: function(x, y, frame) { this.x = x; this.y = y; this.flipX = false; this.flipY = false; this._alpha = 1; this._visible = true; this.parent.dirty = true; if (frame) { this.setFrame(frame) } return this }, setFlipX: function(value) { this.flipX = value; return this }, setFlipY: function(value) { this.flipY = value; return this }, setFlip: function(x, y) { this.flipX = x; this.flipY = y; return this }, setVisible: function(value) { this.visible = value; return this }, setAlpha: function(value) { this.alpha = value; return this }, destroy: function() { this.parent.dirty = true; this.parent.children.remove(this); this.parent = undefined; this.frame = undefined; this.data = undefined }, visible: { get: function() { return this._visible }, set: function(value) { this._visible = value; this.parent.dirty = true } }, alpha: { get: function() { return this._alpha }, set: function(value) { this._alpha = value; this.parent.dirty = true } } }); module.exports = Bob }, function(module, exports, __webpack_require__) { var renderWebGL = __webpack_require__(2); var renderCanvas = __webpack_require__(2); if (true) { renderWebGL = __webpack_require__(704) } if (true) { renderCanvas = __webpack_require__(705) } module.exports = { renderWebGL: renderWebGL, renderCanvas: renderCanvas } }, function(module, exports) { var ContainerWebGLRenderer = function(renderer, container, interpolationPercentage, camera, parentMatrix) { var children = container.list; if (children.length === 0) { return } var transformMatrix = container.localTransform; if (parentMatrix) { transformMatrix.loadIdentity(); transformMatrix.multiply(parentMatrix); transformMatrix.translate(container.x, container.y); transformMatrix.rotate(container.rotation); transformMatrix.scale(container.scaleX, container.scaleY) } else { transformMatrix.applyITRS(container.x, container.y, container.rotation, container.scaleX, container.scaleY) } var containerHasBlendMode = container.blendMode !== -1; if (!containerHasBlendMode) { renderer.setBlendMode(0) } var alpha = container._alpha; var scrollFactorX = container.scrollFactorX; var scrollFactorY = container.scrollFactorY; for (var i = 0; i < children.length; i++) { var child = children[i]; if (!child.willRender(camera)) { continue } var childAlpha = child._alpha; var childScrollFactorX = child.scrollFactorX; var childScrollFactorY = child.scrollFactorY; if (!containerHasBlendMode && child.blendMode !== renderer.currentBlendMode) { renderer.setBlendMode(child.blendMode) } child.setScrollFactor(childScrollFactorX * scrollFactorX, childScrollFactorY * scrollFactorY); child.setAlpha(childAlpha * alpha); child.renderWebGL(renderer, child, interpolationPercentage, camera, transformMatrix); child.setAlpha(childAlpha); child.setScrollFactor(childScrollFactorX, childScrollFactorY) } }; module.exports = ContainerWebGLRenderer }, function(module, exports) { var ContainerCanvasRenderer = function(renderer, container, interpolationPercentage, camera, parentMatrix) { var children = container.list; if (children.length === 0) { return } var transformMatrix = container.localTransform; if (parentMatrix) { transformMatrix.loadIdentity(); transformMatrix.multiply(parentMatrix); transformMatrix.translate(container.x, container.y); transformMatrix.rotate(container.rotation); transformMatrix.scale(container.scaleX, container.scaleY) } else { transformMatrix.applyITRS(container.x, container.y, container.rotation, container.scaleX, container.scaleY) } var containerHasBlendMode = container.blendMode !== -1; if (!containerHasBlendMode) { renderer.setBlendMode(0) } var alpha = container._alpha; var scrollFactorX = container.scrollFactorX; var scrollFactorY = container.scrollFactorY; for (var i = 0; i < children.length; i++) { var child = children[i]; if (!child.willRender(camera)) { continue } var childAlpha = child._alpha; var childBlendMode = child._blendMode; var childScrollFactorX = child.scrollFactorX; var childScrollFactorY = child.scrollFactorY; child.setScrollFactor(childScrollFactorX * scrollFactorX, childScrollFactorY * scrollFactorY); child.setAlpha(childAlpha * alpha); if (containerHasBlendMode) { child.setBlendMode(container._blendMode) } child.renderCanvas(renderer, child, interpolationPercentage, camera, transformMatrix); child.setAlpha(childAlpha); child.setScrollFactor(childScrollFactorX, childScrollFactorY); child.setBlendMode(childBlendMode) } }; module.exports = ContainerCanvasRenderer }, function(module, exports, __webpack_require__) { var renderWebGL = __webpack_require__(2); var renderCanvas = __webpack_require__(2); if (true) { renderWebGL = __webpack_require__(707) } if (true) { renderCanvas = __webpack_require__(708) } module.exports = { renderWebGL: renderWebGL, renderCanvas: renderCanvas } }, function(module, exports, __webpack_require__) { var Utils = __webpack_require__(10); var DynamicBitmapTextWebGLRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix) { var text = src.text; var textLength = text.length; if (textLength === 0) { return } var pipeline = this.pipeline; renderer.setPipeline(pipeline, src); var crop = src.cropWidth > 0 || src.cropHeight > 0; if (crop) { pipeline.flush(); renderer.pushScissor(src.x, src.y, src.cropWidth * src.scaleX, src.cropHeight * src.scaleY) } var camMatrix = pipeline._tempMatrix1; var spriteMatrix = pipeline._tempMatrix2; var calcMatrix = pipeline._tempMatrix3; var fontMatrix = pipeline._tempMatrix4; spriteMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); camMatrix.copyFrom(camera.matrix); if (parentMatrix) { camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); spriteMatrix.e = src.x; spriteMatrix.f = src.y; camMatrix.multiply(spriteMatrix, calcMatrix) } else { spriteMatrix.e -= camera.scrollX * src.scrollFactorX; spriteMatrix.f -= camera.scrollY * src.scrollFactorY; camMatrix.multiply(spriteMatrix, calcMatrix) } var frame = src.frame; var texture = frame.glTexture; var textureX = frame.cutX; var textureY = frame.cutY; var textureWidth = texture.width; var textureHeight = texture.height; var tintEffect = src._isTinted && src.tintFill; var tintTL = Utils.getTintAppendFloatAlpha(src._tintTL, camera.alpha * src._alphaTL); var tintTR = Utils.getTintAppendFloatAlpha(src._tintTR, camera.alpha * src._alphaTR); var tintBL = Utils.getTintAppendFloatAlpha(src._tintBL, camera.alpha * src._alphaBL); var tintBR = Utils.getTintAppendFloatAlpha(src._tintBR, camera.alpha * src._alphaBR); pipeline.setTexture2D(texture, 0); var xAdvance = 0; var yAdvance = 0; var charCode = 0; var lastCharCode = 0; var letterSpacing = src.letterSpacing; var glyph; var glyphX = 0; var glyphY = 0; var glyphW = 0; var glyphH = 0; var lastGlyph; var scrollX = src.scrollX; var scrollY = src.scrollY; var fontData = src.fontData; var chars = fontData.chars; var lineHeight = fontData.lineHeight; var scale = src.fontSize / fontData.size; var rotation = 0; var align = src._align; var currentLine = 0; var lineOffsetX = 0; src.getTextBounds(false); var lineData = src._bounds.lines; if (align === 1) { lineOffsetX = (lineData.longest - lineData.lengths[0]) / 2 } else if (align === 2) { lineOffsetX = lineData.longest - lineData.lengths[0] } var roundPixels = camera.roundPixels; var displayCallback = src.displayCallback; var callbackData = src.callbackData; for (var i = 0; i < textLength; i++) { charCode = text.charCodeAt(i); if (charCode === 10) { currentLine++; if (align === 1) { lineOffsetX = (lineData.longest - lineData.lengths[currentLine]) / 2 } else if (align === 2) { lineOffsetX = lineData.longest - lineData.lengths[currentLine] } xAdvance = 0; yAdvance += lineHeight; lastGlyph = null; continue } glyph = chars[charCode]; if (!glyph) { continue } glyphX = textureX + glyph.x; glyphY = textureY + glyph.y; glyphW = glyph.width; glyphH = glyph.height; var x = glyph.xOffset + xAdvance - scrollX; var y = glyph.yOffset + yAdvance - scrollY; if (lastGlyph !== null) { var kerningOffset = glyph.kerning[lastCharCode]; x += kerningOffset !== undefined ? kerningOffset : 0 } xAdvance += glyph.xAdvance + letterSpacing; lastGlyph = glyph; lastCharCode = charCode; if (glyphW === 0 || glyphH === 0 || charCode === 32) { continue } scale = src.fontSize / src.fontData.size; rotation = 0; if (displayCallback) { callbackData.color = 0; callbackData.tint.topLeft = tintTL; callbackData.tint.topRight = tintTR; callbackData.tint.bottomLeft = tintBL; callbackData.tint.bottomRight = tintBR; callbackData.index = i; callbackData.charCode = charCode; callbackData.x = x; callbackData.y = y; callbackData.scale = scale; callbackData.rotation = rotation; callbackData.data = glyph.data; var output = displayCallback(callbackData); x = output.x; y = output.y; scale = output.scale; rotation = output.rotation; if (output.color) { tintTL = output.color; tintTR = output.color; tintBL = output.color; tintBR = output.color } else { tintTL = output.tint.topLeft; tintTR = output.tint.topRight; tintBL = output.tint.bottomLeft; tintBR = output.tint.bottomRight } tintTL = Utils.getTintAppendFloatAlpha(tintTL, camera.alpha * src._alphaTL); tintTR = Utils.getTintAppendFloatAlpha(tintTR, camera.alpha * src._alphaTR); tintBL = Utils.getTintAppendFloatAlpha(tintBL, camera.alpha * src._alphaBL); tintBR = Utils.getTintAppendFloatAlpha(tintBR, camera.alpha * src._alphaBR) } x *= scale; y *= scale; x -= src.displayOriginX; y -= src.displayOriginY; x += lineOffsetX; fontMatrix.applyITRS(x, y, rotation, scale, scale); calcMatrix.multiply(fontMatrix, spriteMatrix); var u0 = glyphX / textureWidth; var v0 = glyphY / textureHeight; var u1 = (glyphX + glyphW) / textureWidth; var v1 = (glyphY + glyphH) / textureHeight; var xw = glyphW; var yh = glyphH; var tx0 = spriteMatrix.e; var ty0 = spriteMatrix.f; var tx1 = yh * spriteMatrix.c + spriteMatrix.e; var ty1 = yh * spriteMatrix.d + spriteMatrix.f; var tx2 = xw * spriteMatrix.a + yh * spriteMatrix.c + spriteMatrix.e; var ty2 = xw * spriteMatrix.b + yh * spriteMatrix.d + spriteMatrix.f; var tx3 = xw * spriteMatrix.a + spriteMatrix.e; var ty3 = xw * spriteMatrix.b + spriteMatrix.f; if (roundPixels) { tx0 |= 0; ty0 |= 0; tx1 |= 0; ty1 |= 0; tx2 |= 0; ty2 |= 0; tx3 |= 0; ty3 |= 0 } pipeline.batchQuad(tx0, ty0, tx1, ty1, tx2, ty2, tx3, ty3, u0, v0, u1, v1, tintTL, tintTR, tintBL, tintBR, tintEffect) } if (crop) { pipeline.flush(); renderer.popScissor() } }; module.exports = DynamicBitmapTextWebGLRenderer }, function(module, exports, __webpack_require__) { var SetTransform = __webpack_require__(24); var DynamicBitmapTextCanvasRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix) { var text = src.text; var textLength = text.length; var ctx = renderer.currentContext; if (textLength === 0 || !SetTransform(renderer, ctx, src, camera, parentMatrix)) { return } var textureFrame = src.frame; var displayCallback = src.displayCallback; var cameraScrollX = camera.scrollX * src.scrollFactorX; var cameraScrollY = camera.scrollY * src.scrollFactorY; var chars = src.fontData.chars; var lineHeight = src.fontData.lineHeight; var xAdvance = 0; var yAdvance = 0; var indexCount = 0; var charCode = 0; var glyph = null; var glyphX = 0; var glyphY = 0; var glyphW = 0; var glyphH = 0; var x = 0; var y = 0; var lastGlyph = null; var lastCharCode = 0; var image = src.frame.source.image; var textureX = textureFrame.cutX; var textureY = textureFrame.cutY; var rotation = 0; var scale = src.fontSize / src.fontData.size; if (src.cropWidth > 0 && src.cropHeight > 0) { ctx.save(); ctx.beginPath(); ctx.rect(0, 0, src.cropWidth, src.cropHeight); ctx.clip() } for (var index = 0; index < textLength; ++index) { scale = src.fontSize / src.fontData.size; rotation = 0; charCode = text.charCodeAt(index); if (charCode === 10) { xAdvance = 0; indexCount = 0; yAdvance += lineHeight; lastGlyph = null; continue } glyph = chars[charCode]; if (!glyph) { continue } glyphX = textureX + glyph.x; glyphY = textureY + glyph.y; glyphW = glyph.width; glyphH = glyph.height; x = indexCount + glyph.xOffset + xAdvance - src.scrollX; y = glyph.yOffset + yAdvance - src.scrollY; if (lastGlyph !== null) { var kerningOffset = glyph.kerning[lastCharCode]; x += kerningOffset !== undefined ? kerningOffset : 0 } if (displayCallback) { var output = displayCallback({ tint: { topLeft: 0, topRight: 0, bottomLeft: 0, bottomRight: 0 }, index: index, charCode: charCode, x: x, y: y, scale: scale, rotation: 0, data: glyph.data }); x = output.x; y = output.y; scale = output.scale; rotation = output.rotation } x *= scale; y *= scale; x -= cameraScrollX; y -= cameraScrollY; if (camera.roundPixels) { x |= 0; y |= 0 } ctx.save(); ctx.translate(x, y); ctx.rotate(rotation); ctx.scale(scale, scale); ctx.drawImage(image, glyphX, glyphY, glyphW, glyphH, 0, 0, glyphW, glyphH); ctx.restore(); xAdvance += glyph.xAdvance; indexCount += 1; lastGlyph = glyph; lastCharCode = charCode } if (src.cropWidth > 0 && src.cropHeight > 0) { ctx.restore() } ctx.restore() }; module.exports = DynamicBitmapTextCanvasRenderer }, function(module, exports, __webpack_require__) { var renderWebGL = __webpack_require__(2); var renderCanvas = __webpack_require__(2); if (true) { renderWebGL = __webpack_require__(710); renderCanvas = __webpack_require__(344) } if (true) { renderCanvas = __webpack_require__(344) } module.exports = { renderWebGL: renderWebGL, renderCanvas: renderCanvas } }, function(module, exports, __webpack_require__) { var Commands = __webpack_require__(183); var Utils = __webpack_require__(10); var Point = function(x, y, width) { this.x = x; this.y = y; this.width = width }; var Path = function(x, y, width) { this.points = []; this.pointsLength = 1; this.points[0] = new Point(x, y, width) }; var matrixStack = []; var GraphicsWebGLRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix) { if (src.commandBuffer.length === 0) { return } var pipeline = this.pipeline; var camMatrix = pipeline._tempMatrix1; var graphicsMatrix = pipeline._tempMatrix2; var currentMatrix = pipeline._tempMatrix4; renderer.setPipeline(pipeline); currentMatrix.loadIdentity(); graphicsMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); camMatrix.copyFrom(camera.matrix); if (parentMatrix) { camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); graphicsMatrix.e = src.x; graphicsMatrix.f = src.y; camMatrix.multiply(graphicsMatrix) } else { graphicsMatrix.e -= camera.scrollX * src.scrollFactorX; graphicsMatrix.f -= camera.scrollY * src.scrollFactorY; camMatrix.multiply(graphicsMatrix) } var commands = src.commandBuffer; var alpha = camera.alpha * src.alpha; var lineWidth = 1; var fillTint = pipeline.fillTint; var strokeTint = pipeline.strokeTint; var tx = 0; var ty = 0; var ta = 0; var iterStep = .01; var PI2 = Math.PI * 2; var cmd; var path = []; var pathIndex = 0; var pathOpen = false; var lastPath = null; var getTint = Utils.getTintAppendFloatAlphaAndSwap; var currentTexture = renderer.blankTexture.glTexture; for (var cmdIndex = 0; cmdIndex < commands.length; cmdIndex++) { cmd = commands[cmdIndex]; switch (cmd) { case Commands.BEGIN_PATH: path.length = 0; lastPath = null; pathOpen = true; break; case Commands.CLOSE_PATH: pathOpen = false; if (lastPath && lastPath.points.length) { lastPath.points.push(lastPath.points[0]) } break; case Commands.FILL_PATH: for (pathIndex = 0; pathIndex < path.length; pathIndex++) { pipeline.setTexture2D(currentTexture); pipeline.batchFillPath(path[pathIndex].points, currentMatrix, camMatrix) } break; case Commands.STROKE_PATH: for (pathIndex = 0; pathIndex < path.length; pathIndex++) { pipeline.setTexture2D(currentTexture); pipeline.batchStrokePath(path[pathIndex].points, lineWidth, pathOpen, currentMatrix, camMatrix) } break; case Commands.LINE_STYLE: lineWidth = commands[++cmdIndex]; var strokeColor = commands[++cmdIndex]; var strokeAlpha = commands[++cmdIndex] * alpha; var strokeTintColor = getTint(strokeColor, strokeAlpha); strokeTint.TL = strokeTintColor; strokeTint.TR = strokeTintColor; strokeTint.BL = strokeTintColor; strokeTint.BR = strokeTintColor; break; case Commands.FILL_STYLE: var fillColor = commands[++cmdIndex]; var fillAlpha = commands[++cmdIndex] * alpha; var fillTintColor = getTint(fillColor, fillAlpha); fillTint.TL = fillTintColor; fillTint.TR = fillTintColor; fillTint.BL = fillTintColor; fillTint.BR = fillTintColor; break; case Commands.GRADIENT_FILL_STYLE: var gradientFillAlpha = commands[++cmdIndex] * alpha; fillTint.TL = getTint(commands[++cmdIndex], gradientFillAlpha); fillTint.TR = getTint(commands[++cmdIndex], gradientFillAlpha); fillTint.BL = getTint(commands[++cmdIndex], gradientFillAlpha); fillTint.BR = getTint(commands[++cmdIndex], gradientFillAlpha); break; case Commands.GRADIENT_LINE_STYLE: lineWidth = commands[++cmdIndex]; var gradientLineAlpha = commands[++cmdIndex] * alpha; strokeTint.TL = getTint(commands[++cmdIndex], gradientLineAlpha); strokeTint.TR = getTint(commands[++cmdIndex], gradientLineAlpha); strokeTint.BL = getTint(commands[++cmdIndex], gradientLineAlpha); strokeTint.BR = getTint(commands[++cmdIndex], gradientLineAlpha); break; case Commands.ARC: var iteration = 0; var x = commands[++cmdIndex]; var y = commands[++cmdIndex]; var radius = commands[++cmdIndex]; var startAngle = commands[++cmdIndex]; var endAngle = commands[++cmdIndex]; var anticlockwise = commands[++cmdIndex]; var overshoot = commands[++cmdIndex]; endAngle -= startAngle; if (anticlockwise) { if (endAngle < -PI2) { endAngle = -PI2 } else if (endAngle > 0) { endAngle = -PI2 + endAngle % PI2 } } else if (endAngle > PI2) { endAngle = PI2 } else if (endAngle < 0) { endAngle = PI2 + endAngle % PI2 } if (lastPath === null) { lastPath = new Path(x + Math.cos(startAngle) * radius, y + Math.sin(startAngle) * radius, lineWidth); path.push(lastPath); iteration += iterStep } while (iteration < 1 + overshoot) { ta = endAngle * iteration + startAngle; tx = x + Math.cos(ta) * radius; ty = y + Math.sin(ta) * radius; lastPath.points.push(new Point(tx, ty, lineWidth)); iteration += iterStep } ta = endAngle + startAngle; tx = x + Math.cos(ta) * radius; ty = y + Math.sin(ta) * radius; lastPath.points.push(new Point(tx, ty, lineWidth)); break; case Commands.FILL_RECT: pipeline.setTexture2D(currentTexture); pipeline.batchFillRect(commands[++cmdIndex], commands[++cmdIndex], commands[++cmdIndex], commands[++cmdIndex], currentMatrix, camMatrix); break; case Commands.FILL_TRIANGLE: pipeline.setTexture2D(currentTexture); pipeline.batchFillTriangle(commands[++cmdIndex], commands[++cmdIndex], commands[++cmdIndex], commands[++cmdIndex], commands[++cmdIndex], commands[++cmdIndex], currentMatrix, camMatrix); break; case Commands.STROKE_TRIANGLE: pipeline.setTexture2D(currentTexture); pipeline.batchStrokeTriangle(commands[++cmdIndex], commands[++cmdIndex], commands[++cmdIndex], commands[++cmdIndex], commands[++cmdIndex], commands[++cmdIndex], lineWidth, currentMatrix, camMatrix); break; case Commands.LINE_TO: if (lastPath !== null) { lastPath.points.push(new Point(commands[++cmdIndex], commands[++cmdIndex], lineWidth)) } else { lastPath = new Path(commands[++cmdIndex], commands[++cmdIndex], lineWidth); path.push(lastPath) } break; case Commands.MOVE_TO: lastPath = new Path(commands[++cmdIndex], commands[++cmdIndex], lineWidth); path.push(lastPath); break; case Commands.SAVE: matrixStack.push(currentMatrix.copyToArray()); break; case Commands.RESTORE: currentMatrix.copyFromArray(matrixStack.pop()); break; case Commands.TRANSLATE: x = commands[++cmdIndex]; y = commands[++cmdIndex]; currentMatrix.translate(x, y); break; case Commands.SCALE: x = commands[++cmdIndex]; y = commands[++cmdIndex]; currentMatrix.scale(x, y); break; case Commands.ROTATE: currentMatrix.rotate(commands[++cmdIndex]); break; case Commands.SET_TEXTURE: var frame = commands[++cmdIndex]; var mode = commands[++cmdIndex]; pipeline.currentFrame = frame; pipeline.setTexture2D(frame.glTexture, 0); pipeline.tintEffect = mode; currentTexture = frame.glTexture; break; case Commands.CLEAR_TEXTURE: pipeline.currentFrame = renderer.blankTexture; pipeline.tintEffect = 2; currentTexture = renderer.blankTexture.glTexture; break } } }; module.exports = GraphicsWebGLRenderer }, function(module, exports, __webpack_require__) { var renderWebGL = __webpack_require__(2); var renderCanvas = __webpack_require__(2); if (true) { renderWebGL = __webpack_require__(712) } if (true) { renderCanvas = __webpack_require__(713) } module.exports = { renderWebGL: renderWebGL, renderCanvas: renderCanvas } }, function(module, exports) { var SpriteWebGLRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix) { this.pipeline.batchSprite(src, camera, parentMatrix) }; module.exports = SpriteWebGLRenderer }, function(module, exports) { var SpriteCanvasRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix) { renderer.batchSprite(src, src.frame, camera, parentMatrix) }; module.exports = SpriteCanvasRenderer }, function(module, exports, __webpack_require__) { var renderWebGL = __webpack_require__(2); var renderCanvas = __webpack_require__(2); if (true) { renderWebGL = __webpack_require__(715) } if (true) { renderCanvas = __webpack_require__(716) } module.exports = { renderWebGL: renderWebGL, renderCanvas: renderCanvas } }, function(module, exports) { var ImageWebGLRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix) { this.pipeline.batchSprite(src, camera, parentMatrix) }; module.exports = ImageWebGLRenderer }, function(module, exports) { var ImageCanvasRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix) { renderer.batchSprite(src, src.frame, camera, parentMatrix) }; module.exports = ImageCanvasRenderer }, function(module, exports, __webpack_require__) { module.exports = { GravityWell: __webpack_require__(345), Particle: __webpack_require__(346), ParticleEmitter: __webpack_require__(347), ParticleEmitterManager: __webpack_require__(185), Zones: __webpack_require__(722) } }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var FloatBetween = __webpack_require__(350); var GetEaseFunction = __webpack_require__(97); var GetFastValue = __webpack_require__(1); var Wrap = __webpack_require__(55); var EmitterOp = new Class({ initialize: function EmitterOp(config, key, defaultValue, emitOnly) { if (emitOnly === undefined) { emitOnly = false } this.propertyKey = key; this.propertyValue = defaultValue; this.defaultValue = defaultValue; this.steps = 0; this.counter = 0; this.start = 0; this.end = 0; this.ease; this.emitOnly = emitOnly; this.onEmit = this.defaultEmit; this.onUpdate = this.defaultUpdate; this.loadConfig(config) }, loadConfig: function(config, newKey) { if (config === undefined) { config = {} } if (newKey) { this.propertyKey = newKey } this.propertyValue = GetFastValue(config, this.propertyKey, this.defaultValue); this.setMethods(); if (this.emitOnly) { this.onUpdate = this.defaultUpdate } }, toJSON: function() { return this.propertyValue }, onChange: function(value) { this.propertyValue = value; return this.setMethods() }, setMethods: function() { var value = this.propertyValue; var t = typeof value; if (t === "number") { this.onEmit = this.staticValueEmit; this.onUpdate = this.staticValueUpdate } else if (Array.isArray(value)) { this.onEmit = this.randomStaticValueEmit } else if (t === "function") { if (this.emitOnly) { this.onEmit = value } else { this.onUpdate = value } } else if (t === "object" && (this.has(value, "random") || this.hasBoth(value, "start", "end") || this.hasBoth(value, "min", "max"))) { this.start = this.has(value, "start") ? value.start : value.min; this.end = this.has(value, "end") ? value.end : value.max; var isRandom = this.hasBoth(value, "min", "max") || this.has(value, "random"); if (isRandom) { var rnd = value.random; if (Array.isArray(rnd)) { this.start = rnd[0]; this.end = rnd[1] } this.onEmit = this.randomRangedValueEmit } if (this.has(value, "steps")) { this.steps = value.steps; this.counter = this.start; this.onEmit = this.steppedEmit } else { var easeType = this.has(value, "ease") ? value.ease : "Linear"; this.ease = GetEaseFunction(easeType); if (!isRandom) { this.onEmit = this.easedValueEmit } this.onUpdate = this.easeValueUpdate } } else if (t === "object" && this.hasEither(value, "onEmit", "onUpdate")) { if (this.has(value, "onEmit")) { this.onEmit = value.onEmit } if (this.has(value, "onUpdate")) { this.onUpdate = value.onUpdate } } return this }, has: function(object, key) { return object.hasOwnProperty(key) }, hasBoth: function(object, key1, key2) { return object.hasOwnProperty(key1) && object.hasOwnProperty(key2) }, hasEither: function(object, key1, key2) { return object.hasOwnProperty(key1) || object.hasOwnProperty(key2) }, defaultEmit: function(particle, key, value) { return value }, defaultUpdate: function(particle, key, t, value) { return value }, staticValueEmit: function() { return this.propertyValue }, staticValueUpdate: function() { return this.propertyValue }, randomStaticValueEmit: function() { var randomIndex = Math.floor(Math.random() * this.propertyValue.length); return this.propertyValue[randomIndex] }, randomRangedValueEmit: function(particle, key) { var value = FloatBetween(this.start, this.end); if (particle && particle.data[key]) { particle.data[key].min = value } return value }, steppedEmit: function() { var current = this.counter; var next = this.counter + (this.end - this.start) / this.steps; this.counter = Wrap(next, this.start, this.end); return current }, easedValueEmit: function(particle, key) { if (particle && particle.data[key]) { var data = particle.data[key]; data.min = this.start; data.max = this.end } return this.start }, easeValueUpdate: function(particle, key, t) { var data = particle.data[key]; return (data.max - data.min) * this.ease(t) + data.min } }); module.exports = EmitterOp }, function(module, exports, __webpack_require__) { var renderWebGL = __webpack_require__(2); var renderCanvas = __webpack_require__(2); if (true) { renderWebGL = __webpack_require__(720) } if (true) { renderCanvas = __webpack_require__(721) } module.exports = { renderWebGL: renderWebGL, renderCanvas: renderCanvas } }, function(module, exports, __webpack_require__) { var Utils = __webpack_require__(10); var ParticleManagerWebGLRenderer = function(renderer, emitterManager, interpolationPercentage, camera, parentMatrix) { var emitters = emitterManager.emitters.list; var emittersLength = emitters.length; if (emittersLength === 0) { return } var pipeline = this.pipeline; var camMatrix = pipeline._tempMatrix1.copyFrom(camera.matrix); var calcMatrix = pipeline._tempMatrix2; var particleMatrix = pipeline._tempMatrix3; var managerMatrix = pipeline._tempMatrix4.applyITRS(emitterManager.x, emitterManager.y, emitterManager.rotation, emitterManager.scaleX, emitterManager.scaleY); camMatrix.multiply(managerMatrix); renderer.setPipeline(pipeline); var roundPixels = camera.roundPixels; var texture = emitterManager.defaultFrame.glTexture; var getTint = Utils.getTintAppendFloatAlphaAndSwap; pipeline.setTexture2D(texture, 0); for (var e = 0; e < emittersLength; e++) { var emitter = emitters[e]; var particles = emitter.alive; var particleCount = particles.length; if (!emitter.visible || particleCount === 0) { continue } var scrollX = camera.scrollX * emitter.scrollFactorX; var scrollY = camera.scrollY * emitter.scrollFactorY; if (parentMatrix) { camMatrix.multiplyWithOffset(parentMatrix, -scrollX, -scrollY); scrollX = 0; scrollY = 0 } if (renderer.setBlendMode(emitter.blendMode)) { pipeline.setTexture2D(texture, 0) } var tintEffect = 0; for (var i = 0; i < particleCount; i++) { var particle = particles[i]; var alpha = particle.alpha * camera.alpha; if (alpha <= 0) { continue } var frame = particle.frame; var x = -frame.halfWidth; var y = -frame.halfHeight; var xw = x + frame.width; var yh = y + frame.height; particleMatrix.applyITRS(0, 0, particle.rotation, particle.scaleX, particle.scaleY); particleMatrix.e = particle.x - scrollX; particleMatrix.f = particle.y - scrollY; camMatrix.multiply(particleMatrix, calcMatrix); var tx0 = calcMatrix.getX(x, y); var ty0 = calcMatrix.getY(x, y); var tx1 = calcMatrix.getX(x, yh); var ty1 = calcMatrix.getY(x, yh); var tx2 = calcMatrix.getX(xw, yh); var ty2 = calcMatrix.getY(xw, yh); var tx3 = calcMatrix.getX(xw, y); var ty3 = calcMatrix.getY(xw, y); if (roundPixels) { tx0 |= 0; ty0 |= 0; tx1 |= 0; ty1 |= 0; tx2 |= 0; ty2 |= 0; tx3 |= 0; ty3 |= 0 } var tint = getTint(particle.tint, alpha); if (pipeline.batchQuad(tx0, ty0, tx1, ty1, tx2, ty2, tx3, ty3, frame.u0, frame.v0, frame.u1, frame.v1, tint, tint, tint, tint, tintEffect)) { pipeline.setTexture2D(texture, 0) } } } }; module.exports = ParticleManagerWebGLRenderer }, function(module, exports) { var ParticleManagerCanvasRenderer = function(renderer, emitterManager, interpolationPercentage, camera, parentMatrix) { var emitters = emitterManager.emitters.list; var emittersLength = emitters.length; if (emittersLength === 0) { return } var camMatrix = renderer._tempMatrix1.copyFrom(camera.matrix); var calcMatrix = renderer._tempMatrix2; var particleMatrix = renderer._tempMatrix3; var managerMatrix = renderer._tempMatrix4.applyITRS(emitterManager.x, emitterManager.y, emitterManager.rotation, emitterManager.scaleX, emitterManager.scaleY); camMatrix.multiply(managerMatrix); var roundPixels = camera.roundPixels; var ctx = renderer.currentContext; ctx.save(); for (var e = 0; e < emittersLength; e++) { var emitter = emitters[e]; var particles = emitter.alive; var particleCount = particles.length; if (!emitter.visible || particleCount === 0) { continue } var scrollX = camera.scrollX * emitter.scrollFactorX; var scrollY = camera.scrollY * emitter.scrollFactorY; if (parentMatrix) { camMatrix.multiplyWithOffset(parentMatrix, -scrollX, -scrollY); scrollX = 0; scrollY = 0 } ctx.globalCompositeOperation = renderer.blendModes[emitter.blendMode]; for (var i = 0; i < particleCount; i++) { var particle = particles[i]; var alpha = particle.alpha * camera.alpha; if (alpha <= 0) { continue } var frame = particle.frame; var cd = frame.canvasData; var x = -frame.halfWidth; var y = -frame.halfHeight; particleMatrix.applyITRS(0, 0, particle.rotation, particle.scaleX, particle.scaleY); particleMatrix.e = particle.x - scrollX; particleMatrix.f = particle.y - scrollY; camMatrix.multiply(particleMatrix, calcMatrix); ctx.globalAlpha = alpha; ctx.save(); calcMatrix.copyToContext(ctx); if (roundPixels) { x |= 0; y |= 0 } ctx.drawImage(frame.source.image, cd.x, cd.y, cd.width, cd.height, x, y, cd.width, cd.height); ctx.restore() } } ctx.restore() }; module.exports = ParticleManagerCanvasRenderer }, function(module, exports, __webpack_require__) { module.exports = { DeathZone: __webpack_require__(348), EdgeZone: __webpack_require__(349), RandomZone: __webpack_require__(352) } }, function(module, exports, __webpack_require__) { var renderWebGL = __webpack_require__(2); var renderCanvas = __webpack_require__(2); if (true) { renderWebGL = __webpack_require__(724) } if (true) { renderCanvas = __webpack_require__(725) } module.exports = { renderWebGL: renderWebGL, renderCanvas: renderCanvas } }, function(module, exports, __webpack_require__) { var Utils = __webpack_require__(10); var RenderTextureWebGLRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix) { var frame = src.frame; var width = frame.width; var height = frame.height; var getTint = Utils.getTintAppendFloatAlpha; this.pipeline.batchTexture(src, frame.glTexture, width, height, src.x, src.y, width, height, src.scaleX, src.scaleY, src.rotation, src.flipX, !src.flipY, src.scrollFactorX, src.scrollFactorY, src.displayOriginX, src.displayOriginY, 0, 0, width, height, getTint(src._tintTL, camera.alpha * src._alphaTL), getTint(src._tintTR, camera.alpha * src._alphaTR), getTint(src._tintBL, camera.alpha * src._alphaBL), getTint(src._tintBR, camera.alpha * src._alphaBR), src._isTinted && src.tintFill, 0, 0, camera, parentMatrix); renderer.setBlankTexture(true) }; module.exports = RenderTextureWebGLRenderer }, function(module, exports) { var RenderTextureCanvasRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix) { renderer.batchSprite(src, src.frame, camera, parentMatrix) }; module.exports = RenderTextureCanvasRenderer }, function(module, exports, __webpack_require__) { var RETRO_FONT_CONST = __webpack_require__(727); var Extend = __webpack_require__(19); var RetroFont = { Parse: __webpack_require__(728) }; RetroFont = Extend(false, RetroFont, RETRO_FONT_CONST); module.exports = RetroFont }, function(module, exports) { var RETRO_FONT_CONST = { TEXT_SET1: " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~", TEXT_SET2: " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ", TEXT_SET3: "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ", TEXT_SET4: "ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789", TEXT_SET5: "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789", TEXT_SET6: "ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789\"(),-.' ", TEXT_SET7: "AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW\")28FLRX-'39", TEXT_SET8: "0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ", TEXT_SET9: "ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'\"?!", TEXT_SET10: "ABCDEFGHIJKLMNOPQRSTUVWXYZ", TEXT_SET11: "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,\"-+!?()':;0123456789" }; module.exports = RETRO_FONT_CONST }, function(module, exports, __webpack_require__) { var GetValue = __webpack_require__(4); var ParseRetroFont = function(scene, config) { var w = config.width; var h = config.height; var cx = Math.floor(w / 2); var cy = Math.floor(h / 2); var letters = GetValue(config, "chars", ""); if (letters === "") { return } var key = GetValue(config, "image", ""); var offsetX = GetValue(config, "offset.x", 0); var offsetY = GetValue(config, "offset.y", 0); var spacingX = GetValue(config, "spacing.x", 0); var spacingY = GetValue(config, "spacing.y", 0); var lineSpacing = GetValue(config, "lineSpacing", 0); var charsPerRow = GetValue(config, "charsPerRow", null); if (charsPerRow === null) { charsPerRow = scene.sys.textures.getFrame(key).width / w; if (charsPerRow > letters.length) { charsPerRow = letters.length } } var x = offsetX; var y = offsetY; var data = { retroFont: true, font: key, size: w, lineHeight: h + lineSpacing, chars: {} }; var r = 0; for (var i = 0; i < letters.length; i++) { var charCode = letters.charCodeAt(i); data.chars[charCode] = { x: x, y: y, width: w, height: h, centerX: cx, centerY: cy, xOffset: 0, yOffset: 0, xAdvance: w, data: {}, kerning: {} }; r++; if (r === charsPerRow) { r = 0; x = offsetX; y += h + spacingY } else { x += w + spacingX } } var entry = { data: data, frame: null, texture: key }; return entry }; module.exports = ParseRetroFont }, function(module, exports) { var GetTextSize = function(text, size, lines) { var canvas = text.canvas; var context = text.context; var style = text.style; var lineWidths = []; var maxLineWidth = 0; var drawnLines = lines.length; if (style.maxLines > 0 && style.maxLines < lines.length) { drawnLines = style.maxLines } style.syncFont(canvas, context); for (var i = 0; i < drawnLines; i++) { var lineWidth = style.strokeThickness; lineWidth += context.measureText(lines[i]).width; if (style.wordWrap) { lineWidth -= context.measureText(" ").width } lineWidths[i] = Math.ceil(lineWidth); maxLineWidth = Math.max(maxLineWidth, lineWidths[i]) } var lineHeight = size.fontSize + style.strokeThickness; var height = lineHeight * drawnLines; var lineSpacing = text.lineSpacing; if (lines.length > 1) { height += lineSpacing * (lines.length - 1) } return { width: maxLineWidth, height: height, lines: drawnLines, lineWidths: lineWidths, lineSpacing: lineSpacing, lineHeight: lineHeight } }; module.exports = GetTextSize }, function(module, exports, __webpack_require__) { var renderWebGL = __webpack_require__(2); var renderCanvas = __webpack_require__(2); if (true) { renderWebGL = __webpack_require__(731) } if (true) { renderCanvas = __webpack_require__(732) } module.exports = { renderWebGL: renderWebGL, renderCanvas: renderCanvas } }, function(module, exports, __webpack_require__) { var Utils = __webpack_require__(10); var TextWebGLRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix) { if (src.text === "") { return } var frame = src.frame; var width = frame.width; var height = frame.height; var getTint = Utils.getTintAppendFloatAlpha; this.pipeline.batchTexture(src, frame.glTexture, width, height, src.x, src.y, width / src.style.resolution, height / src.style.resolution, src.scaleX, src.scaleY, src.rotation, src.flipX, src.flipY, src.scrollFactorX, src.scrollFactorY, src.displayOriginX, src.displayOriginY, 0, 0, width, height, getTint(src._tintTL, camera.alpha * src._alphaTL), getTint(src._tintTR, camera.alpha * src._alphaTR), getTint(src._tintBL, camera.alpha * src._alphaBL), getTint(src._tintBR, camera.alpha * src._alphaBR), src._isTinted && src.tintFill, 0, 0, camera, parentMatrix) }; module.exports = TextWebGLRenderer }, function(module, exports) { var TextCanvasRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix) { if (src.text !== "") { renderer.batchSprite(src, src.frame, camera, parentMatrix) } }; module.exports = TextCanvasRenderer }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var GetAdvancedValue = __webpack_require__(13); var GetValue = __webpack_require__(4); var MeasureText = __webpack_require__(734); var propertyMap = { fontFamily: ["fontFamily", "Courier"], fontSize: ["fontSize", "16px"], fontStyle: ["fontStyle", ""], backgroundColor: ["backgroundColor", null], color: ["color", "#fff"], stroke: ["stroke", "#fff"], strokeThickness: ["strokeThickness", 0], shadowOffsetX: ["shadow.offsetX", 0], shadowOffsetY: ["shadow.offsetY", 0], shadowColor: ["shadow.color", "#000"], shadowBlur: ["shadow.blur", 0], shadowStroke: ["shadow.stroke", false], shadowFill: ["shadow.fill", false], align: ["align", "left"], maxLines: ["maxLines", 0], fixedWidth: ["fixedWidth", 0], fixedHeight: ["fixedHeight", 0], resolution: ["resolution", 0], rtl: ["rtl", false], testString: ["testString", "|MÉqgy"], baselineX: ["baselineX", 1.2], baselineY: ["baselineY", 1.4], wordWrapWidth: ["wordWrap.width", null], wordWrapCallback: ["wordWrap.callback", null], wordWrapCallbackScope: ["wordWrap.callbackScope", null], wordWrapUseAdvanced: ["wordWrap.useAdvancedWrap", false] }; var TextStyle = new Class({ initialize: function TextStyle(text, style) { this.parent = text; this.fontFamily; this.fontSize; this.fontStyle; this.backgroundColor; this.color; this.stroke; this.strokeThickness; this.shadowOffsetX; this.shadowOffsetY; this.shadowColor; this.shadowBlur; this.shadowStroke; this.shadowFill; this.align; this.maxLines; this.fixedWidth; this.fixedHeight; this.resolution; this.rtl; this.testString; this.baselineX; this.baselineY; this._font; this.setStyle(style, false, true); var metrics = GetValue(style, "metrics", false); if (metrics) { this.metrics = { ascent: GetValue(metrics, "ascent", 0), descent: GetValue(metrics, "descent", 0), fontSize: GetValue(metrics, "fontSize", 0) } } else { this.metrics = MeasureText(this) } }, setStyle: function(style, updateText, setDefaults) { if (updateText === undefined) { updateText = true } if (setDefaults === undefined) { setDefaults = false } if (style && style.hasOwnProperty("fontSize") && typeof style.fontSize === "number") { style.fontSize = style.fontSize.toString() + "px" } for (var key in propertyMap) { var value = setDefaults ? propertyMap[key][1] : this[key]; if (key === "wordWrapCallback" || key === "wordWrapCallbackScope") { this[key] = GetValue(style, propertyMap[key][0], value) } else { this[key] = GetAdvancedValue(style, propertyMap[key][0], value) } } var font = GetValue(style, "font", null); if (font === null) { this._font = [this.fontStyle, this.fontSize, this.fontFamily].join(" ").trim() } else { this._font = font } var fill = GetValue(style, "fill", null); if (fill !== null) { this.color = fill } if (updateText) { return this.update(true) } else { return this.parent } }, syncFont: function(canvas, context) { context.font = this._font }, syncStyle: function(canvas, context) { context.textBaseline = "alphabetic"; context.fillStyle = this.color; context.strokeStyle = this.stroke; context.lineWidth = this.strokeThickness; context.lineCap = "round"; context.lineJoin = "round" }, syncShadow: function(context, enabled) { if (enabled) { context.shadowOffsetX = this.shadowOffsetX; context.shadowOffsetY = this.shadowOffsetY; context.shadowColor = this.shadowColor; context.shadowBlur = this.shadowBlur } else { context.shadowOffsetX = 0; context.shadowOffsetY = 0; context.shadowColor = 0; context.shadowBlur = 0 } }, update: function(recalculateMetrics) { if (recalculateMetrics) { this._font = [this.fontStyle, this.fontSize, this.fontFamily].join(" ").trim(); this.metrics = MeasureText(this) } return this.parent.updateText() }, setFont: function(font) { var fontFamily = font; var fontSize = ""; var fontStyle = ""; if (typeof font !== "string") { fontFamily = GetValue(font, "fontFamily", "Courier"); fontSize = GetValue(font, "fontSize", "16px"); fontStyle = GetValue(font, "fontStyle", "") } if (fontFamily !== this.fontFamily || fontSize !== this.fontSize || fontStyle !== this.fontStyle) { this.fontFamily = fontFamily; this.fontSize = fontSize; this.fontStyle = fontStyle; this.update(true) } return this.parent }, setFontFamily: function(family) { if (this.fontFamily !== family) { this.fontFamily = family; this.update(true) } return this.parent }, setFontStyle: function(style) { if (this.fontStyle !== style) { this.fontStyle = style; this.update(true) } return this.parent }, setFontSize: function(size) { if (typeof size === "number") { size = size.toString() + "px" } if (this.fontSize !== size) { this.fontSize = size; this.update(true) } return this.parent }, setTestString: function(string) { this.testString = string; return this.update(true) }, setFixedSize: function(width, height) { this.fixedWidth = width; this.fixedHeight = height; if (width) { this.parent.width = width } if (height) { this.parent.height = height } return this.update(false) }, setBackgroundColor: function(color) { this.backgroundColor = color; return this.update(false) }, setFill: function(color) { this.color = color; return this.update(false) }, setColor: function(color) { this.color = color; return this.update(false) }, setResolution: function(value) { this.resolution = value; return this.update(false) }, setStroke: function(color, thickness) { if (thickness === undefined) { thickness = this.strokeThickness } if (color === undefined && this.strokeThickness !== 0) { this.strokeThickness = 0; this.update(true) } else if (this.stroke !== color || this.strokeThickness !== thickness) { this.stroke = color; this.strokeThickness = thickness; this.update(true) } return this.parent }, setShadow: function(x, y, color, blur, shadowStroke, shadowFill) { if (x === undefined) { x = 0 } if (y === undefined) { y = 0 } if (color === undefined) { color = "#000" } if (blur === undefined) { blur = 0 } if (shadowStroke === undefined) { shadowStroke = false } if (shadowFill === undefined) { shadowFill = true } this.shadowOffsetX = x; this.shadowOffsetY = y; this.shadowColor = color; this.shadowBlur = blur; this.shadowStroke = shadowStroke; this.shadowFill = shadowFill; return this.update(false) }, setShadowOffset: function(x, y) { if (x === undefined) { x = 0 } if (y === undefined) { y = x } this.shadowOffsetX = x; this.shadowOffsetY = y; return this.update(false) }, setShadowColor: function(color) { if (color === undefined) { color = "#000" } this.shadowColor = color; return this.update(false) }, setShadowBlur: function(blur) { if (blur === undefined) { blur = 0 } this.shadowBlur = blur; return this.update(false) }, setShadowStroke: function(enabled) { this.shadowStroke = enabled; return this.update(false) }, setShadowFill: function(enabled) { this.shadowFill = enabled; return this.update(false) }, setWordWrapWidth: function(width, useAdvancedWrap) { if (useAdvancedWrap === undefined) { useAdvancedWrap = false } this.wordWrapWidth = width; this.wordWrapUseAdvanced = useAdvancedWrap; return this.update(false) }, setWordWrapCallback: function(callback, scope) { if (scope === undefined) { scope = null } this.wordWrapCallback = callback; this.wordWrapCallbackScope = scope; return this.update(false) }, setAlign: function(align) { if (align === undefined) { align = "left" } this.align = align; return this.update(false) }, setMaxLines: function(max) { if (max === undefined) { max = 0 } this.maxLines = max; return this.update(false) }, getTextMetrics: function() { var metrics = this.metrics; return { ascent: metrics.ascent, descent: metrics.descent, fontSize: metrics.fontSize } }, toJSON: function() { var output = {}; for (var key in propertyMap) { output[key] = this[key] } output.metrics = this.getTextMetrics(); return output }, destroy: function() { this.parent = undefined } }); module.exports = TextStyle }, function(module, exports, __webpack_require__) { var CanvasPool = __webpack_require__(28); var MeasureText = function(textStyle) { var canvas = CanvasPool.create(this); var context = canvas.getContext("2d"); textStyle.syncFont(canvas, context); var width = Math.ceil(context.measureText(textStyle.testString).width * textStyle.baselineX); var baseline = width; var height = 2 * baseline; baseline = baseline * textStyle.baselineY | 0; canvas.width = width; canvas.height = height; context.fillStyle = "#f00"; context.fillRect(0, 0, width, height); context.font = textStyle._font; context.textBaseline = "alphabetic"; context.fillStyle = "#000"; context.fillText(textStyle.testString, 0, baseline); var output = { ascent: 0, descent: 0, fontSize: 0 }; if (!context.getImageData(0, 0, width, height)) { output.ascent = baseline; output.descent = baseline + 6; output.fontSize = output.ascent + output.descent; CanvasPool.remove(canvas); return output } var imagedata = context.getImageData(0, 0, width, height).data; var pixels = imagedata.length; var line = width * 4; var i; var j; var idx = 0; var stop = false; for (i = 0; i < baseline; i++) { for (j = 0; j < line; j += 4) { if (imagedata[idx + j] !== 255) { stop = true; break } } if (!stop) { idx += line } else { break } } output.ascent = baseline - i; idx = pixels - line; stop = false; for (i = height; i > baseline; i--) { for (j = 0; j < line; j += 4) { if (imagedata[idx + j] !== 255) { stop = true; break } } if (!stop) { idx -= line } else { break } } output.descent = i - baseline; output.fontSize = output.ascent + output.descent; CanvasPool.remove(canvas); return output }; module.exports = MeasureText }, function(module, exports, __webpack_require__) { var renderWebGL = __webpack_require__(2); var renderCanvas = __webpack_require__(2); if (true) { renderWebGL = __webpack_require__(736) } if (true) { renderCanvas = __webpack_require__(737) } module.exports = { renderWebGL: renderWebGL, renderCanvas: renderCanvas } }, function(module, exports, __webpack_require__) { var Utils = __webpack_require__(10); var TileSpriteWebGLRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix) { src.updateCanvas(); var getTint = Utils.getTintAppendFloatAlpha; this.pipeline.batchTexture(src, src.fillPattern, src.displayFrame.width * src.tileScaleX, src.displayFrame.height * src.tileScaleY, src.x, src.y, src.width, src.height, src.scaleX, src.scaleY, src.rotation, src.flipX, src.flipY, src.scrollFactorX, src.scrollFactorY, src.originX * src.width, src.originY * src.height, 0, 0, src.width, src.height, getTint(src._tintTL, camera.alpha * src._alphaTL), getTint(src._tintTR, camera.alpha * src._alphaTR), getTint(src._tintBL, camera.alpha * src._alphaBL), getTint(src._tintBR, camera.alpha * src._alphaBR), src._isTinted && src.tintFill, src.tilePositionX % src.displayFrame.width / src.displayFrame.width, src.tilePositionY % src.displayFrame.height / src.displayFrame.height, camera, parentMatrix) }; module.exports = TileSpriteWebGLRenderer }, function(module, exports) { var TileSpriteCanvasRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix) { src.updateCanvas(); renderer.batchSprite(src, src.frame, camera, parentMatrix) }; module.exports = TileSpriteCanvasRenderer }, function(module, exports, __webpack_require__) { var renderWebGL = __webpack_require__(2); var renderCanvas = __webpack_require__(2); if (true) { renderWebGL = __webpack_require__(739) } if (true) { renderCanvas = __webpack_require__(740) } module.exports = { renderWebGL: renderWebGL, renderCanvas: renderCanvas } }, function(module, exports, __webpack_require__) { var FillPathWebGL = __webpack_require__(100); var StrokePathWebGL = __webpack_require__(66); var ArcWebGLRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix) { var pipeline = this.pipeline; var camMatrix = pipeline._tempMatrix1; var shapeMatrix = pipeline._tempMatrix2; var calcMatrix = pipeline._tempMatrix3; renderer.setPipeline(pipeline); shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); camMatrix.copyFrom(camera.matrix); if (parentMatrix) { camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); shapeMatrix.e = src.x; shapeMatrix.f = src.y } else { shapeMatrix.e -= camera.scrollX * src.scrollFactorX; shapeMatrix.f -= camera.scrollY * src.scrollFactorY } camMatrix.multiply(shapeMatrix, calcMatrix); var dx = src._displayOriginX; var dy = src._displayOriginY; var alpha = camera.alpha * src.alpha; if (src.isFilled) { FillPathWebGL(pipeline, calcMatrix, src, alpha, dx, dy) } if (src.isStroked) { StrokePathWebGL(pipeline, src, alpha, dx, dy) } }; module.exports = ArcWebGLRenderer }, function(module, exports, __webpack_require__) { var DegToRad = __webpack_require__(36); var FillStyleCanvas = __webpack_require__(37); var LineStyleCanvas = __webpack_require__(51); var SetTransform = __webpack_require__(24); var ArcCanvasRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix) { var ctx = renderer.currentContext; if (SetTransform(renderer, ctx, src, camera, parentMatrix)) { var radius = src.radius; ctx.beginPath(); ctx.arc(radius - src.originX * (radius * 2), radius - src.originY * (radius * 2), radius, DegToRad(src._startAngle), DegToRad(src._endAngle), src.anticlockwise); if (src.closePath) { ctx.closePath() } if (src.isFilled) { FillStyleCanvas(ctx, src); ctx.fill() } if (src.isStroked) { LineStyleCanvas(ctx, src); ctx.stroke() } } }; module.exports = ArcCanvasRenderer }, function(module, exports, __webpack_require__) { var renderWebGL = __webpack_require__(2); var renderCanvas = __webpack_require__(2); if (true) { renderWebGL = __webpack_require__(742) } if (true) { renderCanvas = __webpack_require__(743) } module.exports = { renderWebGL: renderWebGL, renderCanvas: renderCanvas } }, function(module, exports, __webpack_require__) { var FillPathWebGL = __webpack_require__(100); var StrokePathWebGL = __webpack_require__(66); var CurveWebGLRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix) { var pipeline = this.pipeline; var camMatrix = pipeline._tempMatrix1; var shapeMatrix = pipeline._tempMatrix2; var calcMatrix = pipeline._tempMatrix3; renderer.setPipeline(pipeline); shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); camMatrix.copyFrom(camera.matrix); if (parentMatrix) { camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); shapeMatrix.e = src.x; shapeMatrix.f = src.y } else { shapeMatrix.e -= camera.scrollX * src.scrollFactorX; shapeMatrix.f -= camera.scrollY * src.scrollFactorY } camMatrix.multiply(shapeMatrix, calcMatrix); var dx = src._displayOriginX + src._curveBounds.x; var dy = src._displayOriginY + src._curveBounds.y; var alpha = camera.alpha * src.alpha; if (src.isFilled) { FillPathWebGL(pipeline, calcMatrix, src, alpha, dx, dy) } if (src.isStroked) { StrokePathWebGL(pipeline, src, alpha, dx, dy) } }; module.exports = CurveWebGLRenderer }, function(module, exports, __webpack_require__) { var FillStyleCanvas = __webpack_require__(37); var LineStyleCanvas = __webpack_require__(51); var SetTransform = __webpack_require__(24); var CurveCanvasRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix) { var ctx = renderer.currentContext; if (SetTransform(renderer, ctx, src, camera, parentMatrix)) { var dx = src._displayOriginX + src._curveBounds.x; var dy = src._displayOriginY + src._curveBounds.y; var path = src.pathData; var pathLength = path.length - 1; var px1 = path[0] - dx; var py1 = path[1] - dy; ctx.beginPath(); ctx.moveTo(px1, py1); if (!src.closePath) { pathLength -= 2 } for (var i = 2; i < pathLength; i += 2) { var px2 = path[i] - dx; var py2 = path[i + 1] - dy; ctx.lineTo(px2, py2) } if (src.closePath) { ctx.closePath() } if (src.isFilled) { FillStyleCanvas(ctx, src); ctx.fill() } if (src.isStroked) { LineStyleCanvas(ctx, src); ctx.stroke() } } }; module.exports = CurveCanvasRenderer }, function(module, exports, __webpack_require__) { var renderWebGL = __webpack_require__(2); var renderCanvas = __webpack_require__(2); if (true) { renderWebGL = __webpack_require__(745) } if (true) { renderCanvas = __webpack_require__(746) } module.exports = { renderWebGL: renderWebGL, renderCanvas: renderCanvas } }, function(module, exports, __webpack_require__) { var FillPathWebGL = __webpack_require__(100); var StrokePathWebGL = __webpack_require__(66); var EllipseWebGLRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix) { var pipeline = this.pipeline; var camMatrix = pipeline._tempMatrix1; var shapeMatrix = pipeline._tempMatrix2; var calcMatrix = pipeline._tempMatrix3; renderer.setPipeline(pipeline); shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); camMatrix.copyFrom(camera.matrix); if (parentMatrix) { camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); shapeMatrix.e = src.x; shapeMatrix.f = src.y } else { shapeMatrix.e -= camera.scrollX * src.scrollFactorX; shapeMatrix.f -= camera.scrollY * src.scrollFactorY } camMatrix.multiply(shapeMatrix, calcMatrix); var dx = src._displayOriginX; var dy = src._displayOriginY; var alpha = camera.alpha * src.alpha; if (src.isFilled) { FillPathWebGL(pipeline, calcMatrix, src, alpha, dx, dy) } if (src.isStroked) { StrokePathWebGL(pipeline, src, alpha, dx, dy) } }; module.exports = EllipseWebGLRenderer }, function(module, exports, __webpack_require__) { var FillStyleCanvas = __webpack_require__(37); var LineStyleCanvas = __webpack_require__(51); var SetTransform = __webpack_require__(24); var EllipseCanvasRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix) { var ctx = renderer.currentContext; if (SetTransform(renderer, ctx, src, camera, parentMatrix)) { var dx = src._displayOriginX; var dy = src._displayOriginY; var path = src.pathData; var pathLength = path.length - 1; var px1 = path[0] - dx; var py1 = path[1] - dy; ctx.beginPath(); ctx.moveTo(px1, py1); if (!src.closePath) { pathLength -= 2 } for (var i = 2; i < pathLength; i += 2) { var px2 = path[i] - dx; var py2 = path[i + 1] - dy; ctx.lineTo(px2, py2) } ctx.closePath(); if (src.isFilled) { FillStyleCanvas(ctx, src); ctx.fill() } if (src.isStroked) { LineStyleCanvas(ctx, src); ctx.stroke() } } }; module.exports = EllipseCanvasRenderer }, function(module, exports, __webpack_require__) { var renderWebGL = __webpack_require__(2); var renderCanvas = __webpack_require__(2); if (true) { renderWebGL = __webpack_require__(748) } if (true) { renderCanvas = __webpack_require__(749) } module.exports = { renderWebGL: renderWebGL, renderCanvas: renderCanvas } }, function(module, exports, __webpack_require__) { var Utils = __webpack_require__(10); var GridWebGLRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix) { var pipeline = this.pipeline; var camMatrix = pipeline._tempMatrix1; var shapeMatrix = pipeline._tempMatrix2; var calcMatrix = pipeline._tempMatrix3; renderer.setPipeline(pipeline); shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); camMatrix.copyFrom(camera.matrix); if (parentMatrix) { camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); shapeMatrix.e = src.x; shapeMatrix.f = src.y } else { shapeMatrix.e -= camera.scrollX * src.scrollFactorX; shapeMatrix.f -= camera.scrollY * src.scrollFactorY } camMatrix.multiply(shapeMatrix, calcMatrix); calcMatrix.translate(-src._displayOriginX, -src._displayOriginY); var alpha = camera.alpha * src.alpha; var width = src.width; var height = src.height; var cellWidth = src.cellWidth; var cellHeight = src.cellHeight; var gridWidth = Math.ceil(width / cellWidth); var gridHeight = Math.ceil(height / cellHeight); var cellWidthA = cellWidth; var cellHeightA = cellHeight; var cellWidthB = cellWidth - (gridWidth * cellWidth - width); var cellHeightB = cellHeight - (gridHeight * cellHeight - height); var fillTint; var fillTintColor; var showCells = src.showCells; var showAltCells = src.showAltCells; var showOutline = src.showOutline; var x = 0; var y = 0; var r = 0; var cw = 0; var ch = 0; if (showOutline) { cellWidthA--; cellHeightA--; if (cellWidthB === cellWidth) { cellWidthB-- } if (cellHeightB === cellHeight) { cellHeightB-- } } if (showCells && src.fillAlpha > 0) { fillTint = pipeline.fillTint; fillTintColor = Utils.getTintAppendFloatAlphaAndSwap(src.fillColor, src.fillAlpha * alpha); fillTint.TL = fillTintColor; fillTint.TR = fillTintColor; fillTint.BL = fillTintColor; fillTint.BR = fillTintColor; for (y = 0; y < gridHeight; y++) { if (showAltCells) { r = y % 2 } for (x = 0; x < gridWidth; x++) { if (showAltCells && r) { r = 0; continue } r++; cw = x < gridWidth - 1 ? cellWidthA : cellWidthB; ch = y < gridHeight - 1 ? cellHeightA : cellHeightB; pipeline.setTexture2D(); pipeline.batchFillRect(x * cellWidth, y * cellHeight, cw, ch) } } } if (showAltCells && src.altFillAlpha > 0) { fillTint = pipeline.fillTint; fillTintColor = Utils.getTintAppendFloatAlphaAndSwap(src.altFillColor, src.altFillAlpha * alpha); fillTint.TL = fillTintColor; fillTint.TR = fillTintColor; fillTint.BL = fillTintColor; fillTint.BR = fillTintColor; for (y = 0; y < gridHeight; y++) { if (showAltCells) { r = y % 2 } for (x = 0; x < gridWidth; x++) { if (showAltCells && !r) { r = 1; continue } r = 0; cw = x < gridWidth - 1 ? cellWidthA : cellWidthB; ch = y < gridHeight - 1 ? cellHeightA : cellHeightB; pipeline.setTexture2D(); pipeline.batchFillRect(x * cellWidth, y * cellHeight, cw, ch) } } } if (showOutline && src.outlineFillAlpha > 0) { var strokeTint = pipeline.strokeTint; var color = Utils.getTintAppendFloatAlphaAndSwap(src.outlineFillColor, src.outlineFillAlpha * alpha); strokeTint.TL = color; strokeTint.TR = color; strokeTint.BL = color; strokeTint.BR = color; for (x = 1; x < gridWidth; x++) { var x1 = x * cellWidth; pipeline.setTexture2D(); pipeline.batchLine(x1, 0, x1, height, 1, 1, 1, 0, false) } for (y = 1; y < gridHeight; y++) { var y1 = y * cellHeight; pipeline.setTexture2D(); pipeline.batchLine(0, y1, width, y1, 1, 1, 1, 0, false) } } }; module.exports = GridWebGLRenderer }, function(module, exports, __webpack_require__) { var FillStyleCanvas = __webpack_require__(37); var LineStyleCanvas = __webpack_require__(51); var SetTransform = __webpack_require__(24); var RectangleCanvasRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix) { var ctx = renderer.currentContext; if (SetTransform(renderer, ctx, src, camera, parentMatrix)) { var dx = src._displayOriginX; var dy = src._displayOriginY; if (src.isFilled) { FillStyleCanvas(ctx, src); ctx.fillRect(-dx, -dy, src.width, src.height) } if (src.isStroked) { LineStyleCanvas(ctx, src); ctx.beginPath(); ctx.rect(-dx, -dy, src.width, src.height); ctx.stroke() } } }; module.exports = RectangleCanvasRenderer }, function(module, exports, __webpack_require__) { var renderWebGL = __webpack_require__(2); var renderCanvas = __webpack_require__(2); if (true) { renderWebGL = __webpack_require__(751) } if (true) { renderCanvas = __webpack_require__(752) } module.exports = { renderWebGL: renderWebGL, renderCanvas: renderCanvas } }, function(module, exports, __webpack_require__) { var Utils = __webpack_require__(10); var IsoBoxWebGLRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix) { var pipeline = this.pipeline; var camMatrix = pipeline._tempMatrix1; var shapeMatrix = pipeline._tempMatrix2; var calcMatrix = pipeline._tempMatrix3; renderer.setPipeline(pipeline); shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); camMatrix.copyFrom(camera.matrix); if (parentMatrix) { camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); shapeMatrix.e = src.x; shapeMatrix.f = src.y } else { shapeMatrix.e -= camera.scrollX * src.scrollFactorX; shapeMatrix.f -= camera.scrollY * src.scrollFactorY } camMatrix.multiply(shapeMatrix, calcMatrix); var size = src.width; var height = src.height; var sizeA = size / 2; var sizeB = size / src.projection; var alpha = camera.alpha * src.alpha; if (!src.isFilled) { return } var tint; var x0; var y0; var x1; var y1; var x2; var y2; var x3; var y3; if (src.showTop) { tint = Utils.getTintAppendFloatAlphaAndSwap(src.fillTop, alpha); x0 = calcMatrix.getX(-sizeA, -height); y0 = calcMatrix.getY(-sizeA, -height); x1 = calcMatrix.getX(0, -sizeB - height); y1 = calcMatrix.getY(0, -sizeB - height); x2 = calcMatrix.getX(sizeA, -height); y2 = calcMatrix.getY(sizeA, -height); x3 = calcMatrix.getX(0, sizeB - height); y3 = calcMatrix.getY(0, sizeB - height); pipeline.setTexture2D(); pipeline.batchQuad(x0, y0, x1, y1, x2, y2, x3, y3, 0, 0, 1, 1, tint, tint, tint, tint, 2) } if (src.showLeft) { tint = Utils.getTintAppendFloatAlphaAndSwap(src.fillLeft, alpha); x0 = calcMatrix.getX(-sizeA, 0); y0 = calcMatrix.getY(-sizeA, 0); x1 = calcMatrix.getX(0, sizeB); y1 = calcMatrix.getY(0, sizeB); x2 = calcMatrix.getX(0, sizeB - height); y2 = calcMatrix.getY(0, sizeB - height); x3 = calcMatrix.getX(-sizeA, -height); y3 = calcMatrix.getY(-sizeA, -height); pipeline.setTexture2D(); pipeline.batchQuad(x0, y0, x1, y1, x2, y2, x3, y3, 0, 0, 1, 1, tint, tint, tint, tint, 2) } if (src.showRight) { tint = Utils.getTintAppendFloatAlphaAndSwap(src.fillRight, alpha); x0 = calcMatrix.getX(sizeA, 0); y0 = calcMatrix.getY(sizeA, 0); x1 = calcMatrix.getX(0, sizeB); y1 = calcMatrix.getY(0, sizeB); x2 = calcMatrix.getX(0, sizeB - height); y2 = calcMatrix.getY(0, sizeB - height); x3 = calcMatrix.getX(sizeA, -height); y3 = calcMatrix.getY(sizeA, -height); pipeline.setTexture2D(); pipeline.batchQuad(x0, y0, x1, y1, x2, y2, x3, y3, 0, 0, 1, 1, tint, tint, tint, tint, 2) } }; module.exports = IsoBoxWebGLRenderer }, function(module, exports, __webpack_require__) { var FillStyleCanvas = __webpack_require__(37); var SetTransform = __webpack_require__(24); var IsoBoxCanvasRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix) { var ctx = renderer.currentContext; if (SetTransform(renderer, ctx, src, camera, parentMatrix) && src.isFilled) { var size = src.width; var height = src.height; var sizeA = size / 2; var sizeB = size / src.projection; if (src.showTop) { FillStyleCanvas(ctx, src, src.fillTop); ctx.beginPath(); ctx.moveTo(-sizeA, -height); ctx.lineTo(0, -sizeB - height); ctx.lineTo(sizeA, -height); ctx.lineTo(sizeA, -1); ctx.lineTo(0, sizeB - 1); ctx.lineTo(-sizeA, -1); ctx.lineTo(-sizeA, -height); ctx.fill() } if (src.showLeft) { FillStyleCanvas(ctx, src, src.fillLeft); ctx.beginPath(); ctx.moveTo(-sizeA, 0); ctx.lineTo(0, sizeB); ctx.lineTo(0, sizeB - height); ctx.lineTo(-sizeA, -height); ctx.lineTo(-sizeA, 0); ctx.fill() } if (src.showRight) { FillStyleCanvas(ctx, src, src.fillRight); ctx.beginPath(); ctx.moveTo(sizeA, 0); ctx.lineTo(0, sizeB); ctx.lineTo(0, sizeB - height); ctx.lineTo(sizeA, -height); ctx.lineTo(sizeA, 0); ctx.fill() } } }; module.exports = IsoBoxCanvasRenderer }, function(module, exports, __webpack_require__) { var renderWebGL = __webpack_require__(2); var renderCanvas = __webpack_require__(2); if (true) { renderWebGL = __webpack_require__(754) } if (true) { renderCanvas = __webpack_require__(755) } module.exports = { renderWebGL: renderWebGL, renderCanvas: renderCanvas } }, function(module, exports, __webpack_require__) { var Utils = __webpack_require__(10); var IsoTriangleWebGLRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix) { var pipeline = this.pipeline; var camMatrix = pipeline._tempMatrix1; var shapeMatrix = pipeline._tempMatrix2; var calcMatrix = pipeline._tempMatrix3; renderer.setPipeline(pipeline); shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); camMatrix.copyFrom(camera.matrix); if (parentMatrix) { camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); shapeMatrix.e = src.x; shapeMatrix.f = src.y } else { shapeMatrix.e -= camera.scrollX * src.scrollFactorX; shapeMatrix.f -= camera.scrollY * src.scrollFactorY } camMatrix.multiply(shapeMatrix, calcMatrix); var size = src.width; var height = src.height; var sizeA = size / 2; var sizeB = size / src.projection; var reversed = src.isReversed; var alpha = camera.alpha * src.alpha; if (!src.isFilled) { return } var tint; var x0; var y0; var x1; var y1; var x2; var y2; if (src.showTop && reversed) { tint = Utils.getTintAppendFloatAlphaAndSwap(src.fillTop, alpha); x0 = calcMatrix.getX(-sizeA, -height); y0 = calcMatrix.getY(-sizeA, -height); x1 = calcMatrix.getX(0, -sizeB - height); y1 = calcMatrix.getY(0, -sizeB - height); x2 = calcMatrix.getX(sizeA, -height); y2 = calcMatrix.getY(sizeA, -height); var x3 = calcMatrix.getX(0, sizeB - height); var y3 = calcMatrix.getY(0, sizeB - height); pipeline.setTexture2D(); pipeline.batchQuad(x0, y0, x1, y1, x2, y2, x3, y3, 0, 0, 1, 1, tint, tint, tint, tint, 2) } if (src.showLeft) { tint = Utils.getTintAppendFloatAlphaAndSwap(src.fillLeft, alpha); if (reversed) { x0 = calcMatrix.getX(-sizeA, -height); y0 = calcMatrix.getY(-sizeA, -height); x1 = calcMatrix.getX(0, sizeB); y1 = calcMatrix.getY(0, sizeB); x2 = calcMatrix.getX(0, sizeB - height); y2 = calcMatrix.getY(0, sizeB - height) } else { x0 = calcMatrix.getX(-sizeA, 0); y0 = calcMatrix.getY(-sizeA, 0); x1 = calcMatrix.getX(0, sizeB); y1 = calcMatrix.getY(0, sizeB); x2 = calcMatrix.getX(0, sizeB - height); y2 = calcMatrix.getY(0, sizeB - height) } pipeline.batchTri(x0, y0, x1, y1, x2, y2, 0, 0, 1, 1, tint, tint, tint, 2) } if (src.showRight) { tint = Utils.getTintAppendFloatAlphaAndSwap(src.fillRight, alpha); if (reversed) { x0 = calcMatrix.getX(sizeA, -height); y0 = calcMatrix.getY(sizeA, -height); x1 = calcMatrix.getX(0, sizeB); y1 = calcMatrix.getY(0, sizeB); x2 = calcMatrix.getX(0, sizeB - height); y2 = calcMatrix.getY(0, sizeB - height) } else { x0 = calcMatrix.getX(sizeA, 0); y0 = calcMatrix.getY(sizeA, 0); x1 = calcMatrix.getX(0, sizeB); y1 = calcMatrix.getY(0, sizeB); x2 = calcMatrix.getX(0, sizeB - height); y2 = calcMatrix.getY(0, sizeB - height) } pipeline.setTexture2D(); pipeline.batchTri(x0, y0, x1, y1, x2, y2, 0, 0, 1, 1, tint, tint, tint, 2) } }; module.exports = IsoTriangleWebGLRenderer }, function(module, exports, __webpack_require__) { var FillStyleCanvas = __webpack_require__(37); var SetTransform = __webpack_require__(24); var IsoTriangleCanvasRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix) { var ctx = renderer.currentContext; if (SetTransform(renderer, ctx, src, camera, parentMatrix) && src.isFilled) { var size = src.width; var height = src.height; var sizeA = size / 2; var sizeB = size / src.projection; var reversed = src.isReversed; if (src.showTop && reversed) { FillStyleCanvas(ctx, src, src.fillTop); ctx.beginPath(); ctx.moveTo(-sizeA, -height); ctx.lineTo(0, -sizeB - height); ctx.lineTo(sizeA, -height); ctx.lineTo(0, sizeB - height); ctx.fill() } if (src.showLeft) { FillStyleCanvas(ctx, src, src.fillLeft); ctx.beginPath(); if (reversed) { ctx.moveTo(-sizeA, -height); ctx.lineTo(0, sizeB); ctx.lineTo(0, sizeB - height) } else { ctx.moveTo(-sizeA, 0); ctx.lineTo(0, sizeB); ctx.lineTo(0, sizeB - height) } ctx.fill() } if (src.showRight) { FillStyleCanvas(ctx, src, src.fillRight); ctx.beginPath(); if (reversed) { ctx.moveTo(sizeA, -height); ctx.lineTo(0, sizeB); ctx.lineTo(0, sizeB - height) } else { ctx.moveTo(sizeA, 0); ctx.lineTo(0, sizeB); ctx.lineTo(0, sizeB - height) } ctx.fill() } } }; module.exports = IsoTriangleCanvasRenderer }, function(module, exports, __webpack_require__) { var renderWebGL = __webpack_require__(2); var renderCanvas = __webpack_require__(2); if (true) { renderWebGL = __webpack_require__(757) } if (true) { renderCanvas = __webpack_require__(758) } module.exports = { renderWebGL: renderWebGL, renderCanvas: renderCanvas } }, function(module, exports, __webpack_require__) { var Utils = __webpack_require__(10); var LineWebGLRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix) { var pipeline = this.pipeline; var camMatrix = pipeline._tempMatrix1; var shapeMatrix = pipeline._tempMatrix2; renderer.setPipeline(pipeline); shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); camMatrix.copyFrom(camera.matrix); if (parentMatrix) { camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); shapeMatrix.e = src.x; shapeMatrix.f = src.y } else { shapeMatrix.e -= camera.scrollX * src.scrollFactorX; shapeMatrix.f -= camera.scrollY * src.scrollFactorY } var dx = src._displayOriginX; var dy = src._displayOriginY; var alpha = camera.alpha * src.alpha; if (src.isStroked) { var strokeTint = pipeline.strokeTint; var color = Utils.getTintAppendFloatAlphaAndSwap(src.strokeColor, src.strokeAlpha * alpha); strokeTint.TL = color; strokeTint.TR = color; strokeTint.BL = color; strokeTint.BR = color; var startWidth = src._startWidth; var endWidth = src._endWidth; pipeline.setTexture2D(); pipeline.batchLine(src.geom.x1 - dx, src.geom.y1 - dy, src.geom.x2 - dx, src.geom.y2 - dy, startWidth, endWidth, 1, 0, false, shapeMatrix, camMatrix) } }; module.exports = LineWebGLRenderer }, function(module, exports, __webpack_require__) { var LineStyleCanvas = __webpack_require__(51); var SetTransform = __webpack_require__(24); var LineCanvasRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix) { var ctx = renderer.currentContext; if (SetTransform(renderer, ctx, src, camera, parentMatrix)) { var dx = src._displayOriginX; var dy = src._displayOriginY; if (src.isStroked) { LineStyleCanvas(ctx, src); ctx.beginPath(); ctx.moveTo(src.geom.x1 - dx, src.geom.y1 - dy); ctx.lineTo(src.geom.x2 - dx, src.geom.y2 - dy); ctx.stroke() } } }; module.exports = LineCanvasRenderer }, function(module, exports, __webpack_require__) { var renderWebGL = __webpack_require__(2); var renderCanvas = __webpack_require__(2); if (true) { renderWebGL = __webpack_require__(760) } if (true) { renderCanvas = __webpack_require__(761) } module.exports = { renderWebGL: renderWebGL, renderCanvas: renderCanvas } }, function(module, exports, __webpack_require__) { var FillPathWebGL = __webpack_require__(100); var StrokePathWebGL = __webpack_require__(66); var PolygonWebGLRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix) { var pipeline = this.pipeline; var camMatrix = pipeline._tempMatrix1; var shapeMatrix = pipeline._tempMatrix2; var calcMatrix = pipeline._tempMatrix3; renderer.setPipeline(pipeline); shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); camMatrix.copyFrom(camera.matrix); if (parentMatrix) { camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); shapeMatrix.e = src.x; shapeMatrix.f = src.y } else { shapeMatrix.e -= camera.scrollX * src.scrollFactorX; shapeMatrix.f -= camera.scrollY * src.scrollFactorY } camMatrix.multiply(shapeMatrix, calcMatrix); var dx = src._displayOriginX; var dy = src._displayOriginY; var alpha = camera.alpha * src.alpha; if (src.isFilled) { FillPathWebGL(pipeline, calcMatrix, src, alpha, dx, dy) } if (src.isStroked) { StrokePathWebGL(pipeline, src, alpha, dx, dy) } }; module.exports = PolygonWebGLRenderer }, function(module, exports, __webpack_require__) { var FillStyleCanvas = __webpack_require__(37); var LineStyleCanvas = __webpack_require__(51); var SetTransform = __webpack_require__(24); var PolygonCanvasRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix) { var ctx = renderer.currentContext; if (SetTransform(renderer, ctx, src, camera, parentMatrix)) { var dx = src._displayOriginX; var dy = src._displayOriginY; var path = src.pathData; var pathLength = path.length - 1; var px1 = path[0] - dx; var py1 = path[1] - dy; ctx.beginPath(); ctx.moveTo(px1, py1); if (!src.closePath) { pathLength -= 2 } for (var i = 2; i < pathLength; i += 2) { var px2 = path[i] - dx; var py2 = path[i + 1] - dy; ctx.lineTo(px2, py2) } ctx.closePath(); if (src.isFilled) { FillStyleCanvas(ctx, src); ctx.fill() } if (src.isStroked) { LineStyleCanvas(ctx, src); ctx.stroke() } } }; module.exports = PolygonCanvasRenderer }, function(module, exports, __webpack_require__) { var renderWebGL = __webpack_require__(2); var renderCanvas = __webpack_require__(2); if (true) { renderWebGL = __webpack_require__(763) } if (true) { renderCanvas = __webpack_require__(764) } module.exports = { renderWebGL: renderWebGL, renderCanvas: renderCanvas } }, function(module, exports, __webpack_require__) { var StrokePathWebGL = __webpack_require__(66); var Utils = __webpack_require__(10); var RectangleWebGLRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix) { var pipeline = this.pipeline; var camMatrix = pipeline._tempMatrix1; var shapeMatrix = pipeline._tempMatrix2; var calcMatrix = pipeline._tempMatrix3; renderer.setPipeline(pipeline); shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); camMatrix.copyFrom(camera.matrix); if (parentMatrix) { camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); shapeMatrix.e = src.x; shapeMatrix.f = src.y } else { shapeMatrix.e -= camera.scrollX * src.scrollFactorX; shapeMatrix.f -= camera.scrollY * src.scrollFactorY } camMatrix.multiply(shapeMatrix, calcMatrix); var dx = src._displayOriginX; var dy = src._displayOriginY; var alpha = camera.alpha * src.alpha; if (src.isFilled) { var fillTint = pipeline.fillTint; var fillTintColor = Utils.getTintAppendFloatAlphaAndSwap(src.fillColor, src.fillAlpha * alpha); fillTint.TL = fillTintColor; fillTint.TR = fillTintColor; fillTint.BL = fillTintColor; fillTint.BR = fillTintColor; pipeline.batchFillRect(-dx, -dy, src.width, src.height) } if (src.isStroked) { StrokePathWebGL(pipeline, src, alpha, dx, dy) } }; module.exports = RectangleWebGLRenderer }, function(module, exports, __webpack_require__) { var FillStyleCanvas = __webpack_require__(37); var LineStyleCanvas = __webpack_require__(51); var SetTransform = __webpack_require__(24); var RectangleCanvasRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix) { var ctx = renderer.currentContext; if (SetTransform(renderer, ctx, src, camera, parentMatrix)) { var dx = src._displayOriginX; var dy = src._displayOriginY; if (src.isFilled) { FillStyleCanvas(ctx, src); ctx.fillRect(-dx, -dy, src.width, src.height) } if (src.isStroked) { LineStyleCanvas(ctx, src); ctx.beginPath(); ctx.rect(-dx, -dy, src.width, src.height); ctx.stroke() } } }; module.exports = RectangleCanvasRenderer }, function(module, exports, __webpack_require__) { var renderWebGL = __webpack_require__(2); var renderCanvas = __webpack_require__(2); if (true) { renderWebGL = __webpack_require__(766) } if (true) { renderCanvas = __webpack_require__(767) } module.exports = { renderWebGL: renderWebGL, renderCanvas: renderCanvas } }, function(module, exports, __webpack_require__) { var FillPathWebGL = __webpack_require__(100); var StrokePathWebGL = __webpack_require__(66); var StarWebGLRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix) { var pipeline = this.pipeline; var camMatrix = pipeline._tempMatrix1; var shapeMatrix = pipeline._tempMatrix2; var calcMatrix = pipeline._tempMatrix3; renderer.setPipeline(pipeline); shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); camMatrix.copyFrom(camera.matrix); if (parentMatrix) { camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); shapeMatrix.e = src.x; shapeMatrix.f = src.y } else { shapeMatrix.e -= camera.scrollX * src.scrollFactorX; shapeMatrix.f -= camera.scrollY * src.scrollFactorY } camMatrix.multiply(shapeMatrix, calcMatrix); var dx = src._displayOriginX; var dy = src._displayOriginY; var alpha = camera.alpha * src.alpha; if (src.isFilled) { FillPathWebGL(pipeline, calcMatrix, src, alpha, dx, dy) } if (src.isStroked) { StrokePathWebGL(pipeline, src, alpha, dx, dy) } }; module.exports = StarWebGLRenderer }, function(module, exports, __webpack_require__) { var FillStyleCanvas = __webpack_require__(37); var LineStyleCanvas = __webpack_require__(51); var SetTransform = __webpack_require__(24); var StarCanvasRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix) { var ctx = renderer.currentContext; if (SetTransform(renderer, ctx, src, camera, parentMatrix)) { var dx = src._displayOriginX; var dy = src._displayOriginY; var path = src.pathData; var pathLength = path.length - 1; var px1 = path[0] - dx; var py1 = path[1] - dy; ctx.beginPath(); ctx.moveTo(px1, py1); if (!src.closePath) { pathLength -= 2 } for (var i = 2; i < pathLength; i += 2) { var px2 = path[i] - dx; var py2 = path[i + 1] - dy; ctx.lineTo(px2, py2) } ctx.closePath(); if (src.isFilled) { FillStyleCanvas(ctx, src); ctx.fill() } if (src.isStroked) { LineStyleCanvas(ctx, src); ctx.stroke() } } }; module.exports = StarCanvasRenderer }, function(module, exports, __webpack_require__) { var renderWebGL = __webpack_require__(2); var renderCanvas = __webpack_require__(2); if (true) { renderWebGL = __webpack_require__(769) } if (true) { renderCanvas = __webpack_require__(770) } module.exports = { renderWebGL: renderWebGL, renderCanvas: renderCanvas } }, function(module, exports, __webpack_require__) { var StrokePathWebGL = __webpack_require__(66); var Utils = __webpack_require__(10); var TriangleWebGLRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix) { var pipeline = this.pipeline; var camMatrix = pipeline._tempMatrix1; var shapeMatrix = pipeline._tempMatrix2; var calcMatrix = pipeline._tempMatrix3; renderer.setPipeline(pipeline); shapeMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); camMatrix.copyFrom(camera.matrix); if (parentMatrix) { camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); shapeMatrix.e = src.x; shapeMatrix.f = src.y } else { shapeMatrix.e -= camera.scrollX * src.scrollFactorX; shapeMatrix.f -= camera.scrollY * src.scrollFactorY } camMatrix.multiply(shapeMatrix, calcMatrix); var dx = src._displayOriginX; var dy = src._displayOriginY; var alpha = camera.alpha * src.alpha; if (src.isFilled) { var fillTint = pipeline.fillTint; var fillTintColor = Utils.getTintAppendFloatAlphaAndSwap(src.fillColor, src.fillAlpha * alpha); fillTint.TL = fillTintColor; fillTint.TR = fillTintColor; fillTint.BL = fillTintColor; fillTint.BR = fillTintColor; var x1 = src.geom.x1 - dx; var y1 = src.geom.y1 - dy; var x2 = src.geom.x2 - dx; var y2 = src.geom.y2 - dy; var x3 = src.geom.x3 - dx; var y3 = src.geom.y3 - dy; pipeline.setTexture2D(); pipeline.batchFillTriangle(x1, y1, x2, y2, x3, y3, shapeMatrix, camMatrix) } if (src.isStroked) { StrokePathWebGL(pipeline, src, alpha, dx, dy) } }; module.exports = TriangleWebGLRenderer }, function(module, exports, __webpack_require__) { var FillStyleCanvas = __webpack_require__(37); var LineStyleCanvas = __webpack_require__(51); var SetTransform = __webpack_require__(24); var TriangleCanvasRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix) { var ctx = renderer.currentContext; if (SetTransform(renderer, ctx, src, camera, parentMatrix)) { var dx = src._displayOriginX; var dy = src._displayOriginY; var x1 = src.geom.x1 - dx; var y1 = src.geom.y1 - dy; var x2 = src.geom.x2 - dx; var y2 = src.geom.y2 - dy; var x3 = src.geom.x3 - dx; var y3 = src.geom.y3 - dy; ctx.beginPath(); ctx.moveTo(x1, y1); ctx.lineTo(x2, y2); ctx.lineTo(x3, y3); ctx.closePath(); if (src.isFilled) { FillStyleCanvas(ctx, src); ctx.fill() } if (src.isStroked) { LineStyleCanvas(ctx, src); ctx.stroke() } } }; module.exports = TriangleCanvasRenderer }, function(module, exports, __webpack_require__) { var Blitter = __webpack_require__(179); var GameObjectFactory = __webpack_require__(5); GameObjectFactory.register("blitter", function(x, y, key, frame) { return this.displayList.add(new Blitter(this.scene, x, y, key, frame)) }) }, function(module, exports, __webpack_require__) { var Container = __webpack_require__(180); var GameObjectFactory = __webpack_require__(5); GameObjectFactory.register("container", function(x, y, children) { return this.displayList.add(new Container(this.scene, x, y, children)) }) }, function(module, exports, __webpack_require__) { var DynamicBitmapText = __webpack_require__(181); var GameObjectFactory = __webpack_require__(5); GameObjectFactory.register("dynamicBitmapText", function(x, y, font, text, size) { return this.displayList.add(new DynamicBitmapText(this.scene, x, y, font, text, size)) }) }, function(module, exports, __webpack_require__) { var Graphics = __webpack_require__(182); var GameObjectFactory = __webpack_require__(5); GameObjectFactory.register("graphics", function(config) { return this.displayList.add(new Graphics(this.scene, config)) }) }, function(module, exports, __webpack_require__) { var Group = __webpack_require__(96); var GameObjectFactory = __webpack_require__(5); GameObjectFactory.register("group", function(children, config) { return this.updateList.add(new Group(this.scene, children, config)) }) }, function(module, exports, __webpack_require__) { var Image = __webpack_require__(82); var GameObjectFactory = __webpack_require__(5); GameObjectFactory.register("image", function(x, y, key, frame) { return this.displayList.add(new Image(this.scene, x, y, key, frame)) }) }, function(module, exports, __webpack_require__) { var GameObjectFactory = __webpack_require__(5); var ParticleEmitterManager = __webpack_require__(185); GameObjectFactory.register("particles", function(key, frame, emitters) { var manager = new ParticleEmitterManager(this.scene, key, frame, emitters); this.displayList.add(manager); this.updateList.add(manager); return manager }) }, function(module, exports, __webpack_require__) { var GameObjectFactory = __webpack_require__(5); var PathFollower = __webpack_require__(353); GameObjectFactory.register("follower", function(path, x, y, key, frame) { var sprite = new PathFollower(this.scene, path, x, y, key, frame); this.displayList.add(sprite); this.updateList.add(sprite); return sprite }) }, function(module, exports, __webpack_require__) { var GameObjectFactory = __webpack_require__(5); var RenderTexture = __webpack_require__(186); GameObjectFactory.register("renderTexture", function(x, y, width, height) { return this.displayList.add(new RenderTexture(this.scene, x, y, width, height)) }) }, function(module, exports, __webpack_require__) { var GameObjectFactory = __webpack_require__(5); var Sprite = __webpack_require__(50); GameObjectFactory.register("sprite", function(x, y, key, frame) { var sprite = new Sprite(this.scene, x, y, key, frame); this.displayList.add(sprite); this.updateList.add(sprite); return sprite }) }, function(module, exports, __webpack_require__) { var BitmapText = __webpack_require__(124); var GameObjectFactory = __webpack_require__(5); GameObjectFactory.register("bitmapText", function(x, y, font, text, size, align) { return this.displayList.add(new BitmapText(this.scene, x, y, font, text, size, align)) }) }, function(module, exports, __webpack_require__) { var Text = __webpack_require__(187); var GameObjectFactory = __webpack_require__(5); GameObjectFactory.register("text", function(x, y, text, style) { return this.displayList.add(new Text(this.scene, x, y, text, style)) }) }, function(module, exports, __webpack_require__) { var TileSprite = __webpack_require__(188); var GameObjectFactory = __webpack_require__(5); GameObjectFactory.register("tileSprite", function(x, y, width, height, key, frame) { return this.displayList.add(new TileSprite(this.scene, x, y, width, height, key, frame)) }) }, function(module, exports, __webpack_require__) { var Zone = __webpack_require__(107); var GameObjectFactory = __webpack_require__(5); GameObjectFactory.register("zone", function(x, y, width, height) { return this.displayList.add(new Zone(this.scene, x, y, width, height)) }) }, function(module, exports, __webpack_require__) { var Arc = __webpack_require__(356); var GameObjectFactory = __webpack_require__(5); GameObjectFactory.register("arc", function(x, y, radius, startAngle, endAngle, anticlockwise, fillColor, fillAlpha) { return this.displayList.add(new Arc(this.scene, x, y, radius, startAngle, endAngle, anticlockwise, fillColor, fillAlpha)) }); GameObjectFactory.register("circle", function(x, y, radius, fillColor, fillAlpha) { return this.displayList.add(new Arc(this.scene, x, y, radius, 0, 360, false, fillColor, fillAlpha)) }) }, function(module, exports, __webpack_require__) { var GameObjectFactory = __webpack_require__(5); var Curve = __webpack_require__(357); GameObjectFactory.register("curve", function(x, y, curve, fillColor, fillAlpha) { return this.displayList.add(new Curve(this.scene, x, y, curve, fillColor, fillAlpha)) }) }, function(module, exports, __webpack_require__) { var Ellipse = __webpack_require__(358); var GameObjectFactory = __webpack_require__(5); GameObjectFactory.register("ellipse", function(x, y, width, height, fillColor, fillAlpha) { return this.displayList.add(new Ellipse(this.scene, x, y, width, height, fillColor, fillAlpha)) }) }, function(module, exports, __webpack_require__) { var GameObjectFactory = __webpack_require__(5); var Grid = __webpack_require__(359); GameObjectFactory.register("grid", function(x, y, width, height, cellWidth, cellHeight, fillColor, fillAlpha, outlineFillColor, outlineFillAlpha) { return this.displayList.add(new Grid(this.scene, x, y, width, height, cellWidth, cellHeight, fillColor, fillAlpha, outlineFillColor, outlineFillAlpha)) }) }, function(module, exports, __webpack_require__) { var GameObjectFactory = __webpack_require__(5); var IsoBox = __webpack_require__(360); GameObjectFactory.register("isobox", function(x, y, size, height, fillTop, fillLeft, fillRight) { return this.displayList.add(new IsoBox(this.scene, x, y, size, height, fillTop, fillLeft, fillRight)) }) }, function(module, exports, __webpack_require__) { var GameObjectFactory = __webpack_require__(5); var IsoTriangle = __webpack_require__(361); GameObjectFactory.register("isotriangle", function(x, y, size, height, reversed, fillTop, fillLeft, fillRight) { return this.displayList.add(new IsoTriangle(this.scene, x, y, size, height, reversed, fillTop, fillLeft, fillRight)) }) }, function(module, exports, __webpack_require__) { var GameObjectFactory = __webpack_require__(5); var Line = __webpack_require__(362); GameObjectFactory.register("line", function(x, y, x1, y1, x2, y2, strokeColor, strokeAlpha) { return this.displayList.add(new Line(this.scene, x, y, x1, y1, x2, y2, strokeColor, strokeAlpha)) }) }, function(module, exports, __webpack_require__) { var GameObjectFactory = __webpack_require__(5); var Polygon = __webpack_require__(363); GameObjectFactory.register("polygon", function(x, y, points, fillColor, fillAlpha) { return this.displayList.add(new Polygon(this.scene, x, y, points, fillColor, fillAlpha)) }) }, function(module, exports, __webpack_require__) { var GameObjectFactory = __webpack_require__(5); var Rectangle = __webpack_require__(368); GameObjectFactory.register("rectangle", function(x, y, width, height, fillColor, fillAlpha) { return this.displayList.add(new Rectangle(this.scene, x, y, width, height, fillColor, fillAlpha)) }) }, function(module, exports, __webpack_require__) { var Star = __webpack_require__(369); var GameObjectFactory = __webpack_require__(5); GameObjectFactory.register("star", function(x, y, points, innerRadius, outerRadius, fillColor, fillAlpha) { return this.displayList.add(new Star(this.scene, x, y, points, innerRadius, outerRadius, fillColor, fillAlpha)) }) }, function(module, exports, __webpack_require__) { var GameObjectFactory = __webpack_require__(5); var Triangle = __webpack_require__(370); GameObjectFactory.register("triangle", function(x, y, x1, y1, x2, y2, x3, y3, fillColor, fillAlpha) { return this.displayList.add(new Triangle(this.scene, x, y, x1, y1, x2, y2, x3, y3, fillColor, fillAlpha)) }) }, function(module, exports, __webpack_require__) { var Blitter = __webpack_require__(179); var BuildGameObject = __webpack_require__(29); var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(13); GameObjectCreator.register("blitter", function(config, addToScene) { if (config === undefined) { config = {} } var key = GetAdvancedValue(config, "key", null); var frame = GetAdvancedValue(config, "frame", null); var blitter = new Blitter(this.scene, 0, 0, key, frame); if (addToScene !== undefined) { config.add = addToScene } BuildGameObject(this.scene, blitter, config); return blitter }) }, function(module, exports, __webpack_require__) { var BuildGameObject = __webpack_require__(29); var Container = __webpack_require__(180); var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(13); GameObjectCreator.register("container", function(config, addToScene) { if (config === undefined) { config = {} } var x = GetAdvancedValue(config, "x", 0); var y = GetAdvancedValue(config, "y", 0); var container = new Container(this.scene, x, y); if (addToScene !== undefined) { config.add = addToScene } BuildGameObject(this.scene, container, config); return container }) }, function(module, exports, __webpack_require__) { var BitmapText = __webpack_require__(181); var BuildGameObject = __webpack_require__(29); var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(13); GameObjectCreator.register("dynamicBitmapText", function(config, addToScene) { if (config === undefined) { config = {} } var font = GetAdvancedValue(config, "font", ""); var text = GetAdvancedValue(config, "text", ""); var size = GetAdvancedValue(config, "size", false); var bitmapText = new BitmapText(this.scene, 0, 0, font, text, size); if (addToScene !== undefined) { config.add = addToScene } BuildGameObject(this.scene, bitmapText, config); return bitmapText }) }, function(module, exports, __webpack_require__) { var GameObjectCreator = __webpack_require__(16); var Graphics = __webpack_require__(182); GameObjectCreator.register("graphics", function(config, addToScene) { if (config === undefined) { config = {} } if (addToScene !== undefined) { config.add = addToScene } var graphics = new Graphics(this.scene, config); if (config.add) { this.scene.sys.displayList.add(graphics) } return graphics }) }, function(module, exports, __webpack_require__) { var GameObjectCreator = __webpack_require__(16); var Group = __webpack_require__(96); GameObjectCreator.register("group", function(config) { return new Group(this.scene, null, config) }) }, function(module, exports, __webpack_require__) { var BuildGameObject = __webpack_require__(29); var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(13); var Image = __webpack_require__(82); GameObjectCreator.register("image", function(config, addToScene) { if (config === undefined) { config = {} } var key = GetAdvancedValue(config, "key", null); var frame = GetAdvancedValue(config, "frame", null); var image = new Image(this.scene, 0, 0, key, frame); if (addToScene !== undefined) { config.add = addToScene } BuildGameObject(this.scene, image, config); return image }) }, function(module, exports, __webpack_require__) { var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(13); var GetFastValue = __webpack_require__(1); var ParticleEmitterManager = __webpack_require__(185); GameObjectCreator.register("particles", function(config, addToScene) { if (config === undefined) { config = {} } var key = GetAdvancedValue(config, "key", null); var frame = GetAdvancedValue(config, "frame", null); var emitters = GetFastValue(config, "emitters", null); var manager = new ParticleEmitterManager(this.scene, key, frame, emitters); if (addToScene !== undefined) { config.add = addToScene } var add = GetFastValue(config, "add", false); if (add) { this.displayList.add(manager) } this.updateList.add(manager); return manager }) }, function(module, exports, __webpack_require__) { var BuildGameObject = __webpack_require__(29); var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(13); var RenderTexture = __webpack_require__(186); GameObjectCreator.register("renderTexture", function(config, addToScene) { if (config === undefined) { config = {} } var x = GetAdvancedValue(config, "x", 0); var y = GetAdvancedValue(config, "y", 0); var width = GetAdvancedValue(config, "width", 32); var height = GetAdvancedValue(config, "height", 32); var renderTexture = new RenderTexture(this.scene, x, y, width, height); if (addToScene !== undefined) { config.add = addToScene } BuildGameObject(this.scene, renderTexture, config); return renderTexture }) }, function(module, exports, __webpack_require__) { var BuildGameObject = __webpack_require__(29); var BuildGameObjectAnimation = __webpack_require__(178); var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(13); var Sprite = __webpack_require__(50); GameObjectCreator.register("sprite", function(config, addToScene) { if (config === undefined) { config = {} } var key = GetAdvancedValue(config, "key", null); var frame = GetAdvancedValue(config, "frame", null); var sprite = new Sprite(this.scene, 0, 0, key, frame); if (addToScene !== undefined) { config.add = addToScene } BuildGameObject(this.scene, sprite, config); BuildGameObjectAnimation(sprite, config); return sprite }) }, function(module, exports, __webpack_require__) { var BitmapText = __webpack_require__(124); var BuildGameObject = __webpack_require__(29); var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(13); var GetValue = __webpack_require__(4); GameObjectCreator.register("bitmapText", function(config, addToScene) { if (config === undefined) { config = {} } var font = GetValue(config, "font", ""); var text = GetAdvancedValue(config, "text", ""); var size = GetAdvancedValue(config, "size", false); var align = GetValue(config, "align", 0); var bitmapText = new BitmapText(this.scene, 0, 0, font, text, size, align); if (addToScene !== undefined) { config.add = addToScene } BuildGameObject(this.scene, bitmapText, config); return bitmapText }) }, function(module, exports, __webpack_require__) { var BuildGameObject = __webpack_require__(29); var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(13); var Text = __webpack_require__(187); GameObjectCreator.register("text", function(config, addToScene) { if (config === undefined) { config = {} } var content = GetAdvancedValue(config, "text", ""); var style = GetAdvancedValue(config, "style", null); var padding = GetAdvancedValue(config, "padding", null); if (padding !== null) { style.padding = padding } var text = new Text(this.scene, 0, 0, content, style); if (addToScene !== undefined) { config.add = addToScene } BuildGameObject(this.scene, text, config); text.autoRound = GetAdvancedValue(config, "autoRound", true); text.resolution = GetAdvancedValue(config, "resolution", 1); return text }) }, function(module, exports, __webpack_require__) { var BuildGameObject = __webpack_require__(29); var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(13); var TileSprite = __webpack_require__(188); GameObjectCreator.register("tileSprite", function(config, addToScene) { if (config === undefined) { config = {} } var x = GetAdvancedValue(config, "x", 0); var y = GetAdvancedValue(config, "y", 0); var width = GetAdvancedValue(config, "width", 512); var height = GetAdvancedValue(config, "height", 512); var key = GetAdvancedValue(config, "key", ""); var frame = GetAdvancedValue(config, "frame", ""); var tile = new TileSprite(this.scene, x, y, width, height, key, frame); if (addToScene !== undefined) { config.add = addToScene } BuildGameObject(this.scene, tile, config); return tile }) }, function(module, exports, __webpack_require__) { var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(13); var Zone = __webpack_require__(107); GameObjectCreator.register("zone", function(config) { var x = GetAdvancedValue(config, "x", 0); var y = GetAdvancedValue(config, "y", 0); var width = GetAdvancedValue(config, "width", 1); var height = GetAdvancedValue(config, "height", width); return new Zone(this.scene, x, y, width, height) }) }, function(module, exports, __webpack_require__) { var renderWebGL = __webpack_require__(2); var renderCanvas = __webpack_require__(2); if (true) { renderWebGL = __webpack_require__(374) } if (true) { renderCanvas = __webpack_require__(374) } module.exports = { renderWebGL: renderWebGL, renderCanvas: renderCanvas } }, function(module, exports) { module.exports = ["normal", "multiply", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light", "difference", "exclusion", "hue", "saturation", "color", "luminosity"] }, function(module, exports, __webpack_require__) { var DOMElement = __webpack_require__(373); var GameObjectFactory = __webpack_require__(5); GameObjectFactory.register("dom", function(x, y, element) { return this.displayList.add(new DOMElement(this.scene, x, y, element)) }) }, function(module, exports, __webpack_require__) { var renderWebGL = __webpack_require__(2); var renderCanvas = __webpack_require__(2); if (true) { renderWebGL = __webpack_require__(813) } if (true) { renderCanvas = __webpack_require__(814) } module.exports = { renderWebGL: renderWebGL, renderCanvas: renderCanvas } }, function(module, exports, __webpack_require__) { var Utils = __webpack_require__(10); var MeshWebGLRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix) { var pipeline = this.pipeline; renderer.setPipeline(pipeline, src); var camMatrix = pipeline._tempMatrix1; var spriteMatrix = pipeline._tempMatrix2; var calcMatrix = pipeline._tempMatrix3; spriteMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); camMatrix.copyFrom(camera.matrix); if (parentMatrix) { camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); spriteMatrix.e = src.x; spriteMatrix.f = src.y; camMatrix.multiply(spriteMatrix, calcMatrix) } else { spriteMatrix.e -= camera.scrollX * src.scrollFactorX; spriteMatrix.f -= camera.scrollY * src.scrollFactorY; camMatrix.multiply(spriteMatrix, calcMatrix) } var frame = src.frame; var texture = frame.glTexture; var vertices = src.vertices; var uvs = src.uv; var colors = src.colors; var alphas = src.alphas; var meshVerticesLength = vertices.length; var vertexCount = Math.floor(meshVerticesLength * .5); if (pipeline.vertexCount + vertexCount >= pipeline.vertexCapacity) { pipeline.flush() } pipeline.setTexture2D(texture, 0); var vertexViewF32 = pipeline.vertexViewF32; var vertexViewU32 = pipeline.vertexViewU32; var vertexOffset = pipeline.vertexCount * pipeline.vertexComponentCount - 1; var colorIndex = 0; var tintEffect = src.tintFill; for (var i = 0; i < meshVerticesLength; i += 2) { var x = vertices[i + 0]; var y = vertices[i + 1]; var tx = x * calcMatrix.a + y * calcMatrix.c + calcMatrix.e; var ty = x * calcMatrix.b + y * calcMatrix.d + calcMatrix.f; if (camera.roundPixels) { tx |= 0; ty |= 0 } vertexViewF32[++vertexOffset] = tx; vertexViewF32[++vertexOffset] = ty; vertexViewF32[++vertexOffset] = uvs[i + 0]; vertexViewF32[++vertexOffset] = uvs[i + 1]; vertexViewF32[++vertexOffset] = tintEffect; vertexViewU32[++vertexOffset] = Utils.getTintAppendFloatAlpha(colors[colorIndex], camera.alpha * alphas[colorIndex]); colorIndex++ } pipeline.vertexCount += vertexCount }; module.exports = MeshWebGLRenderer }, function(module, exports) { var MeshCanvasRenderer = function() {}; module.exports = MeshCanvasRenderer }, function(module, exports, __webpack_require__) { var Mesh = __webpack_require__(126); var GameObjectFactory = __webpack_require__(5); if (true) { GameObjectFactory.register("mesh", function(x, y, vertices, uv, colors, alphas, texture, frame) { return this.displayList.add(new Mesh(this.scene, x, y, vertices, uv, colors, alphas, texture, frame)) }) } }, function(module, exports, __webpack_require__) { var Quad = __webpack_require__(191); var GameObjectFactory = __webpack_require__(5); if (true) { GameObjectFactory.register("quad", function(x, y, key, frame) { return this.displayList.add(new Quad(this.scene, x, y, key, frame)) }) } }, function(module, exports, __webpack_require__) { var BuildGameObject = __webpack_require__(29); var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(13); var GetValue = __webpack_require__(4); var Mesh = __webpack_require__(126); GameObjectCreator.register("mesh", function(config, addToScene) { if (config === undefined) { config = {} } var key = GetAdvancedValue(config, "key", null); var frame = GetAdvancedValue(config, "frame", null); var vertices = GetValue(config, "vertices", []); var colors = GetValue(config, "colors", []); var alphas = GetValue(config, "alphas", []); var uv = GetValue(config, "uv", []); var mesh = new Mesh(this.scene, 0, 0, vertices, uv, colors, alphas, key, frame); if (addToScene !== undefined) { config.add = addToScene } BuildGameObject(this.scene, mesh, config); return mesh }) }, function(module, exports, __webpack_require__) { var BuildGameObject = __webpack_require__(29); var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(13); var Quad = __webpack_require__(191); GameObjectCreator.register("quad", function(config, addToScene) { if (config === undefined) { config = {} } var x = GetAdvancedValue(config, "x", 0); var y = GetAdvancedValue(config, "y", 0); var key = GetAdvancedValue(config, "key", null); var frame = GetAdvancedValue(config, "frame", null); var quad = new Quad(this.scene, x, y, key, frame); if (addToScene !== undefined) { config.add = addToScene } BuildGameObject(this.scene, quad, config); return quad }) }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var LightsManager = __webpack_require__(376); var PluginCache = __webpack_require__(15); var LightsPlugin = new Class({ Extends: LightsManager, initialize: function LightsPlugin(scene) { this.scene = scene; this.systems = scene.sys; if (!scene.sys.settings.isBooted) { scene.sys.events.once("boot", this.boot, this) } LightsManager.call(this) }, boot: function() { var eventEmitter = this.systems.events; eventEmitter.on("shutdown", this.shutdown, this); eventEmitter.on("destroy", this.destroy, this) }, destroy: function() { this.shutdown(); this.scene = undefined; this.systems = undefined } }); PluginCache.register("LightsPlugin", LightsPlugin, "lights"); module.exports = LightsPlugin }, function(module, exports, __webpack_require__) { var Circle = __webpack_require__(78); Circle.Area = __webpack_require__(821); Circle.Circumference = __webpack_require__(240); Circle.CircumferencePoint = __webpack_require__(144); Circle.Clone = __webpack_require__(822); Circle.Contains = __webpack_require__(46); Circle.ContainsPoint = __webpack_require__(823); Circle.ContainsRect = __webpack_require__(824); Circle.CopyFrom = __webpack_require__(825); Circle.Equals = __webpack_require__(826); Circle.GetBounds = __webpack_require__(827); Circle.GetPoint = __webpack_require__(237); Circle.GetPoints = __webpack_require__(239); Circle.Offset = __webpack_require__(828); Circle.OffsetPoint = __webpack_require__(829); Circle.Random = __webpack_require__(145); module.exports = Circle }, function(module, exports) { var Area = function(circle) { return circle.radius > 0 ? Math.PI * circle.radius * circle.radius : 0 }; module.exports = Area }, function(module, exports, __webpack_require__) { var Circle = __webpack_require__(78); var Clone = function(source) { return new Circle(source.x, source.y, source.radius) }; module.exports = Clone }, function(module, exports, __webpack_require__) { var Contains = __webpack_require__(46); var ContainsPoint = function(circle, point) { return Contains(circle, point.x, point.y) }; module.exports = ContainsPoint }, function(module, exports, __webpack_require__) { var Contains = __webpack_require__(46); var ContainsRect = function(circle, rect) { return Contains(circle, rect.x, rect.y) && Contains(circle, rect.right, rect.y) && Contains(circle, rect.x, rect.bottom) && Contains(circle, rect.right, rect.bottom) }; module.exports = ContainsRect }, function(module, exports) { var CopyFrom = function(source, dest) { return dest.setTo(source.x, source.y, source.radius) }; module.exports = CopyFrom }, function(module, exports) { var Equals = function(circle, toCompare) { return circle.x === toCompare.x && circle.y === toCompare.y && circle.radius === toCompare.radius }; module.exports = Equals }, function(module, exports, __webpack_require__) { var Rectangle = __webpack_require__(9); var GetBounds = function(circle, out) { if (out === undefined) { out = new Rectangle } out.x = circle.left; out.y = circle.top; out.width = circle.diameter; out.height = circle.diameter; return out }; module.exports = GetBounds }, function(module, exports) { var Offset = function(circle, x, y) { circle.x += x; circle.y += y; return circle }; module.exports = Offset }, function(module, exports) { var OffsetPoint = function(circle, point) { circle.x += point.x; circle.y += point.y; return circle }; module.exports = OffsetPoint }, function(module, exports, __webpack_require__) { var Ellipse = __webpack_require__(94); Ellipse.Area = __webpack_require__(831); Ellipse.Circumference = __webpack_require__(343); Ellipse.CircumferencePoint = __webpack_require__(184); Ellipse.Clone = __webpack_require__(832); Ellipse.Contains = __webpack_require__(95); Ellipse.ContainsPoint = __webpack_require__(833); Ellipse.ContainsRect = __webpack_require__(834); Ellipse.CopyFrom = __webpack_require__(835); Ellipse.Equals = __webpack_require__(836); Ellipse.GetBounds = __webpack_require__(837); Ellipse.GetPoint = __webpack_require__(341); Ellipse.GetPoints = __webpack_require__(342); Ellipse.Offset = __webpack_require__(838); Ellipse.OffsetPoint = __webpack_require__(839); Ellipse.Random = __webpack_require__(152); module.exports = Ellipse }, function(module, exports) { var Area = function(ellipse) { if (ellipse.isEmpty()) { return 0 } return ellipse.getMajorRadius() * ellipse.getMinorRadius() * Math.PI }; module.exports = Area }, function(module, exports, __webpack_require__) { var Ellipse = __webpack_require__(94); var Clone = function(source) { return new Ellipse(source.x, source.y, source.width, source.height) }; module.exports = Clone }, function(module, exports, __webpack_require__) { var Contains = __webpack_require__(95); var ContainsPoint = function(ellipse, point) { return Contains(ellipse, point.x, point.y) }; module.exports = ContainsPoint }, function(module, exports, __webpack_require__) { var Contains = __webpack_require__(95); var ContainsRect = function(ellipse, rect) { return Contains(ellipse, rect.x, rect.y) && Contains(ellipse, rect.right, rect.y) && Contains(ellipse, rect.x, rect.bottom) && Contains(ellipse, rect.right, rect.bottom) }; module.exports = ContainsRect }, function(module, exports) { var CopyFrom = function(source, dest) { return dest.setTo(source.x, source.y, source.width, source.height) }; module.exports = CopyFrom }, function(module, exports) { var Equals = function(ellipse, toCompare) { return ellipse.x === toCompare.x && ellipse.y === toCompare.y && ellipse.width === toCompare.width && ellipse.height === toCompare.height }; module.exports = Equals }, function(module, exports, __webpack_require__) { var Rectangle = __webpack_require__(9); var GetBounds = function(ellipse, out) { if (out === undefined) { out = new Rectangle } out.x = ellipse.left; out.y = ellipse.top; out.width = ellipse.width; out.height = ellipse.height; return out }; module.exports = GetBounds }, function(module, exports) { var Offset = function(ellipse, x, y) { ellipse.x += x; ellipse.y += y; return ellipse }; module.exports = Offset }, function(module, exports) { var OffsetPoint = function(ellipse, point) { ellipse.x += point.x; ellipse.y += point.y; return ellipse }; module.exports = OffsetPoint }, function(module, exports, __webpack_require__) { var DistanceBetween = __webpack_require__(56); var CircleToCircle = function(circleA, circleB) { return DistanceBetween(circleA.x, circleA.y, circleB.x, circleB.y) <= circleA.radius + circleB.radius }; module.exports = CircleToCircle }, function(module, exports) { var CircleToRectangle = function(circle, rect) { var halfWidth = rect.width / 2; var halfHeight = rect.height / 2; var cx = Math.abs(circle.x - rect.x - halfWidth); var cy = Math.abs(circle.y - rect.y - halfHeight); var xDist = halfWidth + circle.radius; var yDist = halfHeight + circle.radius; if (cx > xDist || cy > yDist) { return false } else if (cx <= halfWidth || cy <= halfHeight) { return true } else { var xCornerDist = cx - halfWidth; var yCornerDist = cy - halfHeight; var xCornerDistSq = xCornerDist * xCornerDist; var yCornerDistSq = yCornerDist * yCornerDist; var maxCornerDistSq = circle.radius * circle.radius; return xCornerDistSq + yCornerDistSq <= maxCornerDistSq } }; module.exports = CircleToRectangle }, function(module, exports, __webpack_require__) { var Rectangle = __webpack_require__(9); var RectangleToRectangle = __webpack_require__(192); var GetRectangleIntersection = function(rectA, rectB, output) { if (output === undefined) { output = new Rectangle } if (RectangleToRectangle(rectA, rectB)) { output.x = Math.max(rectA.x, rectB.x); output.y = Math.max(rectA.y, rectB.y); output.width = Math.min(rectA.right, rectB.right) - output.x; output.height = Math.min(rectA.bottom, rectB.bottom) - output.y } return output }; module.exports = GetRectangleIntersection }, function(module, exports) { var LineToRectangle = function(line, rect) { var x1 = line.x1; var y1 = line.y1; var x2 = line.x2; var y2 = line.y2; var bx1 = rect.x; var by1 = rect.y; var bx2 = rect.right; var by2 = rect.bottom; var t = 0; if (x1 >= bx1 && x1 <= bx2 && y1 >= by1 && y1 <= by2 || x2 >= bx1 && x2 <= bx2 && y2 >= by1 && y2 <= by2) { return true } if (x1 < bx1 && x2 >= bx1) { t = y1 + (y2 - y1) * (bx1 - x1) / (x2 - x1); if (t > by1 && t <= by2) { return true } } else if (x1 > bx2 && x2 <= bx2) { t = y1 + (y2 - y1) * (bx2 - x1) / (x2 - x1); if (t >= by1 && t <= by2) { return true } } if (y1 < by1 && y2 >= by1) { t = x1 + (x2 - x1) * (by1 - y1) / (y2 - y1); if (t >= bx1 && t <= bx2) { return true } } else if (y1 > by2 && y2 <= by2) { t = x1 + (x2 - x1) * (by2 - y1) / (y2 - y1); if (t >= bx1 && t <= bx2) { return true } } return false }; module.exports = LineToRectangle }, function(module, exports, __webpack_require__) { var PointToLine = __webpack_require__(380); var PointToLineSegment = function(point, line) { if (!PointToLine(point, line)) { return false } var xMin = Math.min(line.x1, line.x2); var xMax = Math.max(line.x1, line.x2); var yMin = Math.min(line.y1, line.y2); var yMax = Math.max(line.y1, line.y2); return point.x >= xMin && point.x <= xMax && (point.y >= yMin && point.y <= yMax) }; module.exports = PointToLineSegment }, function(module, exports, __webpack_require__) { var LineToLine = __webpack_require__(127); var Contains = __webpack_require__(47); var ContainsArray = __webpack_require__(193); var Decompose = __webpack_require__(381); var RectangleToTriangle = function(rect, triangle) { if (triangle.left > rect.right || triangle.right < rect.left || triangle.top > rect.bottom || triangle.bottom < rect.top) { return false } var triA = triangle.getLineA(); var triB = triangle.getLineB(); var triC = triangle.getLineC(); if (Contains(rect, triA.x1, triA.y1) || Contains(rect, triA.x2, triA.y2)) { return true } if (Contains(rect, triB.x1, triB.y1) || Contains(rect, triB.x2, triB.y2)) { return true } if (Contains(rect, triC.x1, triC.y1) || Contains(rect, triC.x2, triC.y2)) { return true } var rectA = rect.getLineA(); var rectB = rect.getLineB(); var rectC = rect.getLineC(); var rectD = rect.getLineD(); if (LineToLine(triA, rectA) || LineToLine(triA, rectB) || LineToLine(triA, rectC) || LineToLine(triA, rectD)) { return true } if (LineToLine(triB, rectA) || LineToLine(triB, rectB) || LineToLine(triB, rectC) || LineToLine(triB, rectD)) { return true } if (LineToLine(triC, rectA) || LineToLine(triC, rectB) || LineToLine(triC, rectC) || LineToLine(triC, rectD)) { return true } var points = Decompose(rect); var within = ContainsArray(triangle, points, true); return within.length > 0 }; module.exports = RectangleToTriangle }, function(module, exports) { var RectangleToValues = function(rect, left, right, top, bottom, tolerance) { if (tolerance === undefined) { tolerance = 0 } return !(left > rect.right + tolerance || right < rect.left - tolerance || top > rect.bottom + tolerance || bottom < rect.top - tolerance) }; module.exports = RectangleToValues }, function(module, exports, __webpack_require__) { var LineToCircle = __webpack_require__(379); var Contains = __webpack_require__(84); var TriangleToCircle = function(triangle, circle) { if (triangle.left > circle.right || triangle.right < circle.left || triangle.top > circle.bottom || triangle.bottom < circle.top) { return false } if (Contains(triangle, circle.x, circle.y)) { return true } if (LineToCircle(triangle.getLineA(), circle)) { return true } if (LineToCircle(triangle.getLineB(), circle)) { return true } if (LineToCircle(triangle.getLineC(), circle)) { return true } return false }; module.exports = TriangleToCircle }, function(module, exports, __webpack_require__) { var Contains = __webpack_require__(84); var LineToLine = __webpack_require__(127); var TriangleToLine = function(triangle, line) { if (Contains(triangle, line.getPointA()) || Contains(triangle, line.getPointB())) { return true } if (LineToLine(triangle.getLineA(), line)) { return true } if (LineToLine(triangle.getLineB(), line)) { return true } if (LineToLine(triangle.getLineC(), line)) { return true } return false }; module.exports = TriangleToLine }, function(module, exports, __webpack_require__) { var ContainsArray = __webpack_require__(193); var Decompose = __webpack_require__(382); var LineToLine = __webpack_require__(127); var TriangleToTriangle = function(triangleA, triangleB) { if (triangleA.left > triangleB.right || triangleA.right < triangleB.left || triangleA.top > triangleB.bottom || triangleA.bottom < triangleB.top) { return false } var lineAA = triangleA.getLineA(); var lineAB = triangleA.getLineB(); var lineAC = triangleA.getLineC(); var lineBA = triangleB.getLineA(); var lineBB = triangleB.getLineB(); var lineBC = triangleB.getLineC(); if (LineToLine(lineAA, lineBA) || LineToLine(lineAA, lineBB) || LineToLine(lineAA, lineBC)) { return true } if (LineToLine(lineAB, lineBA) || LineToLine(lineAB, lineBB) || LineToLine(lineAB, lineBC)) { return true } if (LineToLine(lineAC, lineBA) || LineToLine(lineAC, lineBB) || LineToLine(lineAC, lineBC)) { return true } var points = Decompose(triangleA); var within = ContainsArray(triangleB, points, true); if (within.length > 0) { return true } points = Decompose(triangleB); within = ContainsArray(triangleA, points, true); if (within.length > 0) { return true } return false }; module.exports = TriangleToTriangle }, function(module, exports, __webpack_require__) { var Line = __webpack_require__(54); Line.Angle = __webpack_require__(85); Line.BresenhamPoints = __webpack_require__(258); Line.CenterOn = __webpack_require__(851); Line.Clone = __webpack_require__(852); Line.CopyFrom = __webpack_require__(853); Line.Equals = __webpack_require__(854); Line.GetMidPoint = __webpack_require__(855); Line.GetNormal = __webpack_require__(856); Line.GetPoint = __webpack_require__(246); Line.GetPoints = __webpack_require__(147); Line.Height = __webpack_require__(857); Line.Length = __webpack_require__(62); Line.NormalAngle = __webpack_require__(383); Line.NormalX = __webpack_require__(858); Line.NormalY = __webpack_require__(859); Line.Offset = __webpack_require__(860); Line.PerpSlope = __webpack_require__(861); Line.Random = __webpack_require__(148); Line.ReflectAngle = __webpack_require__(862); Line.Rotate = __webpack_require__(863); Line.RotateAroundPoint = __webpack_require__(864); Line.RotateAroundXY = __webpack_require__(194); Line.SetToAngle = __webpack_require__(865); Line.Slope = __webpack_require__(866); Line.Width = __webpack_require__(867); module.exports = Line }, function(module, exports) { var CenterOn = function(line, x, y) { var tx = x - (line.x1 + line.x2) / 2; var ty = y - (line.y1 + line.y2) / 2; line.x1 += tx; line.y1 += ty; line.x2 += tx; line.y2 += ty; return line }; module.exports = CenterOn }, function(module, exports, __webpack_require__) { var Line = __webpack_require__(54); var Clone = function(source) { return new Line(source.x1, source.y1, source.x2, source.y2) }; module.exports = Clone }, function(module, exports) { var CopyFrom = function(source, dest) { return dest.setTo(source.x1, source.y1, source.x2, source.y2) }; module.exports = CopyFrom }, function(module, exports) { var Equals = function(line, toCompare) { return line.x1 === toCompare.x1 && line.y1 === toCompare.y1 && line.x2 === toCompare.x2 && line.y2 === toCompare.y2 }; module.exports = Equals }, function(module, exports, __webpack_require__) { var Point = __webpack_require__(6); var GetMidPoint = function(line, out) { if (out === undefined) { out = new Point } out.x = (line.x1 + line.x2) / 2; out.y = (line.y1 + line.y2) / 2; return out }; module.exports = GetMidPoint }, function(module, exports, __webpack_require__) { var MATH_CONST = __webpack_require__(18); var Angle = __webpack_require__(85); var Point = __webpack_require__(6); var GetNormal = function(line, out) { if (out === undefined) { out = new Point } var a = Angle(line) - MATH_CONST.TAU; out.x = Math.cos(a); out.y = Math.sin(a); return out }; module.exports = GetNormal }, function(module, exports) { var Height = function(line) { return Math.abs(line.y1 - line.y2) }; module.exports = Height }, function(module, exports, __webpack_require__) { var MATH_CONST = __webpack_require__(18); var Angle = __webpack_require__(85); var NormalX = function(line) { return Math.cos(Angle(line) - MATH_CONST.TAU) }; module.exports = NormalX }, function(module, exports, __webpack_require__) { var MATH_CONST = __webpack_require__(18); var Angle = __webpack_require__(85); var NormalY = function(line) { return Math.sin(Angle(line) - MATH_CONST.TAU) }; module.exports = NormalY }, function(module, exports) { var Offset = function(line, x, y) { line.x1 += x; line.y1 += y; line.x2 += x; line.y2 += y; return line }; module.exports = Offset }, function(module, exports) { var PerpSlope = function(line) { return -((line.x2 - line.x1) / (line.y2 - line.y1)) }; module.exports = PerpSlope }, function(module, exports, __webpack_require__) { var Angle = __webpack_require__(85); var NormalAngle = __webpack_require__(383); var ReflectAngle = function(lineA, lineB) { return 2 * NormalAngle(lineB) - Math.PI - Angle(lineA) }; module.exports = ReflectAngle }, function(module, exports, __webpack_require__) { var RotateAroundXY = __webpack_require__(194); var Rotate = function(line, angle) { var x = (line.x1 + line.x2) / 2; var y = (line.y1 + line.y2) / 2; return RotateAroundXY(line, x, y, angle) }; module.exports = Rotate }, function(module, exports, __webpack_require__) { var RotateAroundXY = __webpack_require__(194); var RotateAroundPoint = function(line, point, angle) { return RotateAroundXY(line, point.x, point.y, angle) }; module.exports = RotateAroundPoint }, function(module, exports) { var SetToAngle = function(line, x, y, angle, length) { line.x1 = x; line.y1 = y; line.x2 = x + Math.cos(angle) * length; line.y2 = y + Math.sin(angle) * length; return line }; module.exports = SetToAngle }, function(module, exports) { var Slope = function(line) { return (line.y2 - line.y1) / (line.x2 - line.x1) }; module.exports = Slope }, function(module, exports) { var Width = function(line) { return Math.abs(line.x1 - line.x2) }; module.exports = Width }, function(module, exports, __webpack_require__) { var Point = __webpack_require__(6); Point.Ceil = __webpack_require__(869); Point.Clone = __webpack_require__(870); Point.CopyFrom = __webpack_require__(871); Point.Equals = __webpack_require__(872); Point.Floor = __webpack_require__(873); Point.GetCentroid = __webpack_require__(874); Point.GetMagnitude = __webpack_require__(384); Point.GetMagnitudeSq = __webpack_require__(385); Point.GetRectangleFromPoints = __webpack_require__(875); Point.Interpolate = __webpack_require__(876); Point.Invert = __webpack_require__(877); Point.Negative = __webpack_require__(878); Point.Project = __webpack_require__(879); Point.ProjectUnit = __webpack_require__(880); Point.SetMagnitude = __webpack_require__(881); module.exports = Point }, function(module, exports) { var Ceil = function(point) { return point.setTo(Math.ceil(point.x), Math.ceil(point.y)) }; module.exports = Ceil }, function(module, exports, __webpack_require__) { var Point = __webpack_require__(6); var Clone = function(source) { return new Point(source.x, source.y) }; module.exports = Clone }, function(module, exports) { var CopyFrom = function(source, dest) { return dest.setTo(source.x, source.y) }; module.exports = CopyFrom }, function(module, exports) { var Equals = function(point, toCompare) { return point.x === toCompare.x && point.y === toCompare.y }; module.exports = Equals }, function(module, exports) { var Floor = function(point) { return point.setTo(Math.floor(point.x), Math.floor(point.y)) }; module.exports = Floor }, function(module, exports, __webpack_require__) { var Point = __webpack_require__(6); var GetCentroid = function(points, out) { if (out === undefined) { out = new Point } if (!Array.isArray(points)) { throw new Error("GetCentroid points argument must be an array") } var len = points.length; if (len < 1) { throw new Error("GetCentroid points array must not be empty") } else if (len === 1) { out.x = points[0].x; out.y = points[0].y } else { for (var i = 0; i < len; i++) { out.x += points[i].x; out.y += points[i].y } out.x /= len; out.y /= len } return out }; module.exports = GetCentroid }, function(module, exports, __webpack_require__) { var Rectangle = __webpack_require__(9); var GetRectangleFromPoints = function(points, out) { if (out === undefined) { out = new Rectangle } var xMax = Number.NEGATIVE_INFINITY; var xMin = Number.POSITIVE_INFINITY; var yMax = Number.NEGATIVE_INFINITY; var yMin = Number.POSITIVE_INFINITY; for (var i = 0; i < points.length; i++) { var point = points[i]; if (point.x > xMax) { xMax = point.x } if (point.x < xMin) { xMin = point.x } if (point.y > yMax) { yMax = point.y } if (point.y < yMin) { yMin = point.y } } out.x = xMin; out.y = yMin; out.width = xMax - xMin; out.height = yMax - yMin; return out }; module.exports = GetRectangleFromPoints }, function(module, exports, __webpack_require__) { var Point = __webpack_require__(6); var Interpolate = function(pointA, pointB, t, out) { if (t === undefined) { t = 0 } if (out === undefined) { out = new Point } out.x = pointA.x + (pointB.x - pointA.x) * t; out.y = pointA.y + (pointB.y - pointA.y) * t; return out }; module.exports = Interpolate }, function(module, exports) { var Invert = function(point) { return point.setTo(point.y, point.x) }; module.exports = Invert }, function(module, exports, __webpack_require__) { var Point = __webpack_require__(6); var Negative = function(point, out) { if (out === undefined) { out = new Point } return out.setTo(-point.x, -point.y) }; module.exports = Negative }, function(module, exports, __webpack_require__) { var Point = __webpack_require__(6); var GetMagnitudeSq = __webpack_require__(385); var Project = function(pointA, pointB, out) { if (out === undefined) { out = new Point } var dot = pointA.x * pointB.x + pointA.y * pointB.y; var amt = dot / GetMagnitudeSq(pointB); if (amt !== 0) { out.x = amt * pointB.x; out.y = amt * pointB.y } return out }; module.exports = Project }, function(module, exports, __webpack_require__) { var Point = __webpack_require__(6); var ProjectUnit = function(pointA, pointB, out) { if (out === undefined) { out = new Point } var amt = pointA.x * pointB.x + pointA.y * pointB.y; if (amt !== 0) { out.x = amt * pointB.x; out.y = amt * pointB.y } return out }; module.exports = ProjectUnit }, function(module, exports, __webpack_require__) { var GetMagnitude = __webpack_require__(384); var SetMagnitude = function(point, magnitude) { if (point.x !== 0 || point.y !== 0) { var m = GetMagnitude(point); point.x /= m; point.y /= m } point.x *= magnitude; point.y *= magnitude; return point }; module.exports = SetMagnitude }, function(module, exports, __webpack_require__) { var Polygon = __webpack_require__(189); Polygon.Clone = __webpack_require__(883); Polygon.Contains = __webpack_require__(190); Polygon.ContainsPoint = __webpack_require__(884); Polygon.GetAABB = __webpack_require__(364); Polygon.GetNumberArray = __webpack_require__(885); Polygon.GetPoints = __webpack_require__(365); Polygon.Perimeter = __webpack_require__(366); Polygon.Reverse = __webpack_require__(886); Polygon.Smooth = __webpack_require__(367); module.exports = Polygon }, function(module, exports, __webpack_require__) { var Polygon = __webpack_require__(189); var Clone = function(polygon) { return new Polygon(polygon.points) }; module.exports = Clone }, function(module, exports, __webpack_require__) { var Contains = __webpack_require__(190); var ContainsPoint = function(polygon, point) { return Contains(polygon, point.x, point.y) }; module.exports = ContainsPoint }, function(module, exports) { var GetNumberArray = function(polygon, output) { if (output === undefined) { output = [] } for (var i = 0; i < polygon.points.length; i++) { output.push(polygon.points[i].x); output.push(polygon.points[i].y) } return output }; module.exports = GetNumberArray }, function(module, exports) { var Reverse = function(polygon) { polygon.points.reverse(); return polygon }; module.exports = Reverse }, function(module, exports) { var Area = function(rect) { return rect.width * rect.height }; module.exports = Area }, function(module, exports) { var Ceil = function(rect) { rect.x = Math.ceil(rect.x); rect.y = Math.ceil(rect.y); return rect }; module.exports = Ceil }, function(module, exports) { var CeilAll = function(rect) { rect.x = Math.ceil(rect.x); rect.y = Math.ceil(rect.y); rect.width = Math.ceil(rect.width); rect.height = Math.ceil(rect.height); return rect }; module.exports = CeilAll }, function(module, exports, __webpack_require__) { var Rectangle = __webpack_require__(9); var Clone = function(source) { return new Rectangle(source.x, source.y, source.width, source.height) }; module.exports = Clone }, function(module, exports, __webpack_require__) { var Contains = __webpack_require__(47); var ContainsPoint = function(rect, point) { return Contains(rect, point.x, point.y) }; module.exports = ContainsPoint }, function(module, exports) { var CopyFrom = function(source, dest) { return dest.setTo(source.x, source.y, source.width, source.height) }; module.exports = CopyFrom }, function(module, exports) { var Equals = function(rect, toCompare) { return rect.x === toCompare.x && rect.y === toCompare.y && rect.width === toCompare.width && rect.height === toCompare.height }; module.exports = Equals }, function(module, exports, __webpack_require__) { var GetAspectRatio = __webpack_require__(195); var FitInside = function(target, source) { var ratio = GetAspectRatio(target); if (ratio < GetAspectRatio(source)) { target.setSize(source.height * ratio, source.height) } else { target.setSize(source.width, source.width / ratio) } return target.setPosition(source.centerX - target.width / 2, source.centerY - target.height / 2) }; module.exports = FitInside }, function(module, exports, __webpack_require__) { var GetAspectRatio = __webpack_require__(195); var FitOutside = function(target, source) { var ratio = GetAspectRatio(target); if (ratio > GetAspectRatio(source)) { target.setSize(source.height * ratio, source.height) } else { target.setSize(source.width, source.width / ratio) } return target.setPosition(source.centerX - target.width / 2, source.centerY - target.height / 2) }; module.exports = FitOutside }, function(module, exports) { var Floor = function(rect) { rect.x = Math.floor(rect.x); rect.y = Math.floor(rect.y); return rect }; module.exports = Floor }, function(module, exports) { var FloorAll = function(rect) { rect.x = Math.floor(rect.x); rect.y = Math.floor(rect.y); rect.width = Math.floor(rect.width); rect.height = Math.floor(rect.height); return rect }; module.exports = FloorAll }, function(module, exports, __webpack_require__) { var Point = __webpack_require__(6); var GetCenter = function(rect, out) { if (out === undefined) { out = new Point } out.x = rect.centerX; out.y = rect.centerY; return out }; module.exports = GetCenter }, function(module, exports, __webpack_require__) { var Point = __webpack_require__(6); var GetSize = function(rect, out) { if (out === undefined) { out = new Point } out.x = rect.width; out.y = rect.height; return out }; module.exports = GetSize }, function(module, exports, __webpack_require__) { var CenterOn = __webpack_require__(162); var Inflate = function(rect, x, y) { var cx = rect.centerX; var cy = rect.centerY; rect.setSize(rect.width + x * 2, rect.height + y * 2); return CenterOn(rect, cx, cy) }; module.exports = Inflate }, function(module, exports, __webpack_require__) { var Rectangle = __webpack_require__(9); var Intersects = __webpack_require__(192); var Intersection = function(rectA, rectB, out) { if (out === undefined) { out = new Rectangle } if (Intersects(rectA, rectB)) { out.x = Math.max(rectA.x, rectB.x); out.y = Math.max(rectA.y, rectB.y); out.width = Math.min(rectA.right, rectB.right) - out.x; out.height = Math.min(rectA.bottom, rectB.bottom) - out.y } else { out.setEmpty() } return out }; module.exports = Intersection }, function(module, exports) { var MergePoints = function(target, points) { var minX = target.x; var maxX = target.right; var minY = target.y; var maxY = target.bottom; for (var i = 0; i < points.length; i++) { minX = Math.min(minX, points[i].x); maxX = Math.max(maxX, points[i].x); minY = Math.min(minY, points[i].y); maxY = Math.max(maxY, points[i].y) } target.x = minX; target.y = minY; target.width = maxX - minX; target.height = maxY - minY; return target }; module.exports = MergePoints }, function(module, exports) { var MergeRect = function(target, source) { var minX = Math.min(target.x, source.x); var maxX = Math.max(target.right, source.right); target.x = minX; target.width = maxX - minX; var minY = Math.min(target.y, source.y); var maxY = Math.max(target.bottom, source.bottom); target.y = minY; target.height = maxY - minY; return target }; module.exports = MergeRect }, function(module, exports) { var MergeXY = function(target, x, y) { var minX = Math.min(target.x, x); var maxX = Math.max(target.right, x); target.x = minX; target.width = maxX - minX; var minY = Math.min(target.y, y); var maxY = Math.max(target.bottom, y); target.y = minY; target.height = maxY - minY; return target }; module.exports = MergeXY }, function(module, exports) { var Offset = function(rect, x, y) { rect.x += x; rect.y += y; return rect }; module.exports = Offset }, function(module, exports) { var OffsetPoint = function(rect, point) { rect.x += point.x; rect.y += point.y; return rect }; module.exports = OffsetPoint }, function(module, exports) { var Overlaps = function(rectA, rectB) { return rectA.x < rectB.right && rectA.right > rectB.x && rectA.y < rectB.bottom && rectA.bottom > rectB.y }; module.exports = Overlaps }, function(module, exports, __webpack_require__) { var Point = __webpack_require__(6); var DegToRad = __webpack_require__(36); var PerimeterPoint = function(rectangle, angle, out) { if (out === undefined) { out = new Point } angle = DegToRad(angle); var s = Math.sin(angle); var c = Math.cos(angle); var dx = c > 0 ? rectangle.width / 2 : rectangle.width / -2; var dy = s > 0 ? rectangle.height / 2 : rectangle.height / -2; if (Math.abs(dx * s) < Math.abs(dy * c)) { dy = dx * s / c } else { dx = dy * c / s } out.x = dx + rectangle.centerX; out.y = dy + rectangle.centerY; return out }; module.exports = PerimeterPoint }, function(module, exports, __webpack_require__) { var Between = __webpack_require__(167); var ContainsRect = __webpack_require__(387); var Point = __webpack_require__(6); var RandomOutside = function(outer, inner, out) { if (out === undefined) { out = new Point } if (ContainsRect(outer, inner)) { switch (Between(0, 3)) { case 0: out.x = outer.x + Math.random() * (inner.right - outer.x); out.y = outer.y + Math.random() * (inner.top - outer.y); break; case 1: out.x = inner.x + Math.random() * (outer.right - inner.x); out.y = inner.bottom + Math.random() * (outer.bottom - inner.bottom); break; case 2: out.x = outer.x + Math.random() * (inner.x - outer.x); out.y = inner.y + Math.random() * (outer.bottom - inner.y); break; case 3: out.x = inner.right + Math.random() * (outer.right - inner.right); out.y = outer.y + Math.random() * (inner.bottom - outer.y); break } } return out }; module.exports = RandomOutside }, function(module, exports) { var SameDimensions = function(rect, toCompare) { return rect.width === toCompare.width && rect.height === toCompare.height }; module.exports = SameDimensions }, function(module, exports) { var Scale = function(rect, x, y) { if (y === undefined) { y = x } rect.width *= x; rect.height *= y; return rect }; module.exports = Scale }, function(module, exports, __webpack_require__) { var Triangle = __webpack_require__(67); Triangle.Area = __webpack_require__(913); Triangle.BuildEquilateral = __webpack_require__(914); Triangle.BuildFromPolygon = __webpack_require__(915); Triangle.BuildRight = __webpack_require__(916); Triangle.CenterOn = __webpack_require__(917); Triangle.Centroid = __webpack_require__(388); Triangle.CircumCenter = __webpack_require__(918); Triangle.CircumCircle = __webpack_require__(919); Triangle.Clone = __webpack_require__(920); Triangle.Contains = __webpack_require__(84); Triangle.ContainsArray = __webpack_require__(193); Triangle.ContainsPoint = __webpack_require__(921); Triangle.CopyFrom = __webpack_require__(922); Triangle.Decompose = __webpack_require__(382); Triangle.Equals = __webpack_require__(923); Triangle.GetPoint = __webpack_require__(371); Triangle.GetPoints = __webpack_require__(372); Triangle.InCenter = __webpack_require__(390); Triangle.Perimeter = __webpack_require__(924); Triangle.Offset = __webpack_require__(389); Triangle.Random = __webpack_require__(153); Triangle.Rotate = __webpack_require__(925); Triangle.RotateAroundPoint = __webpack_require__(926); Triangle.RotateAroundXY = __webpack_require__(196); module.exports = Triangle }, function(module, exports) { var Area = function(triangle) { var x1 = triangle.x1; var y1 = triangle.y1; var x2 = triangle.x2; var y2 = triangle.y2; var x3 = triangle.x3; var y3 = triangle.y3; return Math.abs(((x3 - x1) * (y2 - y1) - (x2 - x1) * (y3 - y1)) / 2) }; module.exports = Area }, function(module, exports, __webpack_require__) { var Triangle = __webpack_require__(67); var BuildEquilateral = function(x, y, length) { var height = length * (Math.sqrt(3) / 2); var x1 = x; var y1 = y; var x2 = x + length / 2; var y2 = y + height; var x3 = x - length / 2; var y3 = y + height; return new Triangle(x1, y1, x2, y2, x3, y3) }; module.exports = BuildEquilateral }, function(module, exports, __webpack_require__) { var EarCut = __webpack_require__(63); var Triangle = __webpack_require__(67); var BuildFromPolygon = function(data, holes, scaleX, scaleY, out) { if (holes === undefined) { holes = null } if (scaleX === undefined) { scaleX = 1 } if (scaleY === undefined) { scaleY = 1 } if (out === undefined) { out = [] } var tris = EarCut(data, holes); var a; var b; var c; var x1; var y1; var x2; var y2; var x3; var y3; for (var i = 0; i < tris.length; i += 3) { a = tris[i]; b = tris[i + 1]; c = tris[i + 2]; x1 = data[a * 2] * scaleX; y1 = data[a * 2 + 1] * scaleY; x2 = data[b * 2] * scaleX; y2 = data[b * 2 + 1] * scaleY; x3 = data[c * 2] * scaleX; y3 = data[c * 2 + 1] * scaleY; out.push(new Triangle(x1, y1, x2, y2, x3, y3)) } return out }; module.exports = BuildFromPolygon }, function(module, exports, __webpack_require__) { var Triangle = __webpack_require__(67); var BuildRight = function(x, y, width, height) { if (height === undefined) { height = width } var x1 = x; var y1 = y; var x2 = x; var y2 = y - height; var x3 = x + width; var y3 = y; return new Triangle(x1, y1, x2, y2, x3, y3) }; module.exports = BuildRight }, function(module, exports, __webpack_require__) { var Centroid = __webpack_require__(388); var Offset = __webpack_require__(389); var CenterOn = function(triangle, x, y, centerFunc) { if (centerFunc === undefined) { centerFunc = Centroid } var center = centerFunc(triangle); var diffX = x - center.x; var diffY = y - center.y; return Offset(triangle, diffX, diffY) }; module.exports = CenterOn }, function(module, exports, __webpack_require__) { var Vector2 = __webpack_require__(3); function det(m00, m01, m10, m11) { return m00 * m11 - m01 * m10 } var CircumCenter = function(triangle, out) { if (out === undefined) { out = new Vector2 } var cx = triangle.x3; var cy = triangle.y3; var ax = triangle.x1 - cx; var ay = triangle.y1 - cy; var bx = triangle.x2 - cx; var by = triangle.y2 - cy; var denom = 2 * det(ax, ay, bx, by); var numx = det(ay, ax * ax + ay * ay, by, bx * bx + by * by); var numy = det(ax, ax * ax + ay * ay, bx, bx * bx + by * by); out.x = cx - numx / denom; out.y = cy + numy / denom; return out }; module.exports = CircumCenter }, function(module, exports, __webpack_require__) { var Circle = __webpack_require__(78); var CircumCircle = function(triangle, out) { if (out === undefined) { out = new Circle } var x1 = triangle.x1; var y1 = triangle.y1; var x2 = triangle.x2; var y2 = triangle.y2; var x3 = triangle.x3; var y3 = triangle.y3; var A = x2 - x1; var B = y2 - y1; var C = x3 - x1; var D = y3 - y1; var E = A * (x1 + x2) + B * (y1 + y2); var F = C * (x1 + x3) + D * (y1 + y3); var G = 2 * (A * (y3 - y2) - B * (x3 - x2)); var dx; var dy; if (Math.abs(G) < 1e-6) { var minX = Math.min(x1, x2, x3); var minY = Math.min(y1, y2, y3); dx = (Math.max(x1, x2, x3) - minX) * .5; dy = (Math.max(y1, y2, y3) - minY) * .5; out.x = minX + dx; out.y = minY + dy; out.radius = Math.sqrt(dx * dx + dy * dy) } else { out.x = (D * E - B * F) / G; out.y = (A * F - C * E) / G; dx = out.x - x1; dy = out.y - y1; out.radius = Math.sqrt(dx * dx + dy * dy) } return out }; module.exports = CircumCircle }, function(module, exports, __webpack_require__) { var Triangle = __webpack_require__(67); var Clone = function(source) { return new Triangle(source.x1, source.y1, source.x2, source.y2, source.x3, source.y3) }; module.exports = Clone }, function(module, exports, __webpack_require__) { var Contains = __webpack_require__(84); var ContainsPoint = function(triangle, point) { return Contains(triangle, point.x, point.y) }; module.exports = ContainsPoint }, function(module, exports) { var CopyFrom = function(source, dest) { return dest.setTo(source.x1, source.y1, source.x2, source.y2, source.x3, source.y3) }; module.exports = CopyFrom }, function(module, exports) { var Equals = function(triangle, toCompare) { return triangle.x1 === toCompare.x1 && triangle.y1 === toCompare.y1 && triangle.x2 === toCompare.x2 && triangle.y2 === toCompare.y2 && triangle.x3 === toCompare.x3 && triangle.y3 === toCompare.y3 }; module.exports = Equals }, function(module, exports, __webpack_require__) { var Length = __webpack_require__(62); var Perimeter = function(triangle) { var line1 = triangle.getLineA(); var line2 = triangle.getLineB(); var line3 = triangle.getLineC(); return Length(line1) + Length(line2) + Length(line3) }; module.exports = Perimeter }, function(module, exports, __webpack_require__) { var RotateAroundXY = __webpack_require__(196); var InCenter = __webpack_require__(390); var Rotate = function(triangle, angle) { var point = InCenter(triangle); return RotateAroundXY(triangle, point.x, point.y, angle) }; module.exports = Rotate }, function(module, exports, __webpack_require__) { var RotateAroundXY = __webpack_require__(196); var RotateAroundPoint = function(triangle, point, angle) { return RotateAroundXY(triangle, point.x, point.y, angle) }; module.exports = RotateAroundPoint }, function(module, exports, __webpack_require__) { var CONST = __webpack_require__(312); var Extend = __webpack_require__(19); var Input = { CreateInteractiveObject: __webpack_require__(391), Gamepad: __webpack_require__(928), InputManager: __webpack_require__(311), InputPlugin: __webpack_require__(934), InputPluginCache: __webpack_require__(128), Keyboard: __webpack_require__(936), Mouse: __webpack_require__(948), Pointer: __webpack_require__(314), Touch: __webpack_require__(949) }; Input = Extend(false, Input, CONST); module.exports = Input }, function(module, exports, __webpack_require__) { module.exports = { Axis: __webpack_require__(392), Button: __webpack_require__(393), Gamepad: __webpack_require__(394), GamepadPlugin: __webpack_require__(929), Configs: __webpack_require__(930) } }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var EventEmitter = __webpack_require__(11); var Gamepad = __webpack_require__(394); var GetValue = __webpack_require__(4); var InputPluginCache = __webpack_require__(128); var GamepadPlugin = new Class({ Extends: EventEmitter, initialize: function GamepadPlugin(sceneInputPlugin) { EventEmitter.call(this); this.scene = sceneInputPlugin.scene; this.settings = this.scene.sys.settings; this.sceneInputPlugin = sceneInputPlugin; this.enabled = true; this.target; this.gamepads = []; this.queue = []; this.onGamepadHandler; this._pad1; this._pad2; this._pad3; this._pad4; sceneInputPlugin.pluginEvents.once("boot", this.boot, this); sceneInputPlugin.pluginEvents.on("start", this.start, this) }, boot: function() { var game = this.scene.sys.game; var settings = this.settings.input; var config = game.config; this.enabled = GetValue(settings, "gamepad", config.inputGamepad) && game.device.input.gamepads; this.target = GetValue(settings, "gamepad.target", config.inputGamepadEventTarget); this.sceneInputPlugin.pluginEvents.once("destroy", this.destroy, this) }, start: function() { if (this.enabled) { this.startListeners() } this.sceneInputPlugin.pluginEvents.once("shutdown", this.shutdown, this) }, isActive: function() { return this.enabled && this.scene.sys.isActive() }, startListeners: function() { var _this = this; var target = this.target; var handler = function(event) { if (event.defaultPrevented || !_this.isActive()) { return } _this.refreshPads(); _this.queue.push(event) }; this.onGamepadHandler = handler; target.addEventListener("gamepadconnected", handler, false); target.addEventListener("gamepaddisconnected", handler, false); this.sceneInputPlugin.pluginEvents.on("update", this.update, this) }, stopListeners: function() { this.target.removeEventListener("gamepadconnected", this.onGamepadHandler); this.target.removeEventListener("gamepaddisconnected", this.onGamepadHandler); this.sceneInputPlugin.pluginEvents.off("update", this.update) }, disconnectAll: function() { for (var i = 0; i < this.gamepads.length; i++) { this.gamepads.connected = false } }, refreshPads: function() { var connectedPads = navigator.getGamepads(); if (!connectedPads) { this.disconnectAll() } else { var currentPads = this.gamepads; for (var i = 0; i < connectedPads.length; i++) { var livePad = connectedPads[i]; if (!livePad) { continue } var id = livePad.id; var index = livePad.index; var currentPad = currentPads[index]; if (!currentPad) { var newPad = new Gamepad(this, livePad); currentPads[index] = newPad; if (!this._pad1) { this._pad1 = newPad } else if (!this._pad2) { this._pad2 = newPad } else if (!this._pad3) { this._pad3 = newPad } else if (!this._pad4) { this._pad4 = newPad } } else if (currentPad.id !== id) { currentPad.destroy(); currentPads[index] = new Gamepad(this, livePad) } else { currentPad.update(livePad) } } } }, getAll: function() { var out = []; var pads = this.gamepads; for (var i = 0; i < pads.length; i++) { if (pads[i]) { out.push(pads[i]) } } return out }, getPad: function(index) { var pads = this.gamepads; for (var i = 0; i < pads.length; i++) { if (pads[i] && pads[i].index === index) { return pads[i] } } }, update: function() { if (!this.enabled) { return } this.refreshPads(); var len = this.queue.length; if (len === 0) { return } var queue = this.queue.splice(0, len); for (var i = 0; i < len; i++) { var event = queue[i]; var pad = this.getPad(event.gamepad.index); if (event.type === "gamepadconnected") { this.emit("connected", pad, event) } else if (event.type === "gamepaddisconnected") { this.emit("disconnected", pad, event) } } }, shutdown: function() { this.stopListeners(); this.disconnectAll(); this.removeAllListeners() }, destroy: function() { this.shutdown(); for (var i = 0; i < this.gamepads.length; i++) { if (this.gamepads[i]) { this.gamepads[i].destroy() } } this.gamepads = []; this.scene = null; this.settings = null; this.sceneInputPlugin = null; this.target = null }, total: { get: function() { return this.gamepads.length } }, pad1: { get: function() { return this._pad1 } }, pad2: { get: function() { return this._pad2 } }, pad3: { get: function() { return this._pad3 } }, pad4: { get: function() { return this._pad4 } } }); InputPluginCache.register("GamepadPlugin", GamepadPlugin, "gamepad", "gamepad", "inputGamepad"); module.exports = GamepadPlugin }, function(module, exports, __webpack_require__) { module.exports = { DUALSHOCK_4: __webpack_require__(931), SNES_USB: __webpack_require__(932), XBOX_360: __webpack_require__(933) } }, function(module, exports) { module.exports = { UP: 12, DOWN: 13, LEFT: 14, RIGHT: 15, SHARE: 8, OPTIONS: 9, PS: 16, TOUCHBAR: 17, X: 0, CIRCLE: 1, SQUARE: 2, TRIANGLE: 3, L1: 4, R1: 5, L2: 6, R2: 7, L3: 10, R3: 11, LEFT_STICK_H: 0, LEFT_STICK_V: 1, RIGHT_STICK_H: 2, RIGHT_STICK_V: 3 } }, function(module, exports) { module.exports = { UP: 12, DOWN: 13, LEFT: 14, RIGHT: 15, SELECT: 8, START: 9, B: 0, A: 1, Y: 2, X: 3, LEFT_SHOULDER: 4, RIGHT_SHOULDER: 5 } }, function(module, exports) { module.exports = { UP: 12, DOWN: 13, LEFT: 14, RIGHT: 15, MENU: 16, A: 0, B: 1, X: 2, Y: 3, LB: 4, RB: 5, LT: 6, RT: 7, BACK: 8, START: 9, LS: 10, RS: 11, LEFT_STICK_H: 0, LEFT_STICK_V: 1, RIGHT_STICK_H: 2, RIGHT_STICK_V: 3 } }, function(module, exports, __webpack_require__) { var Circle = __webpack_require__(78); var CircleContains = __webpack_require__(46); var Class = __webpack_require__(0); var CreateInteractiveObject = __webpack_require__(391); var CreatePixelPerfectHandler = __webpack_require__(935); var DistanceBetween = __webpack_require__(56); var Ellipse = __webpack_require__(94); var EllipseContains = __webpack_require__(95); var EventEmitter = __webpack_require__(11); var GetFastValue = __webpack_require__(1); var InputPluginCache = __webpack_require__(128); var IsPlainObject = __webpack_require__(7); var PluginCache = __webpack_require__(15); var Rectangle = __webpack_require__(9); var RectangleContains = __webpack_require__(47); var Triangle = __webpack_require__(67); var TriangleContains = __webpack_require__(84); var InputPlugin = new Class({ Extends: EventEmitter, initialize: function InputPlugin(scene) { EventEmitter.call(this); this.scene = scene; this.systems = scene.sys; this.settings = scene.sys.settings; this.manager = scene.sys.game.input; this.pluginEvents = new EventEmitter; this.enabled = true; this.displayList; this.cameras; InputPluginCache.install(this); this.mouse = this.manager.mouse; this.topOnly = true; this.pollRate = -1; this._pollTimer = 0; var _eventData = { cancelled: false }; this._eventContainer = { stopPropagation: function() { _eventData.cancelled = true } }; this._eventData = _eventData; this.dragDistanceThreshold = 0; this.dragTimeThreshold = 0; this._temp = []; this._tempZones = []; this._list = []; this._pendingInsertion = []; this._pendingRemoval = []; this._draggable = []; this._drag = { 0: [], 1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: [], 8: [], 9: [], 10: [] }; this._over = { 0: [], 1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: [], 8: [], 9: [], 10: [] }; this._validTypes = ["onDown", "onUp", "onOver", "onOut", "onMove", "onDragStart", "onDrag", "onDragEnd", "onDragEnter", "onDragLeave", "onDragOver", "onDrop"]; scene.sys.events.once("boot", this.boot, this); scene.sys.events.on("start", this.start, this) }, boot: function() { this.cameras = this.systems.cameras; this.displayList = this.systems.displayList; this.systems.events.once("destroy", this.destroy, this); this.pluginEvents.emit("boot") }, start: function() { var eventEmitter = this.systems.events; eventEmitter.on("transitionstart", this.transitionIn, this); eventEmitter.on("transitionout", this.transitionOut, this); eventEmitter.on("transitioncomplete", this.transitionComplete, this); eventEmitter.on("preupdate", this.preUpdate, this); eventEmitter.on("update", this.update, this); eventEmitter.once("shutdown", this.shutdown, this); this.enabled = true; this.pluginEvents.emit("start") }, preUpdate: function() { this.pluginEvents.emit("preUpdate"); var removeList = this._pendingRemoval; var insertList = this._pendingInsertion; var toRemove = removeList.length; var toInsert = insertList.length; if (toRemove === 0 && toInsert === 0) { return } var current = this._list; for (var i = 0; i < toRemove; i++) { var gameObject = removeList[i]; var index = current.indexOf(gameObject); if (index > -1) { current.splice(index, 1); this.clear(gameObject) } } removeList.length = 0; this._pendingRemoval.length = 0; this._list = current.concat(insertList.splice(0)) }, isActive: function() { return this.enabled && this.scene.sys.isActive() }, update: function(time, delta) { if (!this.isActive()) { return } this.pluginEvents.emit("update", time, delta); var manager = this.manager; if (manager.globalTopOnly && manager.ignoreEvents) { return } var runUpdate = manager.dirty || this.pollRate === 0; if (this.pollRate > -1) { this._pollTimer -= delta; if (this._pollTimer < 0) { runUpdate = true; this._pollTimer = this.pollRate } } if (!runUpdate) { return } var pointers = this.manager.pointers; for (var i = 0; i < this.manager.pointersTotal; i++) { var pointer = pointers[i]; this._tempZones = []; this._temp = this.hitTestPointer(pointer); this.sortGameObjects(this._temp); this.sortGameObjects(this._tempZones); if (this.topOnly) { if (this._temp.length) { this._temp.splice(1) } if (this._tempZones.length) { this._tempZones.splice(1) } } var total = this.processDragEvents(pointer, time); if (!pointer.wasTouch) { total += this.processOverOutEvents(pointer) } if (pointer.justDown) { total += this.processDownEvents(pointer) } if (pointer.justUp) { total += this.processUpEvents(pointer) } if (pointer.justMoved) { total += this.processMoveEvents(pointer) } if (total > 0 && manager.globalTopOnly) { manager.ignoreEvents = true } } }, clear: function(gameObject) { var input = gameObject.input; if (!input) { return } this.queueForRemoval(gameObject); input.gameObject = undefined; input.target = undefined; input.hitArea = undefined; input.hitAreaCallback = undefined; input.callbackContext = undefined; this.manager.resetCursor(input); gameObject.input = null; var index = this._draggable.indexOf(gameObject); if (index > -1) { this._draggable.splice(index, 1) } index = this._drag[0].indexOf(gameObject); if (index > -1) { this._drag[0].splice(index, 1) } index = this._over[0].indexOf(gameObject); if (index > -1) { this._over[0].splice(index, 1) } return gameObject }, disable: function(gameObject) { gameObject.input.enabled = false }, enable: function(gameObject, shape, callback, dropZone) { if (dropZone === undefined) { dropZone = false } if (gameObject.input) { gameObject.input.enabled = true } else { this.setHitArea(gameObject, shape, callback) } if (gameObject.input && dropZone && !gameObject.input.dropZone) { gameObject.input.dropZone = dropZone } return this }, hitTestPointer: function(pointer) { var cameras = this.cameras.getCamerasBelowPointer(pointer); for (var c = 0; c < cameras.length; c++) { var camera = cameras[c]; var over = this.manager.hitTest(pointer, this._list, camera); for (var i = 0; i < over.length; i++) { var obj = over[i]; if (obj.input.dropZone) { this._tempZones.push(obj) } } if (over.length > 0) { pointer.camera = camera; return over } } pointer.camera = cameras[0]; return [] }, processDownEvents: function(pointer) { var total = 0; var currentlyOver = this._temp; var _eventData = this._eventData; var _eventContainer = this._eventContainer; _eventData.cancelled = false; var aborted = false; for (var i = 0; i < currentlyOver.length; i++) { var gameObject = currentlyOver[i]; if (!gameObject.input) { continue } total++; gameObject.emit("pointerdown", pointer, gameObject.input.localX, gameObject.input.localY, _eventContainer); if (_eventData.cancelled) { aborted = true; break } this.emit("gameobjectdown", pointer, gameObject, _eventContainer); if (_eventData.cancelled) { aborted = true; break } } if (!aborted) { this.emit("pointerdown", pointer, currentlyOver) } return total }, processDragEvents: function(pointer, time) { if (this._draggable.length === 0) { return 0 } var i; var gameObject; var list; var input; var currentlyOver = this._temp; if (pointer.dragState === 0 && pointer.primaryDown && pointer.justDown && currentlyOver.length > 0) { pointer.dragState = 1 } else if (pointer.dragState > 0 && !pointer.primaryDown && pointer.justUp) { pointer.dragState = 5 } if (pointer.dragState === 1) { var draglist = []; for (i = 0; i < currentlyOver.length; i++) { gameObject = currentlyOver[i]; if (gameObject.input.draggable && gameObject.input.dragState === 0) { draglist.push(gameObject) } } if (draglist.length === 0) { pointer.dragState = 0; return 0 } else if (draglist.length > 1) { this.sortGameObjects(draglist); if (this.topOnly) { draglist.splice(1) } } this._drag[pointer.id] = draglist; if (this.dragDistanceThreshold === 0 && this.dragTimeThreshold === 0) { pointer.dragState = 3 } else { pointer.dragState = 2 } } if (pointer.dragState === 2) { if (this.dragDistanceThreshold > 0 && DistanceBetween(pointer.x, pointer.y, pointer.downX, pointer.downY) >= this.dragDistanceThreshold) { pointer.dragState = 3 } if (this.dragTimeThreshold > 0 && time >= pointer.downTime + this.dragTimeThreshold) { pointer.dragState = 3 } } if (pointer.dragState === 3) { list = this._drag[pointer.id]; for (i = 0; i < list.length; i++) { gameObject = list[i]; input = gameObject.input; input.dragState = 2; input.dragX = pointer.x - gameObject.x; input.dragY = pointer.y - gameObject.y; input.dragStartX = gameObject.x; input.dragStartY = gameObject.y; gameObject.emit("dragstart", pointer, input.dragX, input.dragY); this.emit("dragstart", pointer, gameObject) } pointer.dragState = 4; return list.length } if (pointer.dragState === 4 && pointer.justMoved && !pointer.justUp) { var dropZones = this._tempZones; list = this._drag[pointer.id]; for (i = 0; i < list.length; i++) { gameObject = list[i]; input = gameObject.input; if (input.target) { var index = dropZones.indexOf(input.target); if (index === 0) { gameObject.emit("dragover", pointer, input.target); this.emit("dragover", pointer, gameObject, input.target) } else if (index > 0) { gameObject.emit("dragleave", pointer, input.target); this.emit("dragleave", pointer, gameObject, input.target); input.target = dropZones[0]; gameObject.emit("dragenter", pointer, input.target); this.emit("dragenter", pointer, gameObject, input.target) } else { gameObject.emit("dragleave", pointer, input.target); this.emit("dragleave", pointer, gameObject, input.target); if (dropZones[0]) { input.target = dropZones[0]; gameObject.emit("dragenter", pointer, input.target); this.emit("dragenter", pointer, gameObject, input.target) } else { input.target = null } } } else if (!input.target && dropZones[0]) { input.target = dropZones[0]; gameObject.emit("dragenter", pointer, input.target); this.emit("dragenter", pointer, gameObject, input.target) } var dragX = pointer.x - gameObject.input.dragX; var dragY = pointer.y - gameObject.input.dragY; gameObject.emit("drag", pointer, dragX, dragY); this.emit("drag", pointer, gameObject, dragX, dragY) } return list.length } if (pointer.dragState === 5) { list = this._drag[pointer.id]; for (i = 0; i < list.length; i++) { gameObject = list[i]; input = gameObject.input; if (input.dragState === 2) { input.dragState = 0; input.dragX = input.localX - gameObject.displayOriginX; input.dragY = input.localY - gameObject.displayOriginY; var dropped = false; if (input.target) { gameObject.emit("drop", pointer, input.target); this.emit("drop", pointer, gameObject, input.target); input.target = null; dropped = true } gameObject.emit("dragend", pointer, input.dragX, input.dragY, dropped); this.emit("dragend", pointer, gameObject, dropped) } } pointer.dragState = 0; list.splice(0) } return 0 }, processMoveEvents: function(pointer) { var total = 0; var currentlyOver = this._temp; var _eventData = this._eventData; var _eventContainer = this._eventContainer; _eventData.cancelled = false; var aborted = false; for (var i = 0; i < currentlyOver.length; i++) { var gameObject = currentlyOver[i]; if (!gameObject.input) { continue } total++; gameObject.emit("pointermove", pointer, gameObject.input.localX, gameObject.input.localY, _eventContainer); if (_eventData.cancelled) { aborted = true; break } this.emit("gameobjectmove", pointer, gameObject, _eventContainer); if (_eventData.cancelled) { aborted = true; break } if (this.topOnly) { break } } if (!aborted) { this.emit("pointermove", pointer, currentlyOver) } return total }, processOverOutEvents: function(pointer) { var currentlyOver = this._temp; var i; var gameObject; var justOut = []; var justOver = []; var stillOver = []; var previouslyOver = this._over[pointer.id]; var currentlyDragging = this._drag[pointer.id]; var manager = this.manager; for (i = 0; i < previouslyOver.length; i++) { gameObject = previouslyOver[i]; if (currentlyOver.indexOf(gameObject) === -1 && currentlyDragging.indexOf(gameObject) === -1) { justOut.push(gameObject) } else { stillOver.push(gameObject) } } for (i = 0; i < currentlyOver.length; i++) { gameObject = currentlyOver[i]; if (previouslyOver.indexOf(gameObject) === -1) { justOver.push(gameObject) } } var total = justOut.length; var totalInteracted = 0; var _eventData = this._eventData; var _eventContainer = this._eventContainer; _eventData.cancelled = false; var aborted = false; if (total > 0) { this.sortGameObjects(justOut); for (i = 0; i < total; i++) { gameObject = justOut[i]; if (!gameObject.input) { continue } gameObject.emit("pointerout", pointer, _eventContainer); manager.resetCursor(gameObject.input); totalInteracted++; if (_eventData.cancelled) { aborted = true; break } this.emit("gameobjectout", pointer, gameObject, _eventContainer); if (_eventData.cancelled) { aborted = true; break } } if (!aborted) { this.emit("pointerout", pointer, justOut) } } total = justOver.length; _eventData.cancelled = false; aborted = false; if (total > 0) { this.sortGameObjects(justOver); for (i = 0; i < total; i++) { gameObject = justOver[i]; if (!gameObject.input) { continue } gameObject.emit("pointerover", pointer, gameObject.input.localX, gameObject.input.localY, _eventContainer); manager.setCursor(gameObject.input); totalInteracted++; if (_eventData.cancelled) { aborted = true; break } this.emit("gameobjectover", pointer, gameObject, _eventContainer); if (_eventData.cancelled) { aborted = true; break } } if (!aborted) { this.emit("pointerover", pointer, justOver) } } previouslyOver = stillOver.concat(justOver); this._over[pointer.id] = this.sortGameObjects(previouslyOver); return totalInteracted }, processUpEvents: function(pointer) { var currentlyOver = this._temp; var _eventData = this._eventData; var _eventContainer = this._eventContainer; _eventData.cancelled = false; var aborted = false; for (var i = 0; i < currentlyOver.length; i++) { var gameObject = currentlyOver[i]; if (!gameObject.input) { continue } gameObject.emit("pointerup", pointer, gameObject.input.localX, gameObject.input.localY, _eventContainer); if (_eventData.cancelled) { aborted = true; break } this.emit("gameobjectup", pointer, gameObject, _eventContainer); if (_eventData.cancelled) { aborted = true; break } } if (!aborted) { this.emit("pointerup", pointer, currentlyOver) } return currentlyOver.length }, queueForInsertion: function(child) { if (this._pendingInsertion.indexOf(child) === -1 && this._list.indexOf(child) === -1) { this._pendingInsertion.push(child) } return this }, queueForRemoval: function(child) { this._pendingRemoval.push(child); return this }, setDraggable: function(gameObjects, value) { if (value === undefined) { value = true } if (!Array.isArray(gameObjects)) { gameObjects = [gameObjects] } for (var i = 0; i < gameObjects.length; i++) { var gameObject = gameObjects[i]; gameObject.input.draggable = value; var index = this._draggable.indexOf(gameObject); if (value && index === -1) { this._draggable.push(gameObject) } else if (!value && index > -1) { this._draggable.splice(index, 1) } } return this }, makePixelPerfect: function(alphaTolerance) { if (alphaTolerance === undefined) { alphaTolerance = 1 } var textureManager = this.systems.textures; return CreatePixelPerfectHandler(textureManager, alphaTolerance) }, setHitArea: function(gameObjects, shape, callback) { if (shape === undefined) { return this.setHitAreaFromTexture(gameObjects) } if (!Array.isArray(gameObjects)) { gameObjects = [gameObjects] } var draggable = false; var dropZone = false; var cursor = false; var useHandCursor = false; if (IsPlainObject(shape)) { var config = shape; shape = GetFastValue(config, "hitArea", null); callback = GetFastValue(config, "hitAreaCallback", null); draggable = GetFastValue(config, "draggable", false); dropZone = GetFastValue(config, "dropZone", false); cursor = GetFastValue(config, "cursor", false); useHandCursor = GetFastValue(config, "useHandCursor", false); var pixelPerfect = GetFastValue(config, "pixelPerfect", false); var alphaTolerance = GetFastValue(config, "alphaTolerance", 1); if (pixelPerfect) { shape = {}; callback = this.makePixelPerfect(alphaTolerance) } if (!shape || !callback) { this.setHitAreaFromTexture(gameObjects) } } else if (typeof shape === "function" && !callback) { callback = shape; shape = {} } for (var i = 0; i < gameObjects.length; i++) { var gameObject = gameObjects[i]; var io = !gameObject.input ? CreateInteractiveObject(gameObject, shape, callback) : gameObject.input; io.dropZone = dropZone; io.cursor = useHandCursor ? "pointer" : cursor; gameObject.input = io; if (draggable) { this.setDraggable(gameObject) } this.queueForInsertion(gameObject) } return this }, setHitAreaCircle: function(gameObjects, x, y, radius, callback) { if (callback === undefined) { callback = CircleContains } var shape = new Circle(x, y, radius); return this.setHitArea(gameObjects, shape, callback) }, setHitAreaEllipse: function(gameObjects, x, y, width, height, callback) { if (callback === undefined) { callback = EllipseContains } var shape = new Ellipse(x, y, width, height); return this.setHitArea(gameObjects, shape, callback) }, setHitAreaFromTexture: function(gameObjects, callback) { if (callback === undefined) { callback = RectangleContains } if (!Array.isArray(gameObjects)) { gameObjects = [gameObjects] } for (var i = 0; i < gameObjects.length; i++) { var gameObject = gameObjects[i]; var frame = gameObject.frame; var width = 0; var height = 0; if (frame) { width = frame.realWidth; height = frame.realHeight } else if (gameObject.width) { width = gameObject.width; height = gameObject.height } if (gameObject.type === "Container" && (width === 0 || height === 0)) { console.warn("Container.setInteractive() must specify a Shape or call setSize() first"); continue } if (width !== 0 && height !== 0) { gameObject.input = CreateInteractiveObject(gameObject, new Rectangle(0, 0, width, height), callback); this.queueForInsertion(gameObject) } } return this }, setHitAreaRectangle: function(gameObjects, x, y, width, height, callback) { if (callback === undefined) { callback = RectangleContains } var shape = new Rectangle(x, y, width, height); return this.setHitArea(gameObjects, shape, callback) }, setHitAreaTriangle: function(gameObjects, x1, y1, x2, y2, x3, y3, callback) { if (callback === undefined) { callback = TriangleContains } var shape = new Triangle(x1, y1, x2, y2, x3, y3); return this.setHitArea(gameObjects, shape, callback) }, setPollAlways: function() { this.pollRate = 0; this._pollTimer = 0; return this }, setPollOnMove: function() { this.pollRate = -1; this._pollTimer = 0; return this }, setPollRate: function(value) { this.pollRate = value; this._pollTimer = 0; return this }, setGlobalTopOnly: function(value) { this.manager.globalTopOnly = value; return this }, setTopOnly: function(value) { this.topOnly = value; return this }, sortGameObjects: function(gameObjects) { if (gameObjects.length < 2) { return gameObjects } this.scene.sys.depthSort(); return gameObjects.sort(this.sortHandlerGO.bind(this)) }, sortHandlerGO: function(childA, childB) { if (!childA.parentContainer && !childB.parentContainer) { return this.displayList.getIndex(childB) - this.displayList.getIndex(childA) } else if (childA.parentContainer === childB.parentContainer) { return childB.parentContainer.getIndex(childB) - childA.parentContainer.getIndex(childA) } else if (childA.parentContainer === childB) { return -1 } else if (childB.parentContainer === childA) { return 1 } else { var listA = childA.getIndexList(); var listB = childB.getIndexList(); var len = Math.min(listA.length, listB.length); for (var i = 0; i < len; i++) { var indexA = listA[i]; var indexB = listB[i]; if (indexA === indexB) { continue } else { return indexB - indexA } } } return 0 }, stopPropagation: function() { if (this.manager.globalTopOnly) { this.manager.ignoreEvents = true } return this }, addUpCallback: function(callback, isOnce) { this.manager.addUpCallback(callback, isOnce); return this }, addDownCallback: function(callback, isOnce) { this.manager.addDownCallback(callback, isOnce); return this }, addMoveCallback: function(callback, isOnce) { this.manager.addMoveCallback(callback, isOnce); return this }, addPointer: function(quantity) { return this.manager.addPointer(quantity) }, setDefaultCursor: function(cursor) { this.manager.setDefaultCursor(cursor); return this }, transitionIn: function() { this.enabled = this.settings.transitionAllowInput }, transitionComplete: function() { if (!this.settings.transitionAllowInput) { this.enabled = true } }, transitionOut: function() { this.enabled = this.settings.transitionAllowInput }, shutdown: function() { this.pluginEvents.emit("shutdown"); this._temp.length = 0; this._list.length = 0; this._draggable.length = 0; this._pendingRemoval.length = 0; this._pendingInsertion.length = 0; for (var i = 0; i < 10; i++) { this._drag[i] = []; this._over[i] = [] } this.removeAllListeners(); var eventEmitter = this.systems.events; eventEmitter.off("transitionstart", this.transitionIn, this); eventEmitter.off("transitionout", this.transitionOut, this); eventEmitter.off("transitioncomplete", this.transitionComplete, this); eventEmitter.off("preupdate", this.preUpdate, this); eventEmitter.off("update", this.update, this); eventEmitter.off("shutdown", this.shutdown, this) }, destroy: function() { this.shutdown(); this.pluginEvents.emit("destroy"); this.pluginEvents.removeAllListeners(); this.scene.sys.events.off("start", this.start, this); this.scene = null; this.cameras = null; this.manager = null; this.events = null; this.mouse = null }, x: { get: function() { return this.manager.activePointer.x } }, y: { get: function() { return this.manager.activePointer.y } }, mousePointer: { get: function() { return this.manager.mousePointer } }, activePointer: { get: function() { return this.manager.activePointer } }, pointer1: { get: function() { return this.manager.pointers[1] } }, pointer2: { get: function() { return this.manager.pointers[2] } }, pointer3: { get: function() { return this.manager.pointers[3] } }, pointer4: { get: function() { return this.manager.pointers[4] } }, pointer5: { get: function() { return this.manager.pointers[5] } }, pointer6: { get: function() { return this.manager.pointers[6] } }, pointer7: { get: function() { return this.manager.pointers[7] } }, pointer8: { get: function() { return this.manager.pointers[8] } }, pointer9: { get: function() { return this.manager.pointers[9] } }, pointer10: { get: function() { return this.manager.pointers[10] } } }); PluginCache.register("InputPlugin", InputPlugin, "input"); module.exports = InputPlugin }, function(module, exports) { var CreatePixelPerfectHandler = function(textureManager, alphaTolerance) { return function(hitArea, x, y, gameObject) { var alpha = textureManager.getPixelAlpha(x, y, gameObject.texture.key, gameObject.frame.name); return alpha && alpha >= alphaTolerance } }; module.exports = CreatePixelPerfectHandler }, function(module, exports, __webpack_require__) { module.exports = { KeyboardPlugin: __webpack_require__(937), Key: __webpack_require__(395), KeyCodes: __webpack_require__(197), KeyCombo: __webpack_require__(396), JustDown: __webpack_require__(944), JustUp: __webpack_require__(945), DownDuration: __webpack_require__(946), UpDuration: __webpack_require__(947) } }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var EventEmitter = __webpack_require__(11); var GetValue = __webpack_require__(4); var InputPluginCache = __webpack_require__(128); var Key = __webpack_require__(395); var KeyCodes = __webpack_require__(197); var KeyCombo = __webpack_require__(396); var KeyMap = __webpack_require__(941); var ProcessKeyDown = __webpack_require__(942); var ProcessKeyUp = __webpack_require__(943); var SnapFloor = __webpack_require__(198); var KeyboardPlugin = new Class({ Extends: EventEmitter, initialize: function KeyboardPlugin(sceneInputPlugin) { EventEmitter.call(this); this.scene = sceneInputPlugin.scene; this.settings = this.scene.sys.settings; this.sceneInputPlugin = sceneInputPlugin; this.enabled = true; this.target; this.keys = []; this.combos = []; this.queue = []; this.onKeyHandler; this.time = 0; sceneInputPlugin.pluginEvents.once("boot", this.boot, this); sceneInputPlugin.pluginEvents.on("start", this.start, this) }, boot: function() { var settings = this.settings.input; var config = this.scene.sys.game.config; this.enabled = GetValue(settings, "keyboard", config.inputKeyboard); this.target = GetValue(settings, "keyboard.target", config.inputKeyboardEventTarget); this.sceneInputPlugin.pluginEvents.once("destroy", this.destroy, this) }, start: function() { if (this.enabled) { this.startListeners() } this.sceneInputPlugin.pluginEvents.once("shutdown", this.shutdown, this) }, isActive: function() { return this.enabled && this.scene.sys.isActive() }, startListeners: function() { var _this = this; var handler = function(event) { if (event.defaultPrevented || !_this.isActive()) { return } _this.queue.push(event); var key = _this.keys[event.keyCode]; if (key && key.preventDefault) { event.preventDefault() } }; this.onKeyHandler = handler; this.target.addEventListener("keydown", handler, false); this.target.addEventListener("keyup", handler, false); this.sceneInputPlugin.pluginEvents.on("update", this.update, this) }, stopListeners: function() { this.target.removeEventListener("keydown", this.onKeyHandler); this.target.removeEventListener("keyup", this.onKeyHandler); this.sceneInputPlugin.pluginEvents.off("update", this.update) }, createCursorKeys: function() { return this.addKeys({ up: KeyCodes.UP, down: KeyCodes.DOWN, left: KeyCodes.LEFT, right: KeyCodes.RIGHT, space: KeyCodes.SPACE, shift: KeyCodes.SHIFT }) }, addKeys: function(keys) { var output = {}; if (typeof keys === "string") { keys = keys.split(","); for (var i = 0; i < keys.length; i++) { var currentKey = keys[i].trim(); if (currentKey) { output[currentKey] = this.addKey(currentKey) } } } else { for (var key in keys) { output[key] = this.addKey(keys[key]) } } return output }, addKey: function(key) { var keys = this.keys; if (key instanceof Key) { var idx = keys.indexOf(key); if (idx > -1) { keys[idx] = key } else { keys[key.keyCode] = key } return key } if (typeof key === "string") { key = KeyCodes[key.toUpperCase()] } if (!keys[key]) { keys[key] = new Key(key) } return keys[key] }, removeKey: function(key) { var keys = this.keys; if (key instanceof Key) { var idx = keys.indexOf(key); if (idx > -1) { this.keys[idx] = undefined } } else if (typeof key === "string") { key = KeyCodes[key.toUpperCase()] } if (keys[key]) { keys[key] = undefined } }, createCombo: function(keys, config) { return new KeyCombo(this, keys, config) }, checkDown: function(key, duration) { if (this.enabled && key.isDown) { var t = SnapFloor(this.time - key.timeDown, duration); if (t > key._tick) { key._tick = t; return true } } return false }, update: function(time) { this.time = time; var len = this.queue.length; if (!this.enabled || len === 0) { return } var queue = this.queue.splice(0, len); var keys = this.keys; for (var i = 0; i < len; i++) { var event = queue[i]; var code = event.keyCode; if (event.type === "keydown") { if (KeyMap[code] && (keys[code] === undefined || keys[code].isDown === false)) { this.emit(event.type, event); this.emit("keydown_" + KeyMap[code], event) } if (keys[code]) { ProcessKeyDown(keys[code], event) } } else { this.emit(event.type, event); this.emit("keyup_" + KeyMap[code], event); if (keys[code]) { ProcessKeyUp(keys[code], event) } } } }, resetKeys: function() { var keys = this.keys; for (var i = 0; i < keys.length; i++) { if (keys[i]) { keys[i].reset() } } return this }, shutdown: function() { this.resetKeys(); this.stopListeners(); this.removeAllListeners(); this.queue = [] }, destroy: function() { this.shutdown(); this.keys = []; this.combos = []; this.queue = []; this.scene = null; this.settings = null; this.sceneInputPlugin = null; this.target = null } }); InputPluginCache.register("KeyboardPlugin", KeyboardPlugin, "keyboard", "keyboard", "inputKeyboard"); module.exports = KeyboardPlugin }, function(module, exports, __webpack_require__) { var AdvanceKeyCombo = __webpack_require__(939); var ProcessKeyCombo = function(event, combo) { if (combo.matched) { return true } var comboMatched = false; var keyMatched = false; if (event.keyCode === combo.current) { if (combo.index > 0 && combo.maxKeyDelay > 0) { var timeLimit = combo.timeLastMatched + combo.maxKeyDelay; if (event.timeStamp <= timeLimit) { keyMatched = true; comboMatched = AdvanceKeyCombo(event, combo) } } else { keyMatched = true; comboMatched = AdvanceKeyCombo(event, combo) } } if (!keyMatched && combo.resetOnWrongKey) { combo.index = 0; combo.current = combo.keyCodes[0] } if (comboMatched) { combo.timeLastMatched = event.timeStamp; combo.matched = true; combo.timeMatched = event.timeStamp } return comboMatched }; module.exports = ProcessKeyCombo }, function(module, exports) { var AdvanceKeyCombo = function(event, combo) { combo.timeLastMatched = event.timeStamp; combo.index++; if (combo.index === combo.size) { return true } else { combo.current = combo.keyCodes[combo.index]; return false } }; module.exports = AdvanceKeyCombo }, function(module, exports) { var ResetKeyCombo = function(combo) { combo.current = combo.keyCodes[0]; combo.index = 0; combo.timeLastMatched = 0; combo.matched = false; combo.timeMatched = 0; return combo }; module.exports = ResetKeyCombo }, function(module, exports, __webpack_require__) { var KeyCodes = __webpack_require__(197); var KeyMap = {}; for (var key in KeyCodes) { KeyMap[KeyCodes[key]] = key } module.exports = KeyMap }, function(module, exports) { var ProcessKeyDown = function(key, event) { key.originalEvent = event; if (key.preventDefault) { event.preventDefault() } if (!key.enabled) { return } key.altKey = event.altKey; key.ctrlKey = event.ctrlKey; key.shiftKey = event.shiftKey; key.location = event.location; if (key.isDown === false) { key.isDown = true; key.isUp = false; key.timeDown = event.timeStamp; key.duration = 0; key._justDown = true; key._justUp = false } key.repeats++; return key }; module.exports = ProcessKeyDown }, function(module, exports) { var ProcessKeyUp = function(key, event) { key.originalEvent = event; if (key.preventDefault) { event.preventDefault() } if (!key.enabled) { return } key.isDown = false; key.isUp = true; key.timeUp = event.timeStamp; key.duration = key.timeUp - key.timeDown; key.repeats = 0; key._justDown = false; key._justUp = true; key._tick = -1; return key }; module.exports = ProcessKeyUp }, function(module, exports) { var JustDown = function(key) { if (key._justDown) { key._justDown = false; return true } else { return false } }; module.exports = JustDown }, function(module, exports) { var JustUp = function(key) { if (key._justUp) { key._justUp = false; return true } else { return false } }; module.exports = JustUp }, function(module, exports) { var DownDuration = function(key, duration) { if (duration === undefined) { duration = 50 } return key.isDown && key.duration < duration }; module.exports = DownDuration }, function(module, exports) { var UpDuration = function(key, duration) { if (duration === undefined) { duration = 50 } return key.isUp && key.duration < duration }; module.exports = UpDuration }, function(module, exports, __webpack_require__) { module.exports = { MouseManager: __webpack_require__(313) } }, function(module, exports, __webpack_require__) { module.exports = { TouchManager: __webpack_require__(316) } }, function(module, exports, __webpack_require__) { var CONST = __webpack_require__(20); var Extend = __webpack_require__(19); var Loader = { FileTypes: __webpack_require__(951), File: __webpack_require__(22), FileTypesManager: __webpack_require__(8), GetURL: __webpack_require__(199), LoaderPlugin: __webpack_require__(972), MergeXHRSettings: __webpack_require__(200), MultiFile: __webpack_require__(69), XHRLoader: __webpack_require__(397), XHRSettings: __webpack_require__(129) }; Loader = Extend(false, Loader, CONST); module.exports = Loader }, function(module, exports, __webpack_require__) { module.exports = { AnimationJSONFile: __webpack_require__(952), AtlasJSONFile: __webpack_require__(953), AtlasXMLFile: __webpack_require__(954), AudioFile: __webpack_require__(398), AudioSpriteFile: __webpack_require__(955), BinaryFile: __webpack_require__(956), BitmapFontFile: __webpack_require__(957), GLSLFile: __webpack_require__(958), HTML5AudioFile: __webpack_require__(399), HTMLFile: __webpack_require__(959), HTMLTextureFile: __webpack_require__(960), ImageFile: __webpack_require__(68), JSONFile: __webpack_require__(57), MultiAtlasFile: __webpack_require__(961), PackFile: __webpack_require__(962), PluginFile: __webpack_require__(963), ScenePluginFile: __webpack_require__(964), ScriptFile: __webpack_require__(965), SpriteSheetFile: __webpack_require__(966), SVGFile: __webpack_require__(967), TextFile: __webpack_require__(400), TilemapCSVFile: __webpack_require__(968), TilemapImpactFile: __webpack_require__(969), TilemapJSONFile: __webpack_require__(970), UnityAtlasFile: __webpack_require__(971), XMLFile: __webpack_require__(201) } }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var FileTypesManager = __webpack_require__(8); var JSONFile = __webpack_require__(57); var AnimationJSONFile = new Class({ Extends: JSONFile, initialize: function AnimationJSONFile(loader, key, url, xhrSettings, dataKey) { JSONFile.call(this, loader, key, url, xhrSettings, dataKey); this.type = "animationJSON" }, onProcess: function() { this.loader.once("loadcomplete", this.onLoadComplete, this); JSONFile.prototype.onProcess.call(this) }, onLoadComplete: function() { this.loader.systems.anims.fromJSON(this.data); this.pendingDestroy() } }); FileTypesManager.register("animation", function(key, url, dataKey, xhrSettings) { if (Array.isArray(key)) { for (var i = 0; i < key.length; i++) { this.addFile(new AnimationJSONFile(this, key[i])) } } else { this.addFile(new AnimationJSONFile(this, key, url, xhrSettings, dataKey)) } return this }); module.exports = AnimationJSONFile }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(1); var ImageFile = __webpack_require__(68); var IsPlainObject = __webpack_require__(7); var JSONFile = __webpack_require__(57); var MultiFile = __webpack_require__(69); var AtlasJSONFile = new Class({ Extends: MultiFile, initialize: function AtlasJSONFile(loader, key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings) { var image; var data; if (IsPlainObject(key)) { var config = key; key = GetFastValue(config, "key"); image = new ImageFile(loader, { key: key, url: GetFastValue(config, "textureURL"), extension: GetFastValue(config, "textureExtension", "png"), normalMap: GetFastValue(config, "normalMap"), xhrSettings: GetFastValue(config, "textureXhrSettings") }); data = new JSONFile(loader, { key: key, url: GetFastValue(config, "atlasURL"), extension: GetFastValue(config, "atlasExtension", "json"), xhrSettings: GetFastValue(config, "atlasXhrSettings") }) } else { image = new ImageFile(loader, key, textureURL, textureXhrSettings); data = new JSONFile(loader, key, atlasURL, atlasXhrSettings) } if (image.linkFile) { MultiFile.call(this, loader, "atlasjson", key, [image, data, image.linkFile]) } else { MultiFile.call(this, loader, "atlasjson", key, [image, data]) } }, addToCache: function() { if (this.isReadyToProcess()) { var image = this.files[0]; var json = this.files[1]; var normalMap = this.files[2] ? this.files[2].data : null; this.loader.textureManager.addAtlas(image.key, image.data, json.data, normalMap); json.addToCache(); this.complete = true } } }); FileTypesManager.register("atlas", function(key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings) { var multifile; if (Array.isArray(key)) { for (var i = 0; i < key.length; i++) { multifile = new AtlasJSONFile(this, key[i]); this.addFile(multifile.files) } } else { multifile = new AtlasJSONFile(this, key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings); this.addFile(multifile.files) } return this }); module.exports = AtlasJSONFile }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(1); var ImageFile = __webpack_require__(68); var IsPlainObject = __webpack_require__(7); var MultiFile = __webpack_require__(69); var XMLFile = __webpack_require__(201); var AtlasXMLFile = new Class({ Extends: MultiFile, initialize: function AtlasXMLFile(loader, key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings) { var image; var data; if (IsPlainObject(key)) { var config = key; key = GetFastValue(config, "key"); image = new ImageFile(loader, { key: key, url: GetFastValue(config, "textureURL"), extension: GetFastValue(config, "textureExtension", "png"), normalMap: GetFastValue(config, "normalMap"), xhrSettings: GetFastValue(config, "textureXhrSettings") }); data = new XMLFile(loader, { key: key, url: GetFastValue(config, "atlasURL"), extension: GetFastValue(config, "atlasExtension", "xml"), xhrSettings: GetFastValue(config, "atlasXhrSettings") }) } else { image = new ImageFile(loader, key, textureURL, textureXhrSettings); data = new XMLFile(loader, key, atlasURL, atlasXhrSettings) } if (image.linkFile) { MultiFile.call(this, loader, "atlasxml", key, [image, data, image.linkFile]) } else { MultiFile.call(this, loader, "atlasxml", key, [image, data]) } }, addToCache: function() { if (this.isReadyToProcess()) { var image = this.files[0]; var xml = this.files[1]; var normalMap = this.files[2] ? this.files[2].data : null; this.loader.textureManager.addAtlasXML(image.key, image.data, xml.data, normalMap); xml.addToCache(); this.complete = true } } }); FileTypesManager.register("atlasXML", function(key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings) { var multifile; if (Array.isArray(key)) { for (var i = 0; i < key.length; i++) { multifile = new AtlasXMLFile(this, key[i]); this.addFile(multifile.files) } } else { multifile = new AtlasXMLFile(this, key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings); this.addFile(multifile.files) } return this }); module.exports = AtlasXMLFile }, function(module, exports, __webpack_require__) { var AudioFile = __webpack_require__(398); var Class = __webpack_require__(0); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(1); var IsPlainObject = __webpack_require__(7); var JSONFile = __webpack_require__(57); var MultiFile = __webpack_require__(69); var AudioSpriteFile = new Class({ Extends: MultiFile, initialize: function AudioSpriteFile(loader, key, jsonURL, audioURL, audioConfig, audioXhrSettings, jsonXhrSettings) { if (IsPlainObject(key)) { var config = key; key = GetFastValue(config, "key"); jsonURL = GetFastValue(config, "jsonURL"); audioURL = GetFastValue(config, "audioURL"); audioConfig = GetFastValue(config, "audioConfig"); audioXhrSettings = GetFastValue(config, "audioXhrSettings"); jsonXhrSettings = GetFastValue(config, "jsonXhrSettings") } var data; if (!audioURL) { data = new JSONFile(loader, key, jsonURL, jsonXhrSettings); MultiFile.call(this, loader, "audiosprite", key, [data]); this.config.resourceLoad = true; this.config.audioConfig = audioConfig; this.config.audioXhrSettings = audioXhrSettings } else { var audio = AudioFile.create(loader, key, audioURL, audioConfig, audioXhrSettings); if (audio) { data = new JSONFile(loader, key, jsonURL, jsonXhrSettings); MultiFile.call(this, loader, "audiosprite", key, [audio, data]); this.config.resourceLoad = false } } }, onFileComplete: function(file) { var index = this.files.indexOf(file); if (index !== -1) { this.pending--; if (this.config.resourceLoad && file.type === "json" && file.data.hasOwnProperty("resources")) { var urls = file.data.resources; var audioConfig = GetFastValue(this.config, "audioConfig"); var audioXhrSettings = GetFastValue(this.config, "audioXhrSettings"); var audio = AudioFile.create(this.loader, file.key, urls, audioConfig, audioXhrSettings); if (audio) { this.addToMultiFile(audio); this.loader.addFile(audio) } } } }, addToCache: function() { if (this.isReadyToProcess()) { var fileA = this.files[0]; var fileB = this.files[1]; fileA.addToCache(); fileB.addToCache(); this.complete = true } } }); FileTypesManager.register("audioSprite", function(key, jsonURL, audioURL, audioConfig, audioXhrSettings, jsonXhrSettings) { var game = this.systems.game; var gameAudioConfig = game.config.audio; var deviceAudio = game.device.audio; if (gameAudioConfig && gameAudioConfig.noAudio || !deviceAudio.webAudio && !deviceAudio.audioData) { return this } var multifile; if (Array.isArray(key)) { for (var i = 0; i < key.length; i++) { multifile = new AudioSpriteFile(this, key[i]); if (multifile.files) { this.addFile(multifile.files) } } } else { multifile = new AudioSpriteFile(this, key, jsonURL, audioURL, audioConfig, audioXhrSettings, jsonXhrSettings); if (multifile.files) { this.addFile(multifile.files) } } return this }) }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var CONST = __webpack_require__(20); var File = __webpack_require__(22); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(1); var IsPlainObject = __webpack_require__(7); var BinaryFile = new Class({ Extends: File, initialize: function BinaryFile(loader, key, url, xhrSettings, dataType) { var extension = "bin"; if (IsPlainObject(key)) { var config = key; key = GetFastValue(config, "key"); url = GetFastValue(config, "url"); xhrSettings = GetFastValue(config, "xhrSettings"); extension = GetFastValue(config, "extension", extension); dataType = GetFastValue(config, "dataType", dataType) } var fileConfig = { type: "binary", cache: loader.cacheManager.binary, extension: extension, responseType: "arraybuffer", key: key, url: url, xhrSettings: xhrSettings, config: { dataType: dataType } }; File.call(this, loader, fileConfig) }, onProcess: function() { this.state = CONST.FILE_PROCESSING; var ctor = this.config.dataType; this.data = ctor ? new ctor(this.xhrLoader.response) : this.xhrLoader.response; this.onProcessComplete() } }); FileTypesManager.register("binary", function(key, url, dataType, xhrSettings) { if (Array.isArray(key)) { for (var i = 0; i < key.length; i++) { this.addFile(new BinaryFile(this, key[i])) } } else { this.addFile(new BinaryFile(this, key, url, xhrSettings, dataType)) } return this }); module.exports = BinaryFile }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(1); var ImageFile = __webpack_require__(68); var IsPlainObject = __webpack_require__(7); var MultiFile = __webpack_require__(69); var ParseXMLBitmapFont = __webpack_require__(339); var XMLFile = __webpack_require__(201); var BitmapFontFile = new Class({ Extends: MultiFile, initialize: function BitmapFontFile(loader, key, textureURL, fontDataURL, textureXhrSettings, fontDataXhrSettings) { var image; var data; if (IsPlainObject(key)) { var config = key; key = GetFastValue(config, "key"); image = new ImageFile(loader, { key: key, url: GetFastValue(config, "textureURL"), extension: GetFastValue(config, "textureExtension", "png"), normalMap: GetFastValue(config, "normalMap"), xhrSettings: GetFastValue(config, "textureXhrSettings") }); data = new XMLFile(loader, { key: key, url: GetFastValue(config, "fontDataURL"), extension: GetFastValue(config, "fontDataExtension", "xml"), xhrSettings: GetFastValue(config, "fontDataXhrSettings") }) } else { image = new ImageFile(loader, key, textureURL, textureXhrSettings); data = new XMLFile(loader, key, fontDataURL, fontDataXhrSettings) } if (image.linkFile) { MultiFile.call(this, loader, "bitmapfont", key, [image, data, image.linkFile]) } else { MultiFile.call(this, loader, "bitmapfont", key, [image, data]) } }, addToCache: function() { if (this.isReadyToProcess()) { var image = this.files[0]; var xml = this.files[1]; image.addToCache(); xml.addToCache(); this.loader.cacheManager.bitmapFont.add(image.key, { data: ParseXMLBitmapFont(xml.data), texture: image.key, frame: null }); this.complete = true } } }); FileTypesManager.register("bitmapFont", function(key, textureURL, fontDataURL, textureXhrSettings, fontDataXhrSettings) { var multifile; if (Array.isArray(key)) { for (var i = 0; i < key.length; i++) { multifile = new BitmapFontFile(this, key[i]); this.addFile(multifile.files) } } else { multifile = new BitmapFontFile(this, key, textureURL, fontDataURL, textureXhrSettings, fontDataXhrSettings); this.addFile(multifile.files) } return this }); module.exports = BitmapFontFile }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var CONST = __webpack_require__(20); var File = __webpack_require__(22); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(1); var IsPlainObject = __webpack_require__(7); var GLSLFile = new Class({ Extends: File, initialize: function GLSLFile(loader, key, url, xhrSettings) { var extension = "glsl"; if (IsPlainObject(key)) { var config = key; key = GetFastValue(config, "key"); url = GetFastValue(config, "url"); xhrSettings = GetFastValue(config, "xhrSettings"); extension = GetFastValue(config, "extension", extension) } var fileConfig = { type: "glsl", cache: loader.cacheManager.shader, extension: extension, responseType: "text", key: key, url: url, xhrSettings: xhrSettings }; File.call(this, loader, fileConfig) }, onProcess: function() { this.state = CONST.FILE_PROCESSING; this.data = this.xhrLoader.responseText; this.onProcessComplete() } }); FileTypesManager.register("glsl", function(key, url, xhrSettings) { if (Array.isArray(key)) { for (var i = 0; i < key.length; i++) { this.addFile(new GLSLFile(this, key[i])) } } else { this.addFile(new GLSLFile(this, key, url, xhrSettings)) } return this }); module.exports = GLSLFile }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var CONST = __webpack_require__(20); var File = __webpack_require__(22); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(1); var IsPlainObject = __webpack_require__(7); var HTMLFile = new Class({ Extends: File, initialize: function HTMLFile(loader, key, url, xhrSettings) { var extension = "html"; if (IsPlainObject(key)) { var config = key; key = GetFastValue(config, "key"); url = GetFastValue(config, "url"); xhrSettings = GetFastValue(config, "xhrSettings"); extension = GetFastValue(config, "extension", extension) } var fileConfig = { type: "text", cache: loader.cacheManager.html, extension: extension, responseType: "text", key: key, url: url, xhrSettings: xhrSettings }; File.call(this, loader, fileConfig) }, onProcess: function() { this.state = CONST.FILE_PROCESSING; this.data = this.xhrLoader.responseText; this.onProcessComplete() } }); FileTypesManager.register("html", function(key, url, xhrSettings) { if (Array.isArray(key)) { for (var i = 0; i < key.length; i++) { this.addFile(new HTMLFile(this, key[i])) } } else { this.addFile(new HTMLFile(this, key, url, xhrSettings)) } return this }); module.exports = HTMLFile }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var CONST = __webpack_require__(20); var File = __webpack_require__(22); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(1); var IsPlainObject = __webpack_require__(7); var HTMLTextureFile = new Class({ Extends: File, initialize: function HTMLTextureFile(loader, key, url, width, height, xhrSettings) { if (width === undefined) { width = 512 } if (height === undefined) { height = 512 } var extension = "html"; if (IsPlainObject(key)) { var config = key; key = GetFastValue(config, "key"); url = GetFastValue(config, "url"); xhrSettings = GetFastValue(config, "xhrSettings"); extension = GetFastValue(config, "extension", extension); width = GetFastValue(config, "width", width); height = GetFastValue(config, "height", height) } var fileConfig = { type: "html", cache: loader.textureManager, extension: extension, responseType: "text", key: key, url: url, xhrSettings: xhrSettings, config: { width: width, height: height } }; File.call(this, loader, fileConfig) }, onProcess: function() { this.state = CONST.FILE_PROCESSING; var w = this.config.width; var h = this.config.height; var data = []; data.push('<svg width="' + w + 'px" height="' + h + 'px" viewBox="0 0 ' + w + " " + h + '" xmlns="http://www.w3.org/2000/svg">'); data.push('<foreignObject width="100%" height="100%">'); data.push('<body xmlns="http://www.w3.org/1999/xhtml">'); data.push(this.xhrLoader.responseText); data.push("</body>"); data.push("</foreignObject>"); data.push("</svg>"); var svg = [data.join("\n")]; var _this = this; try { var blob = new window.Blob(svg, { type: "image/svg+xml;charset=utf-8" }) } catch (e) { _this.state = CONST.FILE_ERRORED; _this.onProcessComplete(); return } this.data = new Image; this.data.crossOrigin = this.crossOrigin; this.data.onload = function() { File.revokeObjectURL(_this.data); _this.onProcessComplete() }; this.data.onerror = function() { File.revokeObjectURL(_this.data); _this.onProcessError() }; File.createObjectURL(this.data, blob, "image/svg+xml") }, addToCache: function() { var texture = this.cache.addImage(this.key, this.data); this.pendingDestroy(texture) } }); FileTypesManager.register("htmlTexture", function(key, url, width, height, xhrSettings) { if (Array.isArray(key)) { for (var i = 0; i < key.length; i++) { this.addFile(new HTMLTextureFile(this, key[i])) } } else { this.addFile(new HTMLTextureFile(this, key, url, width, height, xhrSettings)) } return this }); module.exports = HTMLTextureFile }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(1); var ImageFile = __webpack_require__(68); var IsPlainObject = __webpack_require__(7); var JSONFile = __webpack_require__(57); var MultiFile = __webpack_require__(69); var MultiAtlasFile = new Class({ Extends: MultiFile, initialize: function MultiAtlasFile(loader, key, atlasURL, path, baseURL, atlasXhrSettings, textureXhrSettings) { if (IsPlainObject(key)) { var config = key; key = GetFastValue(config, "key"); atlasURL = GetFastValue(config, "url"); atlasXhrSettings = GetFastValue(config, "xhrSettings"); path = GetFastValue(config, "path"); baseURL = GetFastValue(config, "baseURL"); textureXhrSettings = GetFastValue(config, "textureXhrSettings") } var data = new JSONFile(loader, key, atlasURL, atlasXhrSettings); MultiFile.call(this, loader, "multiatlas", key, [data]); this.config.path = path; this.config.baseURL = baseURL; this.config.textureXhrSettings = textureXhrSettings }, onFileComplete: function(file) { var index = this.files.indexOf(file); if (index !== -1) { this.pending--; if (file.type === "json" && file.data.hasOwnProperty("textures")) { var textures = file.data.textures; var config = this.config; var loader = this.loader; var currentBaseURL = loader.baseURL; var currentPath = loader.path; var currentPrefix = loader.prefix; var baseURL = GetFastValue(config, "baseURL", currentBaseURL); var path = GetFastValue(config, "path", currentPath); var prefix = GetFastValue(config, "prefix", currentPrefix); var textureXhrSettings = GetFastValue(config, "textureXhrSettings"); loader.setBaseURL(baseURL); loader.setPath(path); loader.setPrefix(prefix); for (var i = 0; i < textures.length; i++) { var textureURL = textures[i].image; var key = "_MA_" + textureURL; var image = new ImageFile(loader, key, textureURL, textureXhrSettings); this.addToMultiFile(image); loader.addFile(image); if (textures[i].normalMap) { var normalMap = new ImageFile(loader, key, textures[i].normalMap, textureXhrSettings); normalMap.type = "normalMap"; image.setLink(normalMap); this.addToMultiFile(normalMap); loader.addFile(normalMap) } } loader.setBaseURL(currentBaseURL); loader.setPath(currentPath); loader.setPrefix(currentPrefix) } } }, addToCache: function() { if (this.isReadyToProcess()) { var fileJSON = this.files[0]; fileJSON.addToCache(); var data = []; var images = []; var normalMaps = []; for (var i = 1; i < this.files.length; i++) { var file = this.files[i]; if (file.type === "normalMap") { continue } var key = file.key.substr(4); var image = file.data; for (var t = 0; t < fileJSON.data.textures.length; t++) { var item = fileJSON.data.textures[t]; if (item.image === key) { images.push(image); data.push(item); if (file.linkFile) { normalMaps.push(file.linkFile.data) } break } } } if (normalMaps.length === 0) { normalMaps = undefined } this.loader.textureManager.addAtlasJSONArray(this.key, images, data, normalMaps); this.complete = true; for (i = 0; i < this.files.length; i++) { this.files[i].pendingDestroy() } } } }); FileTypesManager.register("multiatlas", function(key, atlasURL, path, baseURL, atlasXhrSettings) { var multifile; if (Array.isArray(key)) { for (var i = 0; i < key.length; i++) { multifile = new MultiAtlasFile(this, key[i]); this.addFile(multifile.files) } } else { multifile = new MultiAtlasFile(this, key, atlasURL, path, baseURL, atlasXhrSettings); this.addFile(multifile.files) } return this }); module.exports = MultiAtlasFile }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var CONST = __webpack_require__(20); var FileTypesManager = __webpack_require__(8); var JSONFile = __webpack_require__(57); var PackFile = new Class({ Extends: JSONFile, initialize: function PackFile(loader, key, url, xhrSettings, dataKey) { JSONFile.call(this, loader, key, url, xhrSettings, dataKey); this.type = "packfile" }, onProcess: function() { if (this.state !== CONST.FILE_POPULATED) { this.state = CONST.FILE_PROCESSING; this.data = JSON.parse(this.xhrLoader.responseText) } this.loader.addPack(this.data, this.config); this.onProcessComplete() } }); FileTypesManager.register("pack", function(key, url, packKey, xhrSettings) { if (Array.isArray(key)) { for (var i = 0; i < key.length; i++) { this.addFile(new PackFile(this, key[i])) } } else { this.addFile(new PackFile(this, key, url, xhrSettings, packKey)) } return this }); module.exports = PackFile }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var CONST = __webpack_require__(20); var File = __webpack_require__(22); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(1); var IsPlainObject = __webpack_require__(7); var PluginFile = new Class({ Extends: File, initialize: function PluginFile(loader, key, url, start, mapping, xhrSettings) { var extension = "js"; if (IsPlainObject(key)) { var config = key; key = GetFastValue(config, "key"); url = GetFastValue(config, "url"); xhrSettings = GetFastValue(config, "xhrSettings"); extension = GetFastValue(config, "extension", extension); start = GetFastValue(config, "start"); mapping = GetFastValue(config, "mapping") } var fileConfig = { type: "plugin", cache: false, extension: extension, responseType: "text", key: key, url: url, xhrSettings: xhrSettings, config: { start: start, mapping: mapping } }; File.call(this, loader, fileConfig); if (typeof url === "function") { this.data = url; this.state = CONST.FILE_POPULATED } }, onProcess: function() { var pluginManager = this.loader.systems.plugins; var config = this.config; var start = GetFastValue(config, "start", false); var mapping = GetFastValue(config, "mapping", null); if (this.state === CONST.FILE_POPULATED) { pluginManager.install(this.key, this.data, start, mapping) } else { this.state = CONST.FILE_PROCESSING; this.data = document.createElement("script"); this.data.language = "javascript"; this.data.type = "text/javascript"; this.data.defer = false; this.data.text = this.xhrLoader.responseText; document.head.appendChild(this.data); pluginManager.install(this.key, window[this.key], start, mapping) } this.onProcessComplete() } }); FileTypesManager.register("plugin", function(key, url, start, mapping, xhrSettings) { if (Array.isArray(key)) { for (var i = 0; i < key.length; i++) { this.addFile(new PluginFile(this, key[i])) } } else { this.addFile(new PluginFile(this, key, url, start, mapping, xhrSettings)) } return this }); module.exports = PluginFile }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var CONST = __webpack_require__(20); var File = __webpack_require__(22); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(1); var IsPlainObject = __webpack_require__(7); var ScenePluginFile = new Class({ Extends: File, initialize: function ScenePluginFile(loader, key, url, systemKey, sceneKey, xhrSettings) { var extension = "js"; if (IsPlainObject(key)) { var config = key; key = GetFastValue(config, "key"); url = GetFastValue(config, "url"); xhrSettings = GetFastValue(config, "xhrSettings"); extension = GetFastValue(config, "extension", extension); systemKey = GetFastValue(config, "systemKey"); sceneKey = GetFastValue(config, "sceneKey") } var fileConfig = { type: "scenePlugin", cache: false, extension: extension, responseType: "text", key: key, url: url, xhrSettings: xhrSettings, config: { systemKey: systemKey, sceneKey: sceneKey } }; File.call(this, loader, fileConfig); if (typeof url === "function") { this.data = url; this.state = CONST.FILE_POPULATED } }, onProcess: function() { var pluginManager = this.loader.systems.plugins; var config = this.config; var key = this.key; var systemKey = GetFastValue(config, "systemKey", key); var sceneKey = GetFastValue(config, "sceneKey", key); if (this.state === CONST.FILE_POPULATED) { pluginManager.installScenePlugin(systemKey, this.data, sceneKey, this.loader.scene) } else { this.state = CONST.FILE_PROCESSING; this.data = document.createElement("script"); this.data.language = "javascript"; this.data.type = "text/javascript"; this.data.defer = false; this.data.text = this.xhrLoader.responseText; document.head.appendChild(this.data); pluginManager.installScenePlugin(systemKey, window[this.key], sceneKey, this.loader.scene) } this.onProcessComplete() } }); FileTypesManager.register("scenePlugin", function(key, url, systemKey, sceneKey, xhrSettings) { if (Array.isArray(key)) { for (var i = 0; i < key.length; i++) { this.addFile(new ScenePluginFile(this, key[i])) } } else { this.addFile(new ScenePluginFile(this, key, url, systemKey, sceneKey, xhrSettings)) } return this }); module.exports = ScenePluginFile }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var CONST = __webpack_require__(20); var File = __webpack_require__(22); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(1); var IsPlainObject = __webpack_require__(7); var ScriptFile = new Class({ Extends: File, initialize: function ScriptFile(loader, key, url, xhrSettings) { var extension = "js"; if (IsPlainObject(key)) { var config = key; key = GetFastValue(config, "key"); url = GetFastValue(config, "url"); xhrSettings = GetFastValue(config, "xhrSettings"); extension = GetFastValue(config, "extension", extension) } var fileConfig = { type: "script", cache: false, extension: extension, responseType: "text", key: key, url: url, xhrSettings: xhrSettings }; File.call(this, loader, fileConfig) }, onProcess: function() { this.state = CONST.FILE_PROCESSING; this.data = document.createElement("script"); this.data.language = "javascript"; this.data.type = "text/javascript"; this.data.defer = false; this.data.text = this.xhrLoader.responseText; document.head.appendChild(this.data); this.onProcessComplete() } }); FileTypesManager.register("script", function(key, url, xhrSettings) { if (Array.isArray(key)) { for (var i = 0; i < key.length; i++) { this.addFile(new ScriptFile(this, key[i])) } } else { this.addFile(new ScriptFile(this, key, url, xhrSettings)) } return this }); module.exports = ScriptFile }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var FileTypesManager = __webpack_require__(8); var ImageFile = __webpack_require__(68); var SpriteSheetFile = new Class({ Extends: ImageFile, initialize: function SpriteSheetFile(loader, key, url, frameConfig, xhrSettings) { ImageFile.call(this, loader, key, url, xhrSettings, frameConfig); this.type = "spritesheet" }, addToCache: function() { var texture = this.cache.addSpriteSheet(this.key, this.data, this.config); this.pendingDestroy(texture) } }); FileTypesManager.register("spritesheet", function(key, url, frameConfig, xhrSettings) { if (Array.isArray(key)) { for (var i = 0; i < key.length; i++) { this.addFile(new SpriteSheetFile(this, key[i])) } } else { this.addFile(new SpriteSheetFile(this, key, url, frameConfig, xhrSettings)) } return this }); module.exports = SpriteSheetFile }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var CONST = __webpack_require__(20); var File = __webpack_require__(22); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(1); var IsPlainObject = __webpack_require__(7); var SVGFile = new Class({ Extends: File, initialize: function SVGFile(loader, key, url, svgConfig, xhrSettings) { var extension = "svg"; if (IsPlainObject(key)) { var config = key; key = GetFastValue(config, "key"); url = GetFastValue(config, "url"); svgConfig = GetFastValue(config, "svgConfig", {}); xhrSettings = GetFastValue(config, "xhrSettings"); extension = GetFastValue(config, "extension", extension) } var fileConfig = { type: "svg", cache: loader.textureManager, extension: extension, responseType: "text", key: key, url: url, xhrSettings: xhrSettings, config: { width: GetFastValue(svgConfig, "width"), height: GetFastValue(svgConfig, "height"), scale: GetFastValue(svgConfig, "scale") } }; File.call(this, loader, fileConfig) }, onProcess: function() { this.state = CONST.FILE_PROCESSING; var text = this.xhrLoader.responseText; var svg = [text]; var width = this.config.width; var height = this.config.height; var scale = this.config.scale; resize: if (width && height || scale) { var xml = null; var parser = new DOMParser; xml = parser.parseFromString(text, "text/xml"); var svgXML = xml.getElementsByTagName("svg")[0]; var hasViewBox = svgXML.hasAttribute("viewBox"); var svgWidth = parseFloat(svgXML.getAttribute("width")); var svgHeight = parseFloat(svgXML.getAttribute("height")); if (!hasViewBox && svgWidth && svgHeight) { svgXML.setAttribute("viewBox", "0 0 " + svgWidth + " " + svgHeight) } else if (hasViewBox && !svgWidth && !svgHeight) { var viewBox = svgXML.getAttribute("viewBox").split(/\s+|,/); svgWidth = viewBox[2]; svgHeight = viewBox[3] } if (scale) { if (svgWidth && svgHeight) { width = svgWidth * scale; height = svgHeight * scale } else { break resize } } svgXML.setAttribute("width", width.toString() + "px"); svgXML.setAttribute("height", height.toString() + "px"); svg = [(new XMLSerializer).serializeToString(svgXML)] } try { var blob = new window.Blob(svg, { type: "image/svg+xml;charset=utf-8" }) } catch (e) { this.onProcessError(); return } this.data = new Image; this.data.crossOrigin = this.crossOrigin; var _this = this; var retry = false; this.data.onload = function() { if (!retry) { File.revokeObjectURL(_this.data) } _this.onProcessComplete() }; this.data.onerror = function() { if (!retry) { retry = true; File.revokeObjectURL(_this.data); _this.data.src = "data:image/svg+xml," + encodeURIComponent(svg.join("")) } else { _this.onProcessError() } }; File.createObjectURL(this.data, blob, "image/svg+xml") }, addToCache: function() { var texture = this.cache.addImage(this.key, this.data); this.pendingDestroy(texture) } }); FileTypesManager.register("svg", function(key, url, svgConfig, xhrSettings) { if (Array.isArray(key)) { for (var i = 0; i < key.length; i++) { this.addFile(new SVGFile(this, key[i])) } } else { this.addFile(new SVGFile(this, key, url, svgConfig, xhrSettings)) } return this }); module.exports = SVGFile }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var CONST = __webpack_require__(20); var File = __webpack_require__(22); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(1); var IsPlainObject = __webpack_require__(7); var TILEMAP_FORMATS = __webpack_require__(31); var TilemapCSVFile = new Class({ Extends: File, initialize: function TilemapCSVFile(loader, key, url, xhrSettings) { var extension = "csv"; if (IsPlainObject(key)) { var config = key; key = GetFastValue(config, "key"); url = GetFastValue(config, "url"); xhrSettings = GetFastValue(config, "xhrSettings"); extension = GetFastValue(config, "extension", extension) } var fileConfig = { type: "tilemapCSV", cache: loader.cacheManager.tilemap, extension: extension, responseType: "text", key: key, url: url, xhrSettings: xhrSettings }; File.call(this, loader, fileConfig); this.tilemapFormat = TILEMAP_FORMATS.CSV }, onProcess: function() { this.state = CONST.FILE_PROCESSING; this.data = this.xhrLoader.responseText; this.onProcessComplete() }, addToCache: function() { var tiledata = { format: this.tilemapFormat, data: this.data }; this.cache.add(this.key, tiledata); this.pendingDestroy(tiledata) } }); FileTypesManager.register("tilemapCSV", function(key, url, xhrSettings) { if (Array.isArray(key)) { for (var i = 0; i < key.length; i++) { this.addFile(new TilemapCSVFile(this, key[i])) } } else { this.addFile(new TilemapCSVFile(this, key, url, xhrSettings)) } return this }); module.exports = TilemapCSVFile }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var FileTypesManager = __webpack_require__(8); var JSONFile = __webpack_require__(57); var TILEMAP_FORMATS = __webpack_require__(31); var TilemapImpactFile = new Class({ Extends: JSONFile, initialize: function TilemapImpactFile(loader, key, url, xhrSettings) { JSONFile.call(this, loader, key, url, xhrSettings); this.type = "tilemapJSON"; this.cache = loader.cacheManager.tilemap }, addToCache: function() { var tiledata = { format: TILEMAP_FORMATS.WELTMEISTER, data: this.data }; this.cache.add(this.key, tiledata); this.pendingDestroy(tiledata) } }); FileTypesManager.register("tilemapImpact", function(key, url, xhrSettings) { if (Array.isArray(key)) { for (var i = 0; i < key.length; i++) { this.addFile(new TilemapImpactFile(this, key[i])) } } else { this.addFile(new TilemapImpactFile(this, key, url, xhrSettings)) } return this }); module.exports = TilemapImpactFile }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var FileTypesManager = __webpack_require__(8); var JSONFile = __webpack_require__(57); var TILEMAP_FORMATS = __webpack_require__(31); var TilemapJSONFile = new Class({ Extends: JSONFile, initialize: function TilemapJSONFile(loader, key, url, xhrSettings) { JSONFile.call(this, loader, key, url, xhrSettings); this.type = "tilemapJSON"; this.cache = loader.cacheManager.tilemap }, addToCache: function() { var tiledata = { format: TILEMAP_FORMATS.TILED_JSON, data: this.data }; this.cache.add(this.key, tiledata); this.pendingDestroy(tiledata) } }); FileTypesManager.register("tilemapTiledJSON", function(key, url, xhrSettings) { if (Array.isArray(key)) { for (var i = 0; i < key.length; i++) { this.addFile(new TilemapJSONFile(this, key[i])) } } else { this.addFile(new TilemapJSONFile(this, key, url, xhrSettings)) } return this }); module.exports = TilemapJSONFile }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(1); var ImageFile = __webpack_require__(68); var IsPlainObject = __webpack_require__(7); var MultiFile = __webpack_require__(69); var TextFile = __webpack_require__(400); var UnityAtlasFile = new Class({ Extends: MultiFile, initialize: function UnityAtlasFile(loader, key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings) { var image; var data; if (IsPlainObject(key)) { var config = key; image = new ImageFile(loader, { key: key, url: GetFastValue(config, "textureURL"), extension: GetFastValue(config, "textureExtension", "png"), normalMap: GetFastValue(config, "normalMap"), xhrSettings: GetFastValue(config, "textureXhrSettings") }); data = new TextFile(loader, { key: key, url: GetFastValue(config, "atlasURL"), extension: GetFastValue(config, "atlasExtension", "txt"), xhrSettings: GetFastValue(config, "atlasXhrSettings") }) } else { image = new ImageFile(loader, key, textureURL, textureXhrSettings); data = new TextFile(loader, key, atlasURL, atlasXhrSettings) } if (image.linkFile) { MultiFile.call(this, loader, "unityatlas", key, [image, data, image.linkFile]) } else { MultiFile.call(this, loader, "unityatlas", key, [image, data]) } }, addToCache: function() { if (this.failed === 0 && !this.complete) { var image = this.files[0]; var text = this.files[1]; var normalMap = this.files[2] ? this.files[2].data : null; this.loader.textureManager.addUnityAtlas(image.key, image.data, text.data, normalMap); text.addToCache(); this.complete = true } } }); FileTypesManager.register("unityAtlas", function(key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings) { var multifile; if (Array.isArray(key)) { for (var i = 0; i < key.length; i++) { multifile = new UnityAtlasFile(this, key[i]); this.addFile(multifile.files) } } else { multifile = new UnityAtlasFile(this, key, textureURL, atlasURL, textureXhrSettings, atlasXhrSettings); this.addFile(multifile.files) } return this }); module.exports = UnityAtlasFile }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var CONST = __webpack_require__(20); var CustomSet = __webpack_require__(81); var EventEmitter = __webpack_require__(11); var FileTypesManager = __webpack_require__(8); var GetFastValue = __webpack_require__(1); var PluginCache = __webpack_require__(15); var XHRSettings = __webpack_require__(129); var LoaderPlugin = new Class({ Extends: EventEmitter, initialize: function LoaderPlugin(scene) { EventEmitter.call(this); var gameConfig = scene.sys.game.config; var sceneConfig = scene.sys.settings.loader; this.scene = scene; this.systems = scene.sys; this.cacheManager = scene.sys.cache; this.textureManager = scene.sys.textures; FileTypesManager.install(this); this.prefix = ""; this.path = ""; this.baseURL = ""; this.setBaseURL(GetFastValue(sceneConfig, "baseURL", gameConfig.loaderBaseURL)); this.setPath(GetFastValue(sceneConfig, "path", gameConfig.loaderPath)); this.setPrefix(GetFastValue(sceneConfig, "prefix", gameConfig.loaderPrefix)); this.maxParallelDownloads = GetFastValue(sceneConfig, "maxParallelDownloads", gameConfig.loaderMaxParallelDownloads); this.xhr = XHRSettings(GetFastValue(sceneConfig, "responseType", gameConfig.loaderResponseType), GetFastValue(sceneConfig, "async", gameConfig.loaderAsync), GetFastValue(sceneConfig, "user", gameConfig.loaderUser), GetFastValue(sceneConfig, "password", gameConfig.loaderPassword), GetFastValue(sceneConfig, "timeout", gameConfig.loaderTimeout)); this.crossOrigin = GetFastValue(sceneConfig, "crossOrigin", gameConfig.loaderCrossOrigin); this.totalToLoad = 0; this.progress = 0; this.list = new CustomSet; this.inflight = new CustomSet; this.queue = new CustomSet; this._deleteQueue = new CustomSet; this.totalFailed = 0; this.totalComplete = 0; this.state = CONST.LOADER_IDLE; scene.sys.events.once("boot", this.boot, this); scene.sys.events.on("start", this.pluginStart, this) }, boot: function() { this.systems.events.once("destroy", this.destroy, this) }, pluginStart: function() { this.systems.events.once("shutdown", this.shutdown, this) }, setBaseURL: function(url) { if (url === undefined) { url = "" } if (url !== "" && url.substr(-1) !== "/") { url = url.concat("/") } this.baseURL = url; return this }, setPath: function(path) { if (path === undefined) { path = "" } if (path !== "" && path.substr(-1) !== "/") { path = path.concat("/") } this.path = path; return this }, setPrefix: function(prefix) { if (prefix === undefined) { prefix = "" } this.prefix = prefix; return this }, setCORS: function(crossOrigin) { this.crossOrigin = crossOrigin; return this }, addFile: function(file) { if (!Array.isArray(file)) { file = [file] } for (var i = 0; i < file.length; i++) { var item = file[i]; if (!this.keyExists(item)) { this.list.set(item); this.emit("addfile", item.key, item.type, this, item); if (this.isLoading()) { this.totalToLoad++; this.updateProgress() } } } }, keyExists: function(file) { var keyConflict = file.hasCacheConflict(); if (!keyConflict) { this.list.iterate(function(item) { if (item.type === file.type && item.key === file.key) { keyConflict = true; return false } }) } if (!keyConflict && this.isLoading()) { this.inflight.iterate(function(item) { if (item.type === file.type && item.key === file.key) { keyConflict = true; return false } }); this.queue.iterate(function(item) { if (item.type === file.type && item.key === file.key) { keyConflict = true; return false } }) } return keyConflict }, addPack: function(pack, packKey) { if (packKey && pack.hasOwnProperty(packKey)) { pack = { packKey: pack[packKey] } } var total = 0; var currentBaseURL = this.baseURL; var currentPath = this.path; var currentPrefix = this.prefix; for (var key in pack) { var config = pack[key]; var baseURL = GetFastValue(config, "baseURL", currentBaseURL); var path = GetFastValue(config, "path", currentPath); var prefix = GetFastValue(config, "prefix", currentPrefix); var files = GetFastValue(config, "files", null); var defaultType = GetFastValue(config, "defaultType", "void"); if (Array.isArray(files)) { this.setBaseURL(baseURL); this.setPath(path); this.setPrefix(prefix); for (var i = 0; i < files.length; i++) { var file = files[i]; var type = file.hasOwnProperty("type") ? file.type : defaultType; if (this[type]) { this[type](file); total++ } } } } this.setBaseURL(currentBaseURL); this.setPath(currentPath); this.setPrefix(currentPrefix); return total > 0 }, isLoading: function() { return this.state === CONST.LOADER_LOADING || this.state === CONST.LOADER_PROCESSING }, isReady: function() { return this.state === CONST.LOADER_IDLE || this.state === CONST.LOADER_COMPLETE }, start: function() { if (!this.isReady()) { return } this.progress = 0; this.totalFailed = 0; this.totalComplete = 0; this.totalToLoad = this.list.size; this.emit("start", this); if (this.list.size === 0) { this.loadComplete() } else { this.state = CONST.LOADER_LOADING; this.inflight.clear(); this.queue.clear(); this.updateProgress(); this.checkLoadQueue(); this.systems.events.on("update", this.update, this) } }, updateProgress: function() { this.progress = 1 - (this.list.size + this.inflight.size) / this.totalToLoad; this.emit("progress", this.progress) }, update: function() { if (this.state === CONST.LOADER_LOADING && this.list.size > 0 && this.inflight.size < this.maxParallelDownloads) { this.checkLoadQueue() } }, checkLoadQueue: function() { this.list.each(function(file) { if (file.state === CONST.FILE_POPULATED || file.state === CONST.FILE_PENDING && this.inflight.size < this.maxParallelDownloads) { this.inflight.set(file); this.list.delete(file); if (!file.crossOrigin) { file.crossOrigin = this.crossOrigin } file.load() } if (this.inflight.size === this.maxParallelDownloads) { return false } }, this) }, nextFile: function(file, success) { if (!this.inflight) { return } this.inflight.delete(file); this.updateProgress(); if (success) { this.totalComplete++; this.queue.set(file); this.emit("load", file); file.onProcess() } else { this.totalFailed++; this._deleteQueue.set(file); this.emit("loaderror", file); this.fileProcessComplete(file) } }, fileProcessComplete: function(file) { if (!this.scene || !this.systems || !this.systems.game || this.systems.game.pendingDestroy) { return } if (file.state === CONST.FILE_ERRORED) { if (file.multiFile) { file.multiFile.onFileFailed(file) } } else if (file.state === CONST.FILE_COMPLETE) { if (file.multiFile) { if (file.multiFile.isReadyToProcess()) { file.multiFile.addToCache() } } else { file.addToCache() } } this.queue.delete(file); if (this.list.size === 0 && this.inflight.size === 0 && this.queue.size === 0) { this.loadComplete() } }, loadComplete: function() { this.emit("loadcomplete", this); this.list.clear(); this.inflight.clear(); this.queue.clear(); this.progress = 1; this.state = CONST.LOADER_COMPLETE; this.systems.events.off("update", this.update, this); this._deleteQueue.iterateLocal("destroy"); this._deleteQueue.clear(); this.emit("complete", this, this.totalComplete, this.totalFailed) }, flagForRemoval: function(file) { this._deleteQueue.set(file) }, saveJSON: function(data, filename) { return this.save(JSON.stringify(data), filename) }, save: function(data, filename, filetype) { if (filename === undefined) { filename = "file.json" } if (filetype === undefined) { filetype = "application/json" } var blob = new Blob([data], { type: filetype }); var url = URL.createObjectURL(blob); var a = document.createElement("a"); a.download = filename; a.textContent = "Download " + filename; a.href = url; a.click(); return this }, reset: function() { this.list.clear(); this.inflight.clear(); this.queue.clear(); var gameConfig = this.systems.game.config; var sceneConfig = this.systems.settings.loader; this.setBaseURL(GetFastValue(sceneConfig, "baseURL", gameConfig.loaderBaseURL)); this.setPath(GetFastValue(sceneConfig, "path", gameConfig.loaderPath)); this.setPrefix(GetFastValue(sceneConfig, "prefix", gameConfig.loaderPrefix)); this.state = CONST.LOADER_IDLE }, shutdown: function() { this.reset(); this.state = CONST.LOADER_SHUTDOWN; this.systems.events.off("update", this.update, this); this.systems.events.off("shutdown", this.shutdown, this) }, destroy: function() { this.shutdown(); this.state = CONST.LOADER_DESTROYED; this.systems.events.off("update", this.update, this); this.systems.events.off("start", this.pluginStart, this); this.list = null; this.inflight = null; this.queue = null; this.scene = null; this.systems = null; this.textureManager = null; this.cacheManager = null } }); PluginCache.register("Loader", LoaderPlugin, "load"); module.exports = LoaderPlugin }, function(module, exports, __webpack_require__) { var CONST = __webpack_require__(18); var Extend = __webpack_require__(19); var PhaserMath = { Angle: __webpack_require__(974), Distance: __webpack_require__(982), Easing: __webpack_require__(984), Fuzzy: __webpack_require__(985), Interpolation: __webpack_require__(988), Pow2: __webpack_require__(993), Snap: __webpack_require__(995), RandomDataGenerator: __webpack_require__(238), Average: __webpack_require__(997), Bernstein: __webpack_require__(406), Between: __webpack_require__(167), CatmullRom: __webpack_require__(166), CeilTo: __webpack_require__(998), Clamp: __webpack_require__(23), DegToRad: __webpack_require__(36), Difference: __webpack_require__(999), Factorial: __webpack_require__(407), FloatBetween: __webpack_require__(350), FloorTo: __webpack_require__(1e3), FromPercent: __webpack_require__(90), GetSpeed: __webpack_require__(1001), IsEven: __webpack_require__(1002), IsEvenStrict: __webpack_require__(1003), Linear: __webpack_require__(113), MaxAdd: __webpack_require__(1004), MinSub: __webpack_require__(1005), Percent: __webpack_require__(1006), RadToDeg: __webpack_require__(165), RandomXY: __webpack_require__(1007), RandomXYZ: __webpack_require__(409), RandomXYZW: __webpack_require__(410), Rotate: __webpack_require__(411), RotateAround: __webpack_require__(247), RotateAroundDistance: __webpack_require__(154), RoundAwayFromZero: __webpack_require__(336), RoundTo: __webpack_require__(1008), SinCosTableGenerator: __webpack_require__(1009), SmootherStep: __webpack_require__(155), SmoothStep: __webpack_require__(156), TransformXY: __webpack_require__(317), Within: __webpack_require__(1010), Wrap: __webpack_require__(55), Vector2: __webpack_require__(3), Vector3: __webpack_require__(86), Vector4: __webpack_require__(125), Matrix3: __webpack_require__(412), Matrix4: __webpack_require__(202), Quaternion: __webpack_require__(413), RotateVec3: __webpack_require__(414) }; PhaserMath = Extend(false, PhaserMath, CONST); module.exports = PhaserMath }, function(module, exports, __webpack_require__) { module.exports = { Between: __webpack_require__(975), BetweenY: __webpack_require__(976), BetweenPoints: __webpack_require__(977), BetweenPointsY: __webpack_require__(978), Reverse: __webpack_require__(979), RotateTo: __webpack_require__(980), ShortestBetween: __webpack_require__(981), Normalize: __webpack_require__(401), Wrap: __webpack_require__(150), WrapDegrees: __webpack_require__(151) } }, function(module, exports) { var Between = function(x1, y1, x2, y2) { return Math.atan2(y2 - y1, x2 - x1) }; module.exports = Between }, function(module, exports) { var BetweenY = function(x1, y1, x2, y2) { return Math.atan2(x2 - x1, y2 - y1) }; module.exports = BetweenY }, function(module, exports) { var BetweenPoints = function(point1, point2) { return Math.atan2(point2.y - point1.y, point2.x - point1.x) }; module.exports = BetweenPoints }, function(module, exports) { var BetweenPointsY = function(point1, point2) { return Math.atan2(point2.x - point1.x, point2.y - point1.y) }; module.exports = BetweenPointsY }, function(module, exports, __webpack_require__) { var Normalize = __webpack_require__(401); var Reverse = function(angle) { return Normalize(angle + Math.PI) }; module.exports = Reverse }, function(module, exports, __webpack_require__) { var MATH_CONST = __webpack_require__(18); var RotateTo = function(currentAngle, targetAngle, lerp) { if (lerp === undefined) { lerp = .05 } if (currentAngle === targetAngle) { return currentAngle } if (Math.abs(targetAngle - currentAngle) <= lerp || Math.abs(targetAngle - currentAngle) >= MATH_CONST.PI2 - lerp) { currentAngle = targetAngle } else { if (Math.abs(targetAngle - currentAngle) > Math.PI) { if (targetAngle < currentAngle) { targetAngle += MATH_CONST.PI2 } else { targetAngle -= MATH_CONST.PI2 } } if (targetAngle > currentAngle) { currentAngle += lerp } else if (targetAngle < currentAngle) { currentAngle -= lerp } } return currentAngle }; module.exports = RotateTo }, function(module, exports) { var ShortestBetween = function(angle1, angle2) { var difference = angle2 - angle1; if (difference === 0) { return 0 } var times = Math.floor((difference - -180) / 360); return difference - times * 360 }; module.exports = ShortestBetween }, function(module, exports, __webpack_require__) { module.exports = { Between: __webpack_require__(56), Power: __webpack_require__(983), Squared: __webpack_require__(402) } }, function(module, exports) { var DistancePower = function(x1, y1, x2, y2, pow) { if (pow === undefined) { pow = 2 } return Math.sqrt(Math.pow(x2 - x1, pow) + Math.pow(y2 - y1, pow)) }; module.exports = DistancePower }, function(module, exports, __webpack_require__) { module.exports = { Back: __webpack_require__(274), Bounce: __webpack_require__(275), Circular: __webpack_require__(276), Cubic: __webpack_require__(277), Elastic: __webpack_require__(278), Expo: __webpack_require__(279), Linear: __webpack_require__(280), Quadratic: __webpack_require__(281), Quartic: __webpack_require__(282), Quintic: __webpack_require__(283), Sine: __webpack_require__(284), Stepped: __webpack_require__(285) } }, function(module, exports, __webpack_require__) { module.exports = { Ceil: __webpack_require__(986), Equal: __webpack_require__(403), Floor: __webpack_require__(987), GreaterThan: __webpack_require__(404), LessThan: __webpack_require__(405) } }, function(module, exports) { var Ceil = function(value, epsilon) { if (epsilon === undefined) { epsilon = 1e-4 } return Math.ceil(value - epsilon) }; module.exports = Ceil }, function(module, exports) { var Floor = function(value, epsilon) { if (epsilon === undefined) { epsilon = 1e-4 } return Math.floor(value + epsilon) }; module.exports = Floor }, function(module, exports, __webpack_require__) { module.exports = { Bezier: __webpack_require__(989), CatmullRom: __webpack_require__(990), CubicBezier: __webpack_require__(289), Linear: __webpack_require__(991), QuadraticBezier: __webpack_require__(293), SmoothStep: __webpack_require__(315), SmootherStep: __webpack_require__(992) } }, function(module, exports, __webpack_require__) { var Bernstein = __webpack_require__(406); var BezierInterpolation = function(v, k) { var b = 0; var n = v.length - 1; for (var i = 0; i <= n; i++) { b += Math.pow(1 - k, n - i) * Math.pow(k, i) * v[i] * Bernstein(n, i) } return b }; module.exports = BezierInterpolation }, function(module, exports, __webpack_require__) { var CatmullRom = __webpack_require__(166); var CatmullRomInterpolation = function(v, k) { var m = v.length - 1; var f = m * k; var i = Math.floor(f); if (v[0] === v[m]) { if (k < 0) { i = Math.floor(f = m * (1 + k)) } return CatmullRom(f - i, v[(i - 1 + m) % m], v[i], v[(i + 1) % m], v[(i + 2) % m]) } else { if (k < 0) { return v[0] - (CatmullRom(-f, v[0], v[0], v[1], v[1]) - v[0]) } if (k > 1) { return v[m] - (CatmullRom(f - m, v[m], v[m], v[m - 1], v[m - 1]) - v[m]) } return CatmullRom(f - i, v[i ? i - 1 : 0], v[i], v[m < i + 1 ? m : i + 1], v[m < i + 2 ? m : i + 2]) } }; module.exports = CatmullRomInterpolation }, function(module, exports, __webpack_require__) { var Linear = __webpack_require__(113); var LinearInterpolation = function(v, k) { var m = v.length - 1; var f = m * k; var i = Math.floor(f); if (k < 0) { return Linear(v[0], v[1], f) } if (k > 1) { return Linear(v[m], v[m - 1], m - f) } return Linear(v[i], v[i + 1 > m ? m : i + 1], f - i) }; module.exports = LinearInterpolation }, function(module, exports, __webpack_require__) { var SmootherStep = __webpack_require__(155); var SmootherStepInterpolation = function(t, min, max) { return min + (max - min) * SmootherStep(t, 0, 1) }; module.exports = SmootherStepInterpolation }, function(module, exports, __webpack_require__) { module.exports = { GetNext: __webpack_require__(355), IsSize: __webpack_require__(116), IsValue: __webpack_require__(994) } }, function(module, exports) { var IsValuePowerOfTwo = function(value) { return value > 0 && (value & value - 1) === 0 }; module.exports = IsValuePowerOfTwo }, function(module, exports, __webpack_require__) { module.exports = { Ceil: __webpack_require__(408), Floor: __webpack_require__(198), To: __webpack_require__(996) } }, function(module, exports) { var SnapTo = function(value, gap, start, divide) { if (start === undefined) { start = 0 } if (gap === 0) { return value } value -= start; value = gap * Math.round(value / gap); return divide ? (start + value) / gap : start + value }; module.exports = SnapTo }, function(module, exports) { var Average = function(values) { var sum = 0; for (var i = 0; i < values.length; i++) { sum += +values[i] } return sum / values.length }; module.exports = Average }, function(module, exports) { var CeilTo = function(value, place, base) { if (place === undefined) { place = 0 } if (base === undefined) { base = 10 } var p = Math.pow(base, -place); return Math.ceil(value * p) / p }; module.exports = CeilTo }, function(module, exports) { var Difference = function(a, b) { return Math.abs(a - b) }; module.exports = Difference }, function(module, exports) { var FloorTo = function(value, place, base) { if (place === undefined) { place = 0 } if (base === undefined) { base = 10 } var p = Math.pow(base, -place); return Math.floor(value * p) / p }; module.exports = FloorTo }, function(module, exports) { var GetSpeed = function(distance, time) { return distance / time / 1e3 }; module.exports = GetSpeed }, function(module, exports) { var IsEven = function(value) { return value == parseFloat(value) ? !(value % 2) : void 0 }; module.exports = IsEven }, function(module, exports) { var IsEvenStrict = function(value) { return value === parseFloat(value) ? !(value % 2) : void 0 }; module.exports = IsEvenStrict }, function(module, exports) { var MaxAdd = function(value, amount, max) { return Math.min(value + amount, max) }; module.exports = MaxAdd }, function(module, exports) { var MinSub = function(value, amount, min) { return Math.max(value - amount, min) }; module.exports = MinSub }, function(module, exports) { var Percent = function(value, min, max, upperMax) { if (max === undefined) { max = min + 1 } var percentage = (value - min) / (max - min); if (percentage > 1) { if (upperMax !== undefined) { percentage = (upperMax - value) / (upperMax - max); if (percentage < 0) { percentage = 0 } } else { percentage = 1 } } else if (percentage < 0) { percentage = 0 } return percentage }; module.exports = Percent }, function(module, exports) { var RandomXY = function(vector, scale) { if (scale === undefined) { scale = 1 } var r = Math.random() * 2 * Math.PI; vector.x = Math.cos(r) * scale; vector.y = Math.sin(r) * scale; return vector }; module.exports = RandomXY }, function(module, exports) { var RoundTo = function(value, place, base) { if (place === undefined) { place = 0 } if (base === undefined) { base = 10 } var p = Math.pow(base, -place); return Math.round(value * p) / p }; module.exports = RoundTo }, function(module, exports) { var SinCosTableGenerator = function(length, sinAmp, cosAmp, frequency) { if (sinAmp === undefined) { sinAmp = 1 } if (cosAmp === undefined) { cosAmp = 1 } if (frequency === undefined) { frequency = 1 } frequency *= Math.PI / length; var cos = []; var sin = []; for (var c = 0; c < length; c++) { cosAmp -= sinAmp * frequency; sinAmp += cosAmp * frequency; cos[c] = cosAmp; sin[c] = sinAmp } return { sin: sin, cos: cos, length: length } }; module.exports = SinCosTableGenerator }, function(module, exports) { var Within = function(a, b, tolerance) { return Math.abs(a - b) <= tolerance }; module.exports = Within }, function(module, exports, __webpack_require__) { module.exports = { Arcade: __webpack_require__(1012), Impact: __webpack_require__(1034), Matter: __webpack_require__(1054) } }, function(module, exports, __webpack_require__) { var CONST = __webpack_require__(52); var Extend = __webpack_require__(19); var Arcade = { ArcadePhysics: __webpack_require__(1013), Body: __webpack_require__(421), Collider: __webpack_require__(422), Factory: __webpack_require__(415), Group: __webpack_require__(418), Image: __webpack_require__(416), Sprite: __webpack_require__(130), StaticBody: __webpack_require__(428), StaticGroup: __webpack_require__(419), World: __webpack_require__(420) }; Arcade = Extend(false, Arcade, CONST); module.exports = Arcade }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var DegToRad = __webpack_require__(36); var DistanceBetween = __webpack_require__(56); var DistanceSquared = __webpack_require__(402); var Factory = __webpack_require__(415); var GetFastValue = __webpack_require__(1); var Merge = __webpack_require__(80); var PluginCache = __webpack_require__(15); var Vector2 = __webpack_require__(3); var World = __webpack_require__(420); var ArcadePhysics = new Class({ initialize: function ArcadePhysics(scene) { this.scene = scene; this.systems = scene.sys; this.config = this.getConfig(); this.world; this.add; scene.sys.events.once("boot", this.boot, this); scene.sys.events.on("start", this.start, this) }, boot: function() { this.world = new World(this.scene, this.config); this.add = new Factory(this.world); this.systems.events.once("destroy", this.destroy, this) }, start: function() { if (!this.world) { this.world = new World(this.scene, this.config); this.add = new Factory(this.world) } var eventEmitter = this.systems.events; eventEmitter.on("update", this.world.update, this.world); eventEmitter.on("postupdate", this.world.postUpdate, this.world); eventEmitter.once("shutdown", this.shutdown, this) }, getConfig: function() { var gameConfig = this.systems.game.config.physics; var sceneConfig = this.systems.settings.physics; var config = Merge(GetFastValue(sceneConfig, "arcade", {}), GetFastValue(gameConfig, "arcade", {})); return config }, overlap: function(object1, object2, overlapCallback, processCallback, callbackContext) { if (overlapCallback === undefined) { overlapCallback = null } if (processCallback === undefined) { processCallback = null } if (callbackContext === undefined) { callbackContext = overlapCallback } return this.world.collideObjects(object1, object2, overlapCallback, processCallback, callbackContext, true) }, collide: function(object1, object2, collideCallback, processCallback, callbackContext) { if (collideCallback === undefined) { collideCallback = null } if (processCallback === undefined) { processCallback = null } if (callbackContext === undefined) { callbackContext = collideCallback } return this.world.collideObjects(object1, object2, collideCallback, processCallback, callbackContext, false) }, pause: function() { return this.world.pause() }, resume: function() { return this.world.resume() }, accelerateTo: function(gameObject, x, y, speed, xSpeedMax, ySpeedMax) { if (speed === undefined) { speed = 60 } var angle = Math.atan2(y - gameObject.y, x - gameObject.x); gameObject.body.acceleration.setToPolar(angle, speed); if (xSpeedMax !== undefined && ySpeedMax !== undefined) { gameObject.body.maxVelocity.set(xSpeedMax, ySpeedMax) } return angle }, accelerateToObject: function(gameObject, destination, speed, xSpeedMax, ySpeedMax) { return this.accelerateTo(gameObject, destination.x, destination.y, speed, xSpeedMax, ySpeedMax) }, closest: function(source) { var bodies = this.world.tree.all(); var min = Number.MAX_VALUE; var closest = null; var x = source.x; var y = source.y; for (var i = bodies.length - 1; i >= 0; i--) { var target = bodies[i]; var distance = DistanceSquared(x, y, target.x, target.y); if (distance < min) { closest = target; min = distance } } return closest }, furthest: function(source) { var bodies = this.world.tree.all(); var max = -1; var farthest = null; var x = source.x; var y = source.y; for (var i = bodies.length - 1; i >= 0; i--) { var target = bodies[i]; var distance = DistanceSquared(x, y, target.x, target.y); if (distance > max) { farthest = target; max = distance } } return farthest }, moveTo: function(gameObject, x, y, speed, maxTime) { if (speed === undefined) { speed = 60 } if (maxTime === undefined) { maxTime = 0 } var angle = Math.atan2(y - gameObject.y, x - gameObject.x); if (maxTime > 0) { speed = DistanceBetween(gameObject.x, gameObject.y, x, y) / (maxTime / 1e3) } gameObject.body.velocity.setToPolar(angle, speed); return angle }, moveToObject: function(gameObject, destination, speed, maxTime) { return this.moveTo(gameObject, destination.x, destination.y, speed, maxTime) }, velocityFromAngle: function(angle, speed, vec2) { if (speed === undefined) { speed = 60 } if (vec2 === undefined) { vec2 = new Vector2 } return vec2.setToPolar(DegToRad(angle), speed) }, velocityFromRotation: function(rotation, speed, vec2) { if (speed === undefined) { speed = 60 } if (vec2 === undefined) { vec2 = new Vector2 } return vec2.setToPolar(rotation, speed) }, shutdown: function() { if (!this.world) { return } var eventEmitter = this.systems.events; eventEmitter.off("update", this.world.update, this.world); eventEmitter.off("postupdate", this.world.postUpdate, this.world); eventEmitter.off("shutdown", this.shutdown, this); this.add.destroy(); this.world.destroy(); this.add = null; this.world = null }, destroy: function() { this.shutdown(); this.scene.sys.events.off("start", this.start, this); this.scene = null; this.systems = null } }); PluginCache.register("ArcadePhysics", ArcadePhysics, "arcadePhysics"); module.exports = ArcadePhysics }, function(module, exports) { var Acceleration = { setAcceleration: function(x, y) { this.body.acceleration.set(x, y); return this }, setAccelerationX: function(value) { this.body.acceleration.x = value; return this }, setAccelerationY: function(value) { this.body.acceleration.y = value; return this } }; module.exports = Acceleration }, function(module, exports) { var Angular = { setAngularVelocity: function(value) { this.body.angularVelocity = value; return this }, setAngularAcceleration: function(value) { this.body.angularAcceleration = value; return this }, setAngularDrag: function(value) { this.body.angularDrag = value; return this } }; module.exports = Angular }, function(module, exports) { var Bounce = { setBounce: function(x, y) { this.body.bounce.set(x, y); return this }, setBounceX: function(value) { this.body.bounce.x = value; return this }, setBounceY: function(value) { this.body.bounce.y = value; return this }, setCollideWorldBounds: function(value) { this.body.collideWorldBounds = value; return this } }; module.exports = Bounce }, function(module, exports) { var Debug = { setDebug: function(showBody, showVelocity, bodyColor) { this.debugShowBody = showBody; this.debugShowVelocity = showVelocity; this.debugBodyColor = bodyColor; return this }, setDebugBodyColor: function(value) { this.body.debugBodyColor = value; return this }, debugShowBody: { get: function() { return this.body.debugShowBody }, set: function(value) { this.body.debugShowBody = value } }, debugShowVelocity: { get: function() { return this.body.debugShowVelocity }, set: function(value) { this.body.debugShowVelocity = value } }, debugBodyColor: { get: function() { return this.body.debugBodyColor }, set: function(value) { this.body.debugBodyColor = value } } }; module.exports = Debug }, function(module, exports) { var Drag = { setDrag: function(x, y) { this.body.drag.set(x, y); return this }, setDragX: function(value) { this.body.drag.x = value; return this }, setDragY: function(value) { this.body.drag.y = value; return this }, setDamping: function(value) { this.body.useDamping = value; return this } }; module.exports = Drag }, function(module, exports) { var Enable = { enableBody: function(reset, x, y, enableGameObject, showGameObject) { if (reset) { this.body.reset(x, y) } if (enableGameObject) { this.body.gameObject.active = true } if (showGameObject) { this.body.gameObject.visible = true } this.body.enable = true; return this }, disableBody: function(disableGameObject, hideGameObject) { if (disableGameObject === undefined) { disableGameObject = false } if (hideGameObject === undefined) { hideGameObject = false } this.body.stop(); this.body.enable = false; if (disableGameObject) { this.body.gameObject.active = false } if (hideGameObject) { this.body.gameObject.visible = false } return this }, refreshBody: function() { this.body.updateFromGameObject(); return this } }; module.exports = Enable }, function(module, exports) { var Friction = { setFriction: function(x, y) { this.body.friction.set(x, y); return this }, setFrictionX: function(x) { this.body.friction.x = x; return this }, setFrictionY: function(y) { this.body.friction.y = y; return this } }; module.exports = Friction }, function(module, exports) { var Gravity = { setGravity: function(x, y) { this.body.gravity.set(x, y); return this }, setGravityX: function(x) { this.body.gravity.x = x; return this }, setGravityY: function(y) { this.body.gravity.y = y; return this } }; module.exports = Gravity }, function(module, exports) { var Immovable = { setImmovable: function(value) { if (value === undefined) { value = true } this.body.immovable = value; return this } }; module.exports = Immovable }, function(module, exports) { var Mass = { setMass: function(value) { this.body.mass = value; return this } }; module.exports = Mass }, function(module, exports) { var Size = { setOffset: function(x, y) { this.body.setOffset(x, y); return this }, setSize: function(width, height, center) { this.body.setSize(width, height, center); return this }, setCircle: function(radius, offsetX, offsetY) { this.body.setCircle(radius, offsetX, offsetY); return this } }; module.exports = Size }, function(module, exports) { var Velocity = { setVelocity: function(x, y) { this.body.setVelocity(x, y); return this }, setVelocityX: function(x) { this.body.setVelocityX(x); return this }, setVelocityY: function(y) { this.body.setVelocityY(y); return this }, setMaxVelocity: function(x, y) { this.body.maxVelocity.set(x, y); return this } }; module.exports = Velocity }, function(module, exports) { var ProcessTileCallbacks = function(tile, sprite) { if (tile.collisionCallback) { return !tile.collisionCallback.call(tile.collisionCallbackContext, sprite, tile) } else if (tile.layer.callbacks[tile.index]) { return !tile.layer.callbacks[tile.index].callback.call(tile.layer.callbacks[tile.index].callbackContext, sprite, tile) } return true }; module.exports = ProcessTileCallbacks }, function(module, exports, __webpack_require__) { var TileCheckX = __webpack_require__(1028); var TileCheckY = __webpack_require__(1030); var TileIntersectsBody = __webpack_require__(427); var SeparateTile = function(i, body, tile, tileWorldRect, tilemapLayer, tileBias) { var tileLeft = tileWorldRect.left; var tileTop = tileWorldRect.top; var tileRight = tileWorldRect.right; var tileBottom = tileWorldRect.bottom; var faceHorizontal = tile.faceLeft || tile.faceRight; var faceVertical = tile.faceTop || tile.faceBottom; if (!faceHorizontal && !faceVertical) { return false } var ox = 0; var oy = 0; var minX = 0; var minY = 1; if (body.deltaAbsX() > body.deltaAbsY()) { minX = -1 } else if (body.deltaAbsX() < body.deltaAbsY()) { minY = -1 } if (body.deltaX() !== 0 && body.deltaY() !== 0 && faceHorizontal && faceVertical) { minX = Math.min(Math.abs(body.position.x - tileRight), Math.abs(body.right - tileLeft)); minY = Math.min(Math.abs(body.position.y - tileBottom), Math.abs(body.bottom - tileTop)) } if (minX < minY) { if (faceHorizontal) { ox = TileCheckX(body, tile, tileLeft, tileRight, tileBias); if (ox !== 0 && !TileIntersectsBody(tileWorldRect, body)) { return true } } if (faceVertical) { oy = TileCheckY(body, tile, tileTop, tileBottom, tileBias) } } else { if (faceVertical) { oy = TileCheckY(body, tile, tileTop, tileBottom, tileBias); if (oy !== 0 && !TileIntersectsBody(tileWorldRect, body)) { return true } } if (faceHorizontal) { ox = TileCheckX(body, tile, tileLeft, tileRight, tileBias) } } return ox !== 0 || oy !== 0 }; module.exports = SeparateTile }, function(module, exports, __webpack_require__) { var ProcessTileSeparationX = __webpack_require__(1029); var TileCheckX = function(body, tile, tileLeft, tileRight, tileBias) { var ox = 0; if (body.deltaX() < 0 && !body.blocked.left && tile.collideRight && body.checkCollision.left) { if (tile.faceRight && body.x < tileRight) { ox = body.x - tileRight; if (ox < -tileBias) { ox = 0 } } } else if (body.deltaX() > 0 && !body.blocked.right && tile.collideLeft && body.checkCollision.right) { if (tile.faceLeft && body.right > tileLeft) { ox = body.right - tileLeft; if (ox > tileBias) { ox = 0 } } } if (ox !== 0) { if (body.customSeparateX) { body.overlapX = ox } else { ProcessTileSeparationX(body, ox) } } return ox }; module.exports = TileCheckX }, function(module, exports) { var ProcessTileSeparationX = function(body, x) { if (x < 0) { body.blocked.none = false; body.blocked.left = true } else if (x > 0) { body.blocked.none = false; body.blocked.right = true } body.position.x -= x; if (body.bounce.x === 0) { body.velocity.x = 0 } else { body.velocity.x = -body.velocity.x * body.bounce.x } }; module.exports = ProcessTileSeparationX }, function(module, exports, __webpack_require__) { var ProcessTileSeparationY = __webpack_require__(1031); var TileCheckY = function(body, tile, tileTop, tileBottom, tileBias) { var oy = 0; if (body.deltaY() < 0 && !body.blocked.up && tile.collideDown && body.checkCollision.up) { if (tile.faceBottom && body.y < tileBottom) { oy = body.y - tileBottom; if (oy < -tileBias) { oy = 0 } } } else if (body.deltaY() > 0 && !body.blocked.down && tile.collideUp && body.checkCollision.down) { if (tile.faceTop && body.bottom > tileTop) { oy = body.bottom - tileTop; if (oy > tileBias) { oy = 0 } } } if (oy !== 0) { if (body.customSeparateY) { body.overlapY = oy } else { ProcessTileSeparationY(body, oy) } } return oy }; module.exports = TileCheckY }, function(module, exports) { var ProcessTileSeparationY = function(body, y) { if (y < 0) { body.blocked.none = false; body.blocked.up = true } else if (y > 0) { body.blocked.none = false; body.blocked.down = true } body.position.y -= y; if (body.bounce.y === 0) { body.velocity.y = 0 } else { body.velocity.y = -body.velocity.y * body.bounce.y } }; module.exports = ProcessTileSeparationY }, function(module, exports, __webpack_require__) { var GetOverlapX = __webpack_require__(423); var SeparateX = function(body1, body2, overlapOnly, bias) { var overlap = GetOverlapX(body1, body2, overlapOnly, bias); if (overlapOnly || overlap === 0 || body1.immovable && body2.immovable || body1.customSeparateX || body2.customSeparateX) { return overlap !== 0 || body1.embedded && body2.embedded } var v1 = body1.velocity.x; var v2 = body2.velocity.x; if (!body1.immovable && !body2.immovable) { overlap *= .5; body1.x -= overlap; body2.x += overlap; var nv1 = Math.sqrt(v2 * v2 * body2.mass / body1.mass) * (v2 > 0 ? 1 : -1); var nv2 = Math.sqrt(v1 * v1 * body1.mass / body2.mass) * (v1 > 0 ? 1 : -1); var avg = (nv1 + nv2) * .5; nv1 -= avg; nv2 -= avg; body1.velocity.x = avg + nv1 * body1.bounce.x; body2.velocity.x = avg + nv2 * body2.bounce.x } else if (!body1.immovable) { body1.x -= overlap; body1.velocity.x = v2 - v1 * body1.bounce.x; if (body2.moves) { body1.y += (body2.y - body2.prev.y) * body2.friction.y } } else { body2.x += overlap; body2.velocity.x = v1 - v2 * body2.bounce.x; if (body1.moves) { body2.y += (body1.y - body1.prev.y) * body1.friction.y } } return true }; module.exports = SeparateX }, function(module, exports, __webpack_require__) { var GetOverlapY = __webpack_require__(424); var SeparateY = function(body1, body2, overlapOnly, bias) { var overlap = GetOverlapY(body1, body2, overlapOnly, bias); if (overlapOnly || overlap === 0 || body1.immovable && body2.immovable || body1.customSeparateY || body2.customSeparateY) { return overlap !== 0 || body1.embedded && body2.embedded } var v1 = body1.velocity.y; var v2 = body2.velocity.y; if (!body1.immovable && !body2.immovable) { overlap *= .5; body1.y -= overlap; body2.y += overlap; var nv1 = Math.sqrt(v2 * v2 * body2.mass / body1.mass) * (v2 > 0 ? 1 : -1); var nv2 = Math.sqrt(v1 * v1 * body1.mass / body2.mass) * (v1 > 0 ? 1 : -1); var avg = (nv1 + nv2) * .5; nv1 -= avg; nv2 -= avg; body1.velocity.y = avg + nv1 * body1.bounce.y; body2.velocity.y = avg + nv2 * body2.bounce.y } else if (!body1.immovable) { body1.y -= overlap; body1.velocity.y = v2 - v1 * body1.bounce.y; if (body2.moves) { body1.x += (body2.x - body2.prev.x) * body2.friction.x } } else { body2.y += overlap; body2.velocity.y = v1 - v2 * body2.bounce.y; if (body1.moves) { body2.x += (body1.x - body1.prev.x) * body1.friction.x } } return true }; module.exports = SeparateY }, function(module, exports, __webpack_require__) { module.exports = { Body: __webpack_require__(429), COLLIDES: __webpack_require__(101), CollisionMap: __webpack_require__(430), Factory: __webpack_require__(431), Image: __webpack_require__(433), ImpactBody: __webpack_require__(432), ImpactPhysics: __webpack_require__(1050), Sprite: __webpack_require__(434), TYPE: __webpack_require__(102), World: __webpack_require__(435) } }, function(module, exports, __webpack_require__) { var Clamp = __webpack_require__(23); var GetVelocity = function(delta, vel, accel, friction, max) { if (accel) { return Clamp(vel + accel * delta, -max, max) } else if (friction) { var frictionDelta = friction * delta; if (vel - frictionDelta > 0) { return vel - frictionDelta } else if (vel + frictionDelta < 0) { return vel + frictionDelta } else { return 0 } } return Clamp(vel, -max, max) }; module.exports = GetVelocity }, function(module, exports) { var UpdateMotion = function(body, res) { body.standing = false; if (res.collision.y) { if (body.bounciness > 0 && Math.abs(body.vel.y) > body.minBounceVelocity) { body.vel.y *= -body.bounciness } else { if (body.vel.y > 0) { body.standing = true } body.vel.y = 0 } } if (res.collision.x) { if (body.bounciness > 0 && Math.abs(body.vel.x) > body.minBounceVelocity) { body.vel.x *= -body.bounciness } else { body.vel.x = 0 } } if (res.collision.slope) { var s = res.collision.slope; if (body.bounciness > 0) { var proj = body.vel.x * s.nx + body.vel.y * s.ny; body.vel.x = (body.vel.x - s.nx * proj * 2) * body.bounciness; body.vel.y = (body.vel.y - s.ny * proj * 2) * body.bounciness } else { var lengthSquared = s.x * s.x + s.y * s.y; var dot = (body.vel.x * s.x + body.vel.y * s.y) / lengthSquared; body.vel.x = s.x * dot; body.vel.y = s.y * dot; var angle = Math.atan2(s.x, s.y); if (angle > body.slopeStanding.min && angle < body.slopeStanding.max) { body.standing = true } } } body.pos.x = res.pos.x; body.pos.y = res.pos.y }; module.exports = UpdateMotion }, function(module, exports) { var H = .5; var N = 1 / 3; var M = 2 / 3; module.exports = { 2: [0, 1, 1, 0, true], 3: [0, 1, 1, H, true], 4: [0, H, 1, 0, true], 5: [0, 1, 1, M, true], 6: [0, M, 1, N, true], 7: [0, N, 1, 0, true], 8: [H, 1, 0, 0, true], 9: [1, 0, H, 1, true], 10: [H, 1, 1, 0, true], 11: [0, 0, H, 1, true], 12: [0, 0, 1, 0, false], 13: [1, 1, 0, 0, true], 14: [1, H, 0, 0, true], 15: [1, 1, 0, H, true], 16: [1, N, 0, 0, true], 17: [1, M, 0, N, true], 18: [1, 1, 0, M, true], 19: [1, 1, H, 0, true], 20: [H, 0, 0, 1, true], 21: [0, 1, H, 0, true], 22: [H, 0, 1, 1, true], 23: [1, 1, 0, 1, false], 24: [0, 0, 1, 1, true], 25: [0, 0, 1, H, true], 26: [0, H, 1, 1, true], 27: [0, 0, 1, N, true], 28: [0, N, 1, M, true], 29: [0, M, 1, 1, true], 30: [N, 1, 0, 0, true], 31: [1, 0, M, 1, true], 32: [M, 1, 1, 0, true], 33: [0, 0, N, 1, true], 34: [1, 0, 1, 1, false], 35: [1, 0, 0, 1, true], 36: [1, H, 0, 1, true], 37: [1, 0, 0, H, true], 38: [1, M, 0, 1, true], 39: [1, N, 0, M, true], 40: [1, 0, 0, N, true], 41: [M, 1, N, 0, true], 42: [M, 0, N, 1, true], 43: [N, 1, M, 0, true], 44: [N, 0, M, 1, true], 45: [0, 1, 0, 0, false], 52: [1, 1, M, 0, true], 53: [N, 0, 0, 1, true], 54: [0, 1, N, 0, true], 55: [M, 0, 1, 1, true] } }, function(module, exports) { var Acceleration = { setAccelerationX: function(x) { this.accel.x = x; return this }, setAccelerationY: function(y) { this.accel.y = y; return this }, setAcceleration: function(x, y) { this.accel.x = x; this.accel.y = y; return this } }; module.exports = Acceleration }, function(module, exports) { var BodyScale = { setBodySize: function(width, height) { if (height === undefined) { height = width } this.body.size.x = Math.round(width); this.body.size.y = Math.round(height); return this }, setBodyScale: function(scaleX, scaleY) { if (scaleY === undefined) { scaleY = scaleX } var gameObject = this.body.gameObject; if (gameObject) { gameObject.setScale(scaleX, scaleY); return this.setBodySize(gameObject.width * gameObject.scaleX, gameObject.height * gameObject.scaleY) } else { return this.setBodySize(this.body.size.x * scaleX, this.body.size.y * scaleY) } } }; module.exports = BodyScale }, function(module, exports, __webpack_require__) { var TYPE = __webpack_require__(102); var BodyType = { getBodyType: function() { return this.body.type }, setTypeNone: function() { this.body.type = TYPE.NONE; return this }, setTypeA: function() { this.body.type = TYPE.A; return this }, setTypeB: function() { this.body.type = TYPE.B; return this } }; module.exports = BodyType }, function(module, exports) { var Bounce = { setBounce: function(value) { this.body.bounciness = value; return this }, setMinBounceVelocity: function(value) { this.body.minBounceVelocity = value; return this }, bounce: { get: function() { return this.body.bounciness }, set: function(value) { this.body.bounciness = value } } }; module.exports = Bounce }, function(module, exports, __webpack_require__) { var TYPE = __webpack_require__(102); var CheckAgainst = { setAvsB: function() { this.setTypeA(); return this.setCheckAgainstB() }, setBvsA: function() { this.setTypeB(); return this.setCheckAgainstA() }, setCheckAgainstNone: function() { this.body.checkAgainst = TYPE.NONE; return this }, setCheckAgainstA: function() { this.body.checkAgainst = TYPE.A; return this }, setCheckAgainstB: function() { this.body.checkAgainst = TYPE.B; return this }, checkAgainst: { get: function() { return this.body.checkAgainst }, set: function(value) { this.body.checkAgainst = value } } }; module.exports = CheckAgainst }, function(module, exports, __webpack_require__) { var COLLIDES = __webpack_require__(101); var Collides = { _collideCallback: null, _callbackScope: null, setCollideCallback: function(callback, scope) { this._collideCallback = callback; if (scope) { this._callbackScope = scope } return this }, setCollidesNever: function() { this.body.collides = COLLIDES.NEVER; return this }, setLiteCollision: function() { this.body.collides = COLLIDES.LITE; return this }, setPassiveCollision: function() { this.body.collides = COLLIDES.PASSIVE; return this }, setActiveCollision: function() { this.body.collides = COLLIDES.ACTIVE; return this }, setFixedCollision: function() { this.body.collides = COLLIDES.FIXED; return this }, collides: { get: function() { return this.body.collides }, set: function(value) { this.body.collides = value } } }; module.exports = Collides }, function(module, exports) { var Debug = { setDebug: function(showBody, showVelocity, bodyColor) { this.debugShowBody = showBody; this.debugShowVelocity = showVelocity; this.debugBodyColor = bodyColor; return this }, setDebugBodyColor: function(value) { this.body.debugBodyColor = value; return this }, debugShowBody: { get: function() { return this.body.debugShowBody }, set: function(value) { this.body.debugShowBody = value } }, debugShowVelocity: { get: function() { return this.body.debugShowVelocity }, set: function(value) { this.body.debugShowVelocity = value } }, debugBodyColor: { get: function() { return this.body.debugBodyColor }, set: function(value) { this.body.debugBodyColor = value } } }; module.exports = Debug }, function(module, exports) { var Friction = { setFrictionX: function(x) { this.friction.x = x; return this }, setFrictionY: function(y) { this.friction.y = y; return this }, setFriction: function(x, y) { this.friction.x = x; this.friction.y = y; return this } }; module.exports = Friction }, function(module, exports) { var Gravity = { setGravity: function(value) { this.body.gravityFactor = value; return this }, gravity: { get: function() { return this.body.gravityFactor }, set: function(value) { this.body.gravityFactor = value } } }; module.exports = Gravity }, function(module, exports) { var Offset = { setOffset: function(x, y, width, height) { this.body.offset.x = x; this.body.offset.y = y; if (width) { this.setBodySize(width, height) } return this } }; module.exports = Offset }, function(module, exports) { var SetGameObject = { setGameObject: function(gameObject, sync) { if (sync === undefined) { sync = true } if (gameObject) { this.body.gameObject = gameObject; if (sync) { this.syncGameObject() } } else { this.body.gameObject = null } return this }, syncGameObject: function() { var gameObject = this.body.gameObject; if (gameObject) { this.setBodySize(gameObject.width * gameObject.scaleX, gameObject.height * gameObject.scaleY) } return this } }; module.exports = SetGameObject }, function(module, exports) { var Velocity = { setVelocityX: function(x) { this.vel.x = x; return this }, setVelocityY: function(y) { this.vel.y = y; return this }, setVelocity: function(x, y) { if (y === undefined) { y = x } this.vel.x = x; this.vel.y = y; return this }, setMaxVelocity: function(x, y) { if (y === undefined) { y = x } this.maxVel.x = x; this.maxVel.y = y; return this } }; module.exports = Velocity }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Factory = __webpack_require__(431); var GetFastValue = __webpack_require__(1); var Merge = __webpack_require__(80); var PluginCache = __webpack_require__(15); var World = __webpack_require__(435); var ImpactPhysics = new Class({ initialize: function ImpactPhysics(scene) { this.scene = scene; this.systems = scene.sys; this.config = this.getConfig(); this.world; this.add; scene.sys.events.once("boot", this.boot, this); scene.sys.events.on("start", this.start, this) }, boot: function() { this.world = new World(this.scene, this.config); this.add = new Factory(this.world); this.systems.events.once("destroy", this.destroy, this) }, start: function() { if (!this.world) { this.world = new World(this.scene, this.config); this.add = new Factory(this.world) } var eventEmitter = this.systems.events; eventEmitter.on("update", this.world.update, this.world); eventEmitter.once("shutdown", this.shutdown, this) }, getConfig: function() { var gameConfig = this.systems.game.config.physics; var sceneConfig = this.systems.settings.physics; var config = Merge(GetFastValue(sceneConfig, "impact", {}), GetFastValue(gameConfig, "impact", {})); return config }, pause: function() { return this.world.pause() }, resume: function() { return this.world.resume() }, shutdown: function() { var eventEmitter = this.systems.events; eventEmitter.off("update", this.world.update, this.world); eventEmitter.off("shutdown", this.shutdown, this); this.add.destroy(); this.world.destroy(); this.add = null; this.world = null }, destroy: function() { this.shutdown(); this.scene.sys.events.off("start", this.start, this); this.scene = null; this.systems = null } }); PluginCache.register("ImpactPhysics", ImpactPhysics, "impactPhysics"); module.exports = ImpactPhysics }, function(module, exports, __webpack_require__) { var COLLIDES = __webpack_require__(101); var SeperateX = __webpack_require__(1052); var SeperateY = __webpack_require__(1053); var Solver = function(world, bodyA, bodyB) { var weak = null; if (bodyA.collides === COLLIDES.LITE || bodyB.collides === COLLIDES.FIXED) { weak = bodyA } else if (bodyB.collides === COLLIDES.LITE || bodyA.collides === COLLIDES.FIXED) { weak = bodyB } if (bodyA.last.x + bodyA.size.x > bodyB.last.x && bodyA.last.x < bodyB.last.x + bodyB.size.x) { if (bodyA.last.y < bodyB.last.y) { SeperateY(world, bodyA, bodyB, weak) } else { SeperateY(world, bodyB, bodyA, weak) } bodyA.collideWith(bodyB, "y"); bodyB.collideWith(bodyA, "y"); world.emit("collide", bodyA, bodyB, "y") } else if (bodyA.last.y + bodyA.size.y > bodyB.last.y && bodyA.last.y < bodyB.last.y + bodyB.size.y) { if (bodyA.last.x < bodyB.last.x) { SeperateX(world, bodyA, bodyB, weak) } else { SeperateX(world, bodyB, bodyA, weak) } bodyA.collideWith(bodyB, "x"); bodyB.collideWith(bodyA, "x"); world.emit("collide", bodyA, bodyB, "x") } }; module.exports = Solver }, function(module, exports) { var SeperateX = function(world, left, right, weak) { var nudge = left.pos.x + left.size.x - right.pos.x; if (weak) { var strong = left === weak ? right : left; weak.vel.x = -weak.vel.x * weak.bounciness + strong.vel.x; var resWeak = world.collisionMap.trace(weak.pos.x, weak.pos.y, weak === left ? -nudge : nudge, 0, weak.size.x, weak.size.y); weak.pos.x = resWeak.pos.x } else { var v2 = (left.vel.x - right.vel.x) / 2; left.vel.x = -v2; right.vel.x = v2; var resLeft = world.collisionMap.trace(left.pos.x, left.pos.y, -nudge / 2, 0, left.size.x, left.size.y); left.pos.x = Math.floor(resLeft.pos.x); var resRight = world.collisionMap.trace(right.pos.x, right.pos.y, nudge / 2, 0, right.size.x, right.size.y); right.pos.x = Math.ceil(resRight.pos.x) } }; module.exports = SeperateX }, function(module, exports) { var SeperateY = function(world, top, bottom, weak) { var nudge = top.pos.y + top.size.y - bottom.pos.y; var nudgeX; var resTop; if (weak) { var strong = top === weak ? bottom : top; weak.vel.y = -weak.vel.y * weak.bounciness + strong.vel.y; nudgeX = 0; if (weak === top && Math.abs(weak.vel.y - strong.vel.y) < weak.minBounceVelocity) { weak.standing = true; nudgeX = strong.vel.x * world.delta } var resWeak = world.collisionMap.trace(weak.pos.x, weak.pos.y, nudgeX, weak === top ? -nudge : nudge, weak.size.x, weak.size.y); weak.pos.y = resWeak.pos.y; weak.pos.x = resWeak.pos.x } else if (world.gravity && (bottom.standing || top.vel.y > 0)) { resTop = world.collisionMap.trace(top.pos.x, top.pos.y, 0, -(top.pos.y + top.size.y - bottom.pos.y), top.size.x, top.size.y); top.pos.y = resTop.pos.y; if (top.bounciness > 0 && top.vel.y > top.minBounceVelocity) { top.vel.y *= -top.bounciness } else { top.standing = true; top.vel.y = 0 } } else { var v2 = (top.vel.y - bottom.vel.y) / 2; top.vel.y = -v2; bottom.vel.y = v2; nudgeX = bottom.vel.x * world.delta; resTop = world.collisionMap.trace(top.pos.x, top.pos.y, nudgeX, -nudge / 2, top.size.x, top.size.y); top.pos.y = resTop.pos.y; var resBottom = world.collisionMap.trace(bottom.pos.x, bottom.pos.y, 0, nudge / 2, bottom.size.x, bottom.size.y); bottom.pos.y = resBottom.pos.y } }; module.exports = SeperateY }, function(module, exports, __webpack_require__) { module.exports = { Factory: __webpack_require__(436), Image: __webpack_require__(439), Matter: __webpack_require__(208), MatterPhysics: __webpack_require__(1073), PolyDecomp: __webpack_require__(437), Sprite: __webpack_require__(440), TileBody: __webpack_require__(205), World: __webpack_require__(446) } }, function(module, exports, __webpack_require__) { var Components = __webpack_require__(131); var GetFastValue = __webpack_require__(1); var Vector2 = __webpack_require__(3); function hasGetterOrSetter(def) { return !!def.get && typeof def.get === "function" || !!def.set && typeof def.set === "function" } var MatterGameObject = function(world, gameObject, options) { if (options === undefined) { options = {} } var x = gameObject.x; var y = gameObject.y; gameObject.body = { temp: true, position: { x: x, y: y } }; var mixins = [Components.Bounce, Components.Collision, Components.Force, Components.Friction, Components.Gravity, Components.Mass, Components.Sensor, Components.SetBody, Components.Sleep, Components.Static, Components.Transform, Components.Velocity]; mixins.forEach(function(mixin) { for (var key in mixin) { if (hasGetterOrSetter(mixin[key])) { Object.defineProperty(gameObject, key, { get: mixin[key].get, set: mixin[key].set }) } else { Object.defineProperty(gameObject, key, { value: mixin[key] }) } } }); gameObject.world = world; gameObject._tempVec2 = new Vector2(x, y); var shape = GetFastValue(options, "shape", null); if (!shape) { shape = "rectangle" } gameObject.setBody(shape, options); return gameObject }; module.exports = MatterGameObject }, function(module, exports) { var Bounce = { setBounce: function(value) { this.body.restitution = value; return this } }; module.exports = Bounce }, function(module, exports) { var Collision = { setCollisionCategory: function(value) { this.body.collisionFilter.category = value; return this }, setCollisionGroup: function(value) { this.body.collisionFilter.group = value; return this }, setCollidesWith: function(categories) { var flags = 0; if (!Array.isArray(categories)) { flags = categories } else { for (var i = 0; i < categories.length; i++) { flags |= categories[i] } } this.body.collisionFilter.mask = flags; return this } }; module.exports = Collision }, function(module, exports, __webpack_require__) { var Body = __webpack_require__(25); var Force = { applyForce: function(force) { this._tempVec2.set(this.body.position.x, this.body.position.y); Body.applyForce(this.body, this._tempVec2, force); return this }, applyForceFrom: function(position, force) { Body.applyForce(this.body, position, force); return this }, thrust: function(speed) { var angle = this.body.angle; this._tempVec2.set(speed * Math.cos(angle), speed * Math.sin(angle)); Body.applyForce(this.body, { x: this.body.position.x, y: this.body.position.y }, this._tempVec2); return this }, thrustLeft: function(speed) { var angle = this.body.angle - Math.PI / 2; this._tempVec2.set(speed * Math.cos(angle), speed * Math.sin(angle)); Body.applyForce(this.body, { x: this.body.position.x, y: this.body.position.y }, this._tempVec2); return this }, thrustRight: function(speed) { var angle = this.body.angle + Math.PI / 2; this._tempVec2.set(speed * Math.cos(angle), speed * Math.sin(angle)); Body.applyForce(this.body, { x: this.body.position.x, y: this.body.position.y }, this._tempVec2); return this }, thrustBack: function(speed) { var angle = this.body.angle - Math.PI; this._tempVec2.set(speed * Math.cos(angle), speed * Math.sin(angle)); Body.applyForce(this.body, { x: this.body.position.x, y: this.body.position.y }, this._tempVec2); return this } }; module.exports = Force }, function(module, exports) { var Friction = { setFriction: function(value, air, fstatic) { this.body.friction = value; if (air !== undefined) { this.body.frictionAir = air } if (fstatic !== undefined) { this.body.frictionStatic = fstatic } return this }, setFrictionAir: function(value) { this.body.frictionAir = value; return this }, setFrictionStatic: function(value) { this.body.frictionStatic = value; return this } }; module.exports = Friction }, function(module, exports) { var Gravity = { setIgnoreGravity: function(value) { this.body.ignoreGravity = value; return this } }; module.exports = Gravity }, function(module, exports, __webpack_require__) { var Body = __webpack_require__(25); var Vector2 = __webpack_require__(3); var Mass = { setMass: function(value) { Body.setMass(this.body, value); return this }, setDensity: function(value) { Body.setDensity(this.body, value); return this }, centerOfMass: { get: function() { return new Vector2(this.body.render.sprite.xOffset * this.width, this.body.render.sprite.yOffset * this.height) } } }; module.exports = Mass }, function(module, exports, __webpack_require__) { var Body = __webpack_require__(25); var Static = { setStatic: function(value) { Body.setStatic(this.body, value); return this }, isStatic: function() { return this.body.isStatic } }; module.exports = Static }, function(module, exports) { var Sensor = { setSensor: function(value) { this.body.isSensor = value; return this }, isSensor: function() { return this.body.isSensor } }; module.exports = Sensor }, function(module, exports, __webpack_require__) { var Bodies = __webpack_require__(58); var Body = __webpack_require__(25); var GetFastValue = __webpack_require__(1); var PhysicsEditorParser = __webpack_require__(1065); var Vertices = __webpack_require__(32); var SetBody = { setRectangle: function(width, height, options) { return this.setBody({ type: "rectangle", width: width, height: height }, options) }, setCircle: function(radius, options) { return this.setBody({ type: "circle", radius: radius }, options) }, setPolygon: function(radius, sides, options) { return this.setBody({ type: "polygon", sides: sides, radius: radius }, options) }, setTrapezoid: function(width, height, slope, options) { return this.setBody({ type: "trapezoid", width: width, height: height, slope: slope }, options) }, setExistingBody: function(body, addToWorld) { if (addToWorld === undefined) { addToWorld = true } if (this.body) { this.world.remove(this.body) } this.body = body; for (var i = 0; i < body.parts.length; i++) { body.parts[i].gameObject = this } var _this = this; body.destroy = function destroy() { _this.world.remove(_this.body); _this.body.gameObject = null }; if (addToWorld) { this.world.add(body) } if (this._originComponent) { this.setOrigin(body.render.sprite.xOffset, body.render.sprite.yOffset) } return this }, setBody: function(config, options) { if (!config) { return this } var body; if (typeof config === "string") { config = { type: config } } var shapeType = GetFastValue(config, "type", "rectangle"); var bodyX = GetFastValue(config, "x", this._tempVec2.x); var bodyY = GetFastValue(config, "y", this._tempVec2.y); var bodyWidth = GetFastValue(config, "width", this.width); var bodyHeight = GetFastValue(config, "height", this.height); switch (shapeType) { case "rectangle": body = Bodies.rectangle(bodyX, bodyY, bodyWidth, bodyHeight, options); break; case "circle": var radius = GetFastValue(config, "radius", Math.max(bodyWidth, bodyHeight) / 2); var maxSides = GetFastValue(config, "maxSides", 25); body = Bodies.circle(bodyX, bodyY, radius, options, maxSides); break; case "trapezoid": var slope = GetFastValue(config, "slope", .5); body = Bodies.trapezoid(bodyX, bodyY, bodyWidth, bodyHeight, slope, options); break; case "polygon": var sides = GetFastValue(config, "sides", 5); var pRadius = GetFastValue(config, "radius", Math.max(bodyWidth, bodyHeight) / 2); body = Bodies.polygon(bodyX, bodyY, sides, pRadius, options); break; case "fromVertices": case "fromVerts": var verts = GetFastValue(config, "verts", null); if (verts) { if (typeof verts === "string") { verts = Vertices.fromPath(verts) } if (this.body && !this.body.hasOwnProperty("temp")) { Body.setVertices(this.body, verts); body = this.body } else { var flagInternal = GetFastValue(config, "flagInternal", false); var removeCollinear = GetFastValue(config, "removeCollinear", .01); var minimumArea = GetFastValue(config, "minimumArea", 10); body = Bodies.fromVertices(bodyX, bodyY, verts, options, flagInternal, removeCollinear, minimumArea) } } break; case "fromPhysicsEditor": body = PhysicsEditorParser.parseBody(bodyX, bodyY, bodyWidth, bodyHeight, config); break } if (body) { this.setExistingBody(body, config.addToWorld) } return this } }; module.exports = SetBody }, function(module, exports, __webpack_require__) { var Bodies = __webpack_require__(58); var Body = __webpack_require__(25); var Bounds = __webpack_require__(34); var Common = __webpack_require__(17); var GetFastValue = __webpack_require__(1); var Vector = __webpack_require__(33); var Vertices = __webpack_require__(32); var PhysicsEditorParser = { parseBody: function(x, y, w, h, config) { var fixtureConfigs = GetFastValue(config, "fixtures", []); var fixtures = []; for (var fc = 0; fc < fixtureConfigs.length; fc++) { var fixtureParts = this.parseFixture(fixtureConfigs[fc]); for (var i = 0; i < fixtureParts.length; i++) { fixtures.push(fixtureParts[i]) } } var matterConfig = Common.extend({}, false, config); delete matterConfig.fixtures; delete matterConfig.type; var body = Body.create(matterConfig); Body.setParts(body, fixtures); body.render.sprite.xOffset = body.position.x / w; body.render.sprite.yOffset = body.position.y / h; Body.setPosition(body, { x: x, y: y }); return body }, parseFixture: function(fixtureConfig) { var matterConfig = Common.extend({}, false, fixtureConfig); delete matterConfig.circle; delete matterConfig.vertices; var fixtures; if (fixtureConfig.circle) { var x = GetFastValue(fixtureConfig.circle, "x"); var y = GetFastValue(fixtureConfig.circle, "y"); var r = GetFastValue(fixtureConfig.circle, "radius"); fixtures = [Bodies.circle(x, y, r, matterConfig)] } else if (fixtureConfig.vertices) { fixtures = this.parseVertices(fixtureConfig.vertices, matterConfig) } return fixtures }, parseVertices: function(vertexSets, options) { var i, j, k, v, z; var parts = []; options = options || {}; for (v = 0; v < vertexSets.length; v += 1) { parts.push(Body.create(Common.extend({ position: Vertices.centre(vertexSets[v]), vertices: vertexSets[v] }, options))) } var coincidentMaxDist = 5; for (i = 0; i < parts.length; i++) { var partA = parts[i]; for (j = i + 1; j < parts.length; j++) { var partB = parts[j]; if (Bounds.overlaps(partA.bounds, partB.bounds)) { var pav = partA.vertices, pbv = partB.vertices; for (k = 0; k < partA.vertices.length; k++) { for (z = 0; z < partB.vertices.length; z++) { var da = Vector.magnitudeSquared(Vector.sub(pav[(k + 1) % pav.length], pbv[z])), db = Vector.magnitudeSquared(Vector.sub(pav[k], pbv[(z + 1) % pbv.length])); if (da < coincidentMaxDist && db < coincidentMaxDist) { pav[k].isInternal = true; pbv[z].isInternal = true } } } } } } return parts } }; module.exports = PhysicsEditorParser }, function(module, exports, __webpack_require__) { var MatterEvents = __webpack_require__(87); var Sleep = { setSleepThreshold: function(value) { if (value === undefined) { value = 60 } this.body.sleepThreshold = value; return this }, setSleepEvents: function(start, end) { this.setSleepStartEvent(start); this.setSleepEndEvent(end); return this }, setSleepStartEvent: function(value) { if (value) { var world = this.world; MatterEvents.on(this.body, "sleepStart", function(event) { world.emit("sleepstart", event, this) }) } else { MatterEvents.off(this.body, "sleepStart") } return this }, setSleepEndEvent: function(value) { if (value) { var world = this.world; MatterEvents.on(this.body, "sleepEnd", function(event) { world.emit("sleepend", event, this) }) } else { MatterEvents.off(this.body, "sleepEnd") } return this } }; module.exports = Sleep }, function(module, exports, __webpack_require__) { var Body = __webpack_require__(25); var MATH_CONST = __webpack_require__(18); var WrapAngle = __webpack_require__(150); var WrapAngleDegrees = __webpack_require__(151); var _FLAG = 4; var Transform = { x: { get: function() { return this.body.position.x }, set: function(value) { this._tempVec2.set(value, this.y); Body.setPosition(this.body, this._tempVec2) } }, y: { get: function() { return this.body.position.y }, set: function(value) { this._tempVec2.set(this.x, value); Body.setPosition(this.body, this._tempVec2) } }, scaleX: { get: function() { return this._scaleX }, set: function(value) { var factor = 1 / this._scaleX; this._scaleX = value; if (this._scaleX === 0) { this.renderFlags &= ~_FLAG } else { this.renderFlags |= _FLAG } Body.scale(this.body, factor, this._scaleY); Body.scale(this.body, value, this._scaleY) } }, scaleY: { get: function() { return this._scaleY }, set: function(value) { var factor = 1 / this._scaleY; this._scaleY = value; if (this._scaleY === 0) { this.renderFlags &= ~_FLAG } else { this.renderFlags |= _FLAG } Body.scale(this.body, this._scaleX, factor); Body.scale(this.body, this._scaleX, value) } }, angle: { get: function() { return WrapAngleDegrees(this.body.angle * MATH_CONST.RAD_TO_DEG) }, set: function(value) { this.rotation = WrapAngleDegrees(value) * MATH_CONST.DEG_TO_RAD } }, rotation: { get: function() { return this.body.angle }, set: function(value) { this._rotation = WrapAngle(value); Body.setAngle(this.body, this._rotation) } }, setPosition: function(x, y) { if (x === undefined) { x = 0 } if (y === undefined) { y = x } this._tempVec2.set(x, y); Body.setPosition(this.body, this._tempVec2); return this }, setRotation: function(radians) { if (radians === undefined) { radians = 0 } this._rotation = WrapAngle(radians); Body.setAngle(this.body, radians); return this }, setFixedRotation: function() { Body.setInertia(this.body, Infinity); return this }, setAngle: function(degrees) { if (degrees === undefined) { degrees = 0 } this.angle = degrees; Body.setAngle(this.body, this.rotation); return this }, setScale: function(x, y, point) { if (x === undefined) { x = 1 } if (y === undefined) { y = x } var factorX = 1 / this._scaleX; var factorY = 1 / this._scaleY; this._scaleX = x; this._scaleY = y; Body.scale(this.body, factorX, factorY, point); Body.scale(this.body, x, y, point); return this } }; module.exports = Transform }, function(module, exports, __webpack_require__) { var Body = __webpack_require__(25); var Velocity = { setAngularVelocity: function(value) { Body.setAngularVelocity(this.body, value); return this }, setVelocityX: function(x) { this._tempVec2.set(x, this.body.velocity.y); Body.setVelocity(this.body, this._tempVec2); return this }, setVelocityY: function(y) { this._tempVec2.set(this.body.velocity.x, y); Body.setVelocity(this.body, this._tempVec2); return this }, setVelocity: function(x, y) { this._tempVec2.set(x, y); Body.setVelocity(this.body, this._tempVec2); return this } }; module.exports = Velocity }, function(module, exports, __webpack_require__) { var Bounds = __webpack_require__(34); var Class = __webpack_require__(0); var Composite = __webpack_require__(70); var Constraint = __webpack_require__(88); var Detector = __webpack_require__(206); var GetFastValue = __webpack_require__(1); var Merge = __webpack_require__(80); var Sleeping = __webpack_require__(103); var Vector2 = __webpack_require__(3); var Vertices = __webpack_require__(32); var PointerConstraint = new Class({ initialize: function PointerConstraint(scene, world, options) { if (options === undefined) { options = {} } var defaults = { label: "Pointer Constraint", pointA: { x: 0, y: 0 }, pointB: { x: 0, y: 0 }, damping: 0, length: .01, stiffness: .1, angularStiffness: 1, collisionFilter: { category: 1, mask: 4294967295, group: 0 } }; this.scene = scene; this.world = world; var camera = GetFastValue(options, "camera", null); if (!camera) { this.camera = scene.sys.cameras.main } else { this.camera = camera; delete options.camera } this.pointer = null; this.active = true; this.position = new Vector2; this.constraint = Constraint.create(Merge(options, defaults)); this.world.on("beforeupdate", this.update, this); scene.sys.input.on("pointerdown", this.onDown, this); scene.sys.input.on("pointerup", this.onUp, this) }, onDown: function(pointer) { this.pointer = pointer }, onUp: function() { this.pointer = null }, getBodyPart: function(body, position) { var constraint = this.constraint; var start = body.parts.length > 1 ? 1 : 0; for (var i = start; i < body.parts.length; i++) { var part = body.parts[i]; if (Vertices.contains(part.vertices, position)) { constraint.bodyB = body; constraint.pointA.x = position.x; constraint.pointA.y = position.y; constraint.pointB.x = position.x - body.position.x; constraint.pointB.y = position.y - body.position.y; constraint.angleB = body.angle; Sleeping.set(body, false); return true } } return false }, update: function() { if (!this.active) { return } var pointer = this.pointer; var constraint = this.constraint; if (!pointer) { if (constraint.bodyB) { constraint.bodyB = null } } else { var pos = this.position; this.camera.getWorldPoint(pointer.x, pointer.y, pos); if (constraint.bodyB) { Sleeping.set(constraint.bodyB, false); constraint.pointA.x = pos.x; constraint.pointA.y = pos.y } else { var bodies = Composite.allBodies(this.world.localWorld); for (var i = 0; i < bodies.length; i++) { var body = bodies[i]; if (!body.ignorePointer && Bounds.contains(body.bounds, pos) && Detector.canCollide(body.collisionFilter, constraint.collisionFilter)) { if (this.getBodyPart(body, pos)) { break } } } } } }, destroy: function() { this.world.removeConstraint(this.constraint); this.constraint = null; this.world.off("beforeupdate", this.update); this.scene.sys.input.off("pointerdown", this.onDown, this); this.scene.sys.input.off("pointerup", this.onUp, this) } }); module.exports = PointerConstraint }, function(module, exports, __webpack_require__) { var Query = {}; module.exports = Query; var Vector = __webpack_require__(33); var SAT = __webpack_require__(207); var Bounds = __webpack_require__(34); var Bodies = __webpack_require__(58); var Vertices = __webpack_require__(32); (function() { Query.collides = function(body, bodies) { var collisions = []; for (var i = 0; i < bodies.length; i++) { var bodyA = bodies[i]; if (Bounds.overlaps(bodyA.bounds, body.bounds)) { for (var j = bodyA.parts.length === 1 ? 0 : 1; j < bodyA.parts.length; j++) { var part = bodyA.parts[j]; if (Bounds.overlaps(part.bounds, body.bounds)) { var collision = SAT.collides(part, body); if (collision.collided) { collisions.push(collision); break } } } } } return collisions }; Query.ray = function(bodies, startPoint, endPoint, rayWidth) { rayWidth = rayWidth || 1e-100; var rayAngle = Vector.angle(startPoint, endPoint), rayLength = Vector.magnitude(Vector.sub(startPoint, endPoint)), rayX = (endPoint.x + startPoint.x) * .5, rayY = (endPoint.y + startPoint.y) * .5, ray = Bodies.rectangle(rayX, rayY, rayLength, rayWidth, { angle: rayAngle }), collisions = Query.collides(ray, bodies); for (var i = 0; i < collisions.length; i += 1) { var collision = collisions[i]; collision.body = collision.bodyB = collision.bodyA } return collisions }; Query.region = function(bodies, bounds, outside) { var result = []; for (var i = 0; i < bodies.length; i++) { var body = bodies[i], overlaps = Bounds.overlaps(body.bounds, bounds); if (overlaps && !outside || !overlaps && outside) result.push(body) } return result }; Query.point = function(bodies, point) { var result = []; for (var i = 0; i < bodies.length; i++) { var body = bodies[i]; if (Bounds.contains(body.bounds, point)) { for (var j = body.parts.length === 1 ? 0 : 1; j < body.parts.length; j++) { var part = body.parts[j]; if (Bounds.contains(part.bounds, point) && Vertices.contains(part.vertices, point)) { result.push(body); break } } } } return result } })() }, function(module, exports, __webpack_require__) { var Metrics = {}; module.exports = Metrics; var Composite = __webpack_require__(70); var Common = __webpack_require__(17); (function() { Metrics.create = function(options) { var defaults = { extended: false, narrowDetections: 0, narrowphaseTests: 0, narrowReuse: 0, narrowReuseCount: 0, midphaseTests: 0, broadphaseTests: 0, narrowEff: 1e-4, midEff: 1e-4, broadEff: 1e-4, collisions: 0, buckets: 0, bodies: 0, pairs: 0 }; return Common.extend(defaults, false, options) }; Metrics.reset = function(metrics) { if (metrics.extended) { metrics.narrowDetections = 0; metrics.narrowphaseTests = 0; metrics.narrowReuse = 0; metrics.narrowReuseCount = 0; metrics.midphaseTests = 0; metrics.broadphaseTests = 0; metrics.narrowEff = 0; metrics.midEff = 0; metrics.broadEff = 0; metrics.collisions = 0; metrics.buckets = 0; metrics.pairs = 0; metrics.bodies = 0 } }; Metrics.update = function(metrics, engine) { if (metrics.extended) { var world = engine.world, bodies = Composite.allBodies(world); metrics.collisions = metrics.narrowDetections; metrics.pairs = engine.pairs.list.length; metrics.bodies = bodies.length; metrics.midEff = (metrics.narrowDetections / (metrics.midphaseTests || 1)).toFixed(2); metrics.narrowEff = (metrics.narrowDetections / (metrics.narrowphaseTests || 1)).toFixed(2); metrics.broadEff = (1 - metrics.broadphaseTests / (bodies.length || 1)).toFixed(2); metrics.narrowReuse = (metrics.narrowReuseCount / (metrics.narrowphaseTests || 1)).toFixed(2) } } })() }, function(module, exports, __webpack_require__) { var Svg = {}; module.exports = Svg; var Bounds = __webpack_require__(34); var Common = __webpack_require__(17); (function() { Svg.pathToVertices = function(path, sampleLength) { if (typeof window !== "undefined" && !("SVGPathSeg" in window)) { Common.warn("Svg.pathToVertices: SVGPathSeg not defined, a polyfill is required.") } var i, il, total, point, segment, segments, segmentsQueue, lastSegment, lastPoint, segmentIndex, points = [], lx, ly, length = 0, x = 0, y = 0; sampleLength = sampleLength || 15; var addPoint = function(px, py, pathSegType) { var isRelative = pathSegType % 2 === 1 && pathSegType > 1; if (!lastPoint || px != lastPoint.x || py != lastPoint.y) { if (lastPoint && isRelative) { lx = lastPoint.x; ly = lastPoint.y } else { lx = 0; ly = 0 } var point = { x: lx + px, y: ly + py }; if (isRelative || !lastPoint) { lastPoint = point } points.push(point); x = lx + px; y = ly + py } }; var addSegmentPoint = function(segment) { var segType = segment.pathSegTypeAsLetter.toUpperCase(); if (segType === "Z") return; switch (segType) { case "M": case "L": case "T": case "C": case "S": case "Q": x = segment.x; y = segment.y; break; case "H": x = segment.x; break; case "V": y = segment.y; break } addPoint(x, y, segment.pathSegType) }; Svg._svgPathToAbsolute(path); total = path.getTotalLength(); segments = []; for (i = 0; i < path.pathSegList.numberOfItems; i += 1) segments.push(path.pathSegList.getItem(i)); segmentsQueue = segments.concat(); while (length < total) { segmentIndex = path.getPathSegAtLength(length); segment = segments[segmentIndex]; if (segment != lastSegment) { while (segmentsQueue.length && segmentsQueue[0] != segment) addSegmentPoint(segmentsQueue.shift()); lastSegment = segment } switch (segment.pathSegTypeAsLetter.toUpperCase()) { case "C": case "T": case "S": case "Q": case "A": point = path.getPointAtLength(length); addPoint(point.x, point.y, 0); break } length += sampleLength } for (i = 0, il = segmentsQueue.length; i < il; ++i) addSegmentPoint(segmentsQueue[i]); return points }; Svg._svgPathToAbsolute = function(path) { var x0, y0, x1, y1, x2, y2, segs = path.pathSegList, x = 0, y = 0, len = segs.numberOfItems; for (var i = 0; i < len; ++i) { var seg = segs.getItem(i), segType = seg.pathSegTypeAsLetter; if (/[MLHVCSQTA]/.test(segType)) { if ("x" in seg) x = seg.x; if ("y" in seg) y = seg.y } else { if ("x1" in seg) x1 = x + seg.x1; if ("x2" in seg) x2 = x + seg.x2; if ("y1" in seg) y1 = y + seg.y1; if ("y2" in seg) y2 = y + seg.y2; if ("x" in seg) x += seg.x; if ("y" in seg) y += seg.y; switch (segType) { case "m": segs.replaceItem(path.createSVGPathSegMovetoAbs(x, y), i); break; case "l": segs.replaceItem(path.createSVGPathSegLinetoAbs(x, y), i); break; case "h": segs.replaceItem(path.createSVGPathSegLinetoHorizontalAbs(x), i); break; case "v": segs.replaceItem(path.createSVGPathSegLinetoVerticalAbs(y), i); break; case "c": segs.replaceItem(path.createSVGPathSegCurvetoCubicAbs(x, y, x1, y1, x2, y2), i); break; case "s": segs.replaceItem(path.createSVGPathSegCurvetoCubicSmoothAbs(x, y, x2, y2), i); break; case "q": segs.replaceItem(path.createSVGPathSegCurvetoQuadraticAbs(x, y, x1, y1), i); break; case "t": segs.replaceItem(path.createSVGPathSegCurvetoQuadraticSmoothAbs(x, y), i); break; case "a": segs.replaceItem(path.createSVGPathSegArcAbs(x, y, seg.r1, seg.r2, seg.angle, seg.largeArcFlag, seg.sweepFlag), i); break; case "z": case "Z": x = x0; y = y0; break } } if (segType == "M" || segType == "m") { x0 = x; y0 = y } } } })() }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var Factory = __webpack_require__(436); var GetFastValue = __webpack_require__(1); var GetValue = __webpack_require__(4); var MatterAttractors = __webpack_require__(1074); var MatterLib = __webpack_require__(441); var MatterWrap = __webpack_require__(1075); var Merge = __webpack_require__(80); var Plugin = __webpack_require__(209); var PluginCache = __webpack_require__(15); var World = __webpack_require__(446); var Vertices = __webpack_require__(32); var MatterPhysics = new Class({ initialize: function MatterPhysics(scene) { this.scene = scene; this.systems = scene.sys; this.config = this.getConfig(); this.world; this.add; this.verts = Vertices; if (GetValue(this.config, "plugins.attractors", false)) { Plugin.register(MatterAttractors); Plugin.use(MatterLib, MatterAttractors) } if (GetValue(this.config, "plugins.wrap", false)) { Plugin.register(MatterWrap); Plugin.use(MatterLib, MatterWrap) } scene.sys.events.once("boot", this.boot, this); scene.sys.events.on("start", this.start, this) }, boot: function() { this.world = new World(this.scene, this.config); this.add = new Factory(this.world); this.systems.events.once("destroy", this.destroy, this) }, start: function() { if (!this.world) { this.world = new World(this.scene, this.config); this.add = new Factory(this.world) } var eventEmitter = this.systems.events; eventEmitter.on("update", this.world.update, this.world); eventEmitter.on("postupdate", this.world.postUpdate, this.world); eventEmitter.once("shutdown", this.shutdown, this) }, getConfig: function() { var gameConfig = this.systems.game.config.physics; var sceneConfig = this.systems.settings.physics; var config = Merge(GetFastValue(sceneConfig, "matter", {}), GetFastValue(gameConfig, "matter", {})); return config }, enableAttractorPlugin: function() { Plugin.register(MatterAttractors); Plugin.use(MatterLib, MatterAttractors); return this }, enableWrapPlugin: function() { Plugin.register(MatterWrap); Plugin.use(MatterLib, MatterWrap); return this }, pause: function() { return this.world.pause() }, resume: function() { return this.world.resume() }, set60Hz: function() { this.world.getDelta = this.world.update60Hz; this.world.autoUpdate = true; return this }, set30Hz: function() { this.world.getDelta = this.world.update30Hz; this.world.autoUpdate = true; return this }, step: function(delta, correction) { this.world.step(delta, correction) }, shutdown: function() { var eventEmitter = this.systems.events; eventEmitter.off("update", this.world.update, this.world); eventEmitter.off("postupdate", this.world.postUpdate, this.world); eventEmitter.off("shutdown", this.shutdown, this); this.add.destroy(); this.world.destroy(); this.add = null; this.world = null }, destroy: function() { this.shutdown(); this.scene.sys.events.off("start", this.start, this); this.scene = null; this.systems = null } }); PluginCache.register("MatterPhysics", MatterPhysics, "matterPhysics"); module.exports = MatterPhysics }, function(module, exports, __webpack_require__) { var Matter = __webpack_require__(208); var MatterAttractors = { name: "matter-attractors", version: "0.1.7", for: "matter-js@^0.13.1", silent: true, install: function(base) { base.after("Body.create", function() { MatterAttractors.Body.init(this) }); base.before("Engine.update", function(engine) { MatterAttractors.Engine.update(engine) }) }, Body: { init: function(body) { body.plugin.attractors = body.plugin.attractors || [] } }, Engine: { update: function(engine) { var world = engine.world, bodies = Matter.Composite.allBodies(world); for (var i = 0; i < bodies.length; i += 1) { var bodyA = bodies[i], attractors = bodyA.plugin.attractors; if (attractors && attractors.length > 0) { for (var j = i + 1; j < bodies.length; j += 1) { var bodyB = bodies[j]; for (var k = 0; k < attractors.length; k += 1) { var attractor = attractors[k], forceVector = attractor; if (Matter.Common.isFunction(attractor)) { forceVector = attractor(bodyA, bodyB) } if (forceVector) { Matter.Body.applyForce(bodyB, bodyB.position, forceVector) } } } } } } }, Attractors: { gravityConstant: .001, gravity: function(bodyA, bodyB) { var bToA = Matter.Vector.sub(bodyB.position, bodyA.position), distanceSq = Matter.Vector.magnitudeSquared(bToA) || 1e-4, normal = Matter.Vector.normalise(bToA), magnitude = -MatterAttractors.Attractors.gravityConstant * (bodyA.mass * bodyB.mass / distanceSq), force = Matter.Vector.mult(normal, magnitude); Matter.Body.applyForce(bodyA, bodyA.position, Matter.Vector.neg(force)); Matter.Body.applyForce(bodyB, bodyB.position, force) } } }; module.exports = MatterAttractors }, function(module, exports, __webpack_require__) { var Matter = __webpack_require__(208); var MatterWrap = { name: "matter-wrap", version: "0.1.4", for: "matter-js@^0.13.1", silent: true, install: function(base) { base.after("Engine.update", function() { MatterWrap.Engine.update(this) }) }, Engine: { update: function(engine) { var world = engine.world, bodies = Matter.Composite.allBodies(world), composites = Matter.Composite.allComposites(world); for (var i = 0; i < bodies.length; i += 1) { var body = bodies[i]; if (body.plugin.wrap) { MatterWrap.Body.wrap(body, body.plugin.wrap) } } for (i = 0; i < composites.length; i += 1) { var composite = composites[i]; if (composite.plugin.wrap) { MatterWrap.Composite.wrap(composite, composite.plugin.wrap) } } } }, Bounds: { wrap: function(objectBounds, bounds) { var x = null, y = null; if (typeof bounds.min.x !== "undefined" && typeof bounds.max.x !== "undefined") { if (objectBounds.min.x > bounds.max.x) { x = bounds.min.x - objectBounds.max.x } else if (objectBounds.max.x < bounds.min.x) { x = bounds.max.x - objectBounds.min.x } } if (typeof bounds.min.y !== "undefined" && typeof bounds.max.y !== "undefined") { if (objectBounds.min.y > bounds.max.y) { y = bounds.min.y - objectBounds.max.y } else if (objectBounds.max.y < bounds.min.y) { y = bounds.max.y - objectBounds.min.y } } if (x !== null || y !== null) { return { x: x || 0, y: y || 0 } } } }, Body: { wrap: function(body, bounds) { var translation = MatterWrap.Bounds.wrap(body.bounds, bounds); if (translation) { Matter.Body.translate(body, translation) } return translation } }, Composite: { bounds: function(composite) { var bodies = Matter.Composite.allBodies(composite), vertices = []; for (var i = 0; i < bodies.length; i += 1) { var body = bodies[i]; vertices.push(body.bounds.min, body.bounds.max) } return Matter.Bounds.create(vertices) }, wrap: function(composite, bounds) { var translation = MatterWrap.Bounds.wrap(MatterWrap.Composite.bounds(composite), bounds); if (translation) { Matter.Composite.translate(composite, translation) } return translation } } }; module.exports = MatterWrap }, function(module, exports, __webpack_require__) { module.exports = { BasePlugin: __webpack_require__(447), DefaultPlugins: __webpack_require__(170), PluginCache: __webpack_require__(15), PluginManager: __webpack_require__(318), ScenePlugin: __webpack_require__(1077) } }, function(module, exports, __webpack_require__) { var BasePlugin = __webpack_require__(447); var Class = __webpack_require__(0); var ScenePlugin = new Class({ Extends: BasePlugin, initialize: function ScenePlugin(scene, pluginManager) { BasePlugin.call(this, pluginManager); this.scene = scene; this.systems = scene.sys; scene.sys.events.once("boot", this.boot, this) }, boot: function() {} }); module.exports = ScenePlugin }, function(module, exports, __webpack_require__) { module.exports = { Canvas: __webpack_require__(1079), Snapshot: __webpack_require__(1080), WebGL: __webpack_require__(1081) } }, function(module, exports, __webpack_require__) { module.exports = { CanvasRenderer: __webpack_require__(304), GetBlendModes: __webpack_require__(306), SetTransform: __webpack_require__(24) } }, function(module, exports, __webpack_require__) { module.exports = { Canvas: __webpack_require__(305), WebGL: __webpack_require__(308) } }, function(module, exports, __webpack_require__) { module.exports = { Utils: __webpack_require__(10), WebGLPipeline: __webpack_require__(171), WebGLRenderer: __webpack_require__(307), Pipelines: __webpack_require__(1082), BYTE: 0, SHORT: 1, UNSIGNED_BYTE: 2, UNSIGNED_SHORT: 3, FLOAT: 4 } }, function(module, exports, __webpack_require__) { module.exports = { BitmapMaskPipeline: __webpack_require__(309), ForwardDiffuseLightPipeline: __webpack_require__(310), TextureTintPipeline: __webpack_require__(172) } }, function(module, exports, __webpack_require__) { var CONST = __webpack_require__(117); var Extend = __webpack_require__(19); var Scene = { SceneManager: __webpack_require__(320), ScenePlugin: __webpack_require__(1084), Settings: __webpack_require__(323), Systems: __webpack_require__(173) }; Scene = Extend(false, Scene, CONST); module.exports = Scene }, function(module, exports, __webpack_require__) { var Clamp = __webpack_require__(23); var Class = __webpack_require__(0); var GetFastValue = __webpack_require__(1); var PluginCache = __webpack_require__(15); var ScenePlugin = new Class({ initialize: function ScenePlugin(scene) { this.scene = scene; this.systems = scene.sys; this.settings = scene.sys.settings; this.key = scene.sys.settings.key; this.manager = scene.sys.game.scene; this.transitionProgress = 0; this._elapsed = 0; this._target = null; this._duration = 0; this._onUpdate; this._onUpdateScope; this._willSleep = false; this._willRemove = false; scene.sys.events.once("boot", this.boot, this); scene.sys.events.on("start", this.pluginStart, this) }, boot: function() { this.systems.events.once("destroy", this.destroy, this) }, pluginStart: function() { this._target = null; this.systems.events.once("shutdown", this.shutdown, this) }, start: function(key, data) { if (key === undefined) { key = this.key } this.manager.queueOp("stop", this.key); this.manager.queueOp("start", key, data); return this }, restart: function(data) { var key = this.key; this.manager.queueOp("stop", key); this.manager.queueOp("start", key, data); return this }, transition: function(config) { if (config === undefined) { config = {} } var key = GetFastValue(config, "target", false); var target = this.manager.getScene(key); if (!key || !this.checkValidTransition(target)) { return false } var duration = GetFastValue(config, "duration", 1e3); this._elapsed = 0; this._target = target; this._duration = duration; this._willSleep = GetFastValue(config, "sleep", false); this._willRemove = GetFastValue(config, "remove", false); var callback = GetFastValue(config, "onUpdate", null); if (callback) { this._onUpdate = callback; this._onUpdateScope = GetFastValue(config, "onUpdateScope", this.scene) } var allowInput = GetFastValue(config, "allowInput", false); this.settings.transitionAllowInput = allowInput; var targetSettings = target.sys.settings; targetSettings.isTransition = true; targetSettings.transitionFrom = this.scene; targetSettings.transitionDuration = duration; targetSettings.transitionAllowInput = allowInput; if (GetFastValue(config, "moveAbove", false)) { this.manager.moveAbove(this.key, key) } else if (GetFastValue(config, "moveBelow", false)) { this.manager.moveBelow(this.key, key) } if (target.sys.isSleeping()) { target.sys.wake() } else { this.manager.start(key, GetFastValue(config, "data")) } this.systems.events.emit("transitionout", target, duration); this.systems.events.on("update", this.step, this); return true }, checkValidTransition: function(target) { if (!target || target.sys.isActive() || target.sys.isTransitioning() || target === this.scene || this.systems.isTransitioning()) { return false } return true }, step: function(time, delta) { this._elapsed += delta; this.transitionProgress = Clamp(this._elapsed / this._duration, 0, 1); if (this._onUpdate) { this._onUpdate.call(this._onUpdateScope, this.transitionProgress) } if (this._elapsed >= this._duration) { this.transitionComplete() } }, transitionComplete: function() { var targetSys = this._target.sys; var targetSettings = this._target.sys.settings; this.systems.events.off("update", this.step, this); targetSys.events.emit("transitioncomplete", this.scene); targetSettings.isTransition = false; targetSettings.transitionFrom = null; this._duration = 0; this._target = null; this._onUpdate = null; this._onUpdateScope = null; if (this._willRemove) { this.manager.remove(this.key) } else if (this._willSleep) { this.systems.sleep() } else { this.manager.stop(this.key) } }, add: function(key, sceneConfig, autoStart) { this.manager.add(key, sceneConfig, autoStart); return this }, launch: function(key, data) { if (key && key !== this.key) { this.manager.queueOp("start", key, data) } return this }, run: function(key, data) { if (key && key !== this.key) { this.manager.queueOp("run", key, data) } return this }, pause: function(key, data) { if (key === undefined) { key = this.key } this.manager.queueOp("pause", key, data); return this }, resume: function(key, data) { if (key === undefined) { key = this.key } this.manager.queueOp("resume", key, data); return this }, sleep: function(key, data) { if (key === undefined) { key = this.key } this.manager.queueOp("sleep", key, data); return this }, wake: function(key, data) { if (key === undefined) { key = this.key } this.manager.queueOp("wake", key, data); return this }, switch: function(key) { if (key !== this.key) { this.manager.queueOp("switch", this.key, key) } return this }, stop: function(key) { if (key === undefined) { key = this.key } this.manager.queueOp("stop", key); return this }, setActive: function(value, key, data) { if (key === undefined) { key = this.key } var scene = this.manager.getScene(key); if (scene) { scene.sys.setActive(value, data) } return this }, setVisible: function(value, key) { if (key === undefined) { key = this.key } var scene = this.manager.getScene(key); if (scene) { scene.sys.setVisible(value) } return this }, isSleeping: function(key) { if (key === undefined) { key = this.key } return this.manager.isSleeping(key) }, isActive: function(key) { if (key === undefined) { key = this.key } return this.manager.isActive(key) }, isVisible: function(key) { if (key === undefined) { key = this.key } return this.manager.isVisible(key) }, swapPosition: function(keyA, keyB) { if (keyB === undefined) { keyB = this.key } if (keyA !== keyB) { this.manager.swapPosition(keyA, keyB) } return this }, moveAbove: function(keyA, keyB) { if (keyB === undefined) { keyB = this.key } if (keyA !== keyB) { this.manager.moveAbove(keyA, keyB) } return this }, moveBelow: function(keyA, keyB) { if (keyB === undefined) { keyB = this.key } if (keyA !== keyB) { this.manager.moveBelow(keyA, keyB) } return this }, remove: function(key) { if (key === undefined) { key = this.key } this.manager.remove(key); return this }, moveUp: function(key) { if (key === undefined) { key = this.key } this.manager.moveUp(key); return this }, moveDown: function(key) { if (key === undefined) { key = this.key } this.manager.moveDown(key); return this }, bringToTop: function(key) { if (key === undefined) { key = this.key } this.manager.bringToTop(key); return this }, sendToBack: function(key) { if (key === undefined) { key = this.key } this.manager.sendToBack(key); return this }, get: function(key) { return this.manager.getScene(key) }, getIndex: function(key) { if (key === undefined) { key = this.key } return this.manager.getIndex(key) }, shutdown: function() { var eventEmitter = this.systems.events; eventEmitter.off("shutdown", this.shutdown, this); eventEmitter.off("postupdate", this.step, this); eventEmitter.off("transitionout") }, destroy: function() { this.shutdown(); this.scene.sys.events.off("start", this.start, this); this.scene = null; this.systems = null; this.settings = null; this.manager = null } }); PluginCache.register("ScenePlugin", ScenePlugin, "scenePlugin"); module.exports = ScenePlugin }, function(module, exports, __webpack_require__) { module.exports = { SoundManagerCreator: __webpack_require__(324), BaseSound: __webpack_require__(119), BaseSoundManager: __webpack_require__(118), WebAudioSound: __webpack_require__(330), WebAudioSoundManager: __webpack_require__(329), HTML5AudioSound: __webpack_require__(326), HTML5AudioSoundManager: __webpack_require__(325), NoAudioSound: __webpack_require__(328), NoAudioSoundManager: __webpack_require__(327) } }, function(module, exports, __webpack_require__) { module.exports = { List: __webpack_require__(121), Map: __webpack_require__(157), ProcessQueue: __webpack_require__(425), RTree: __webpack_require__(426), Set: __webpack_require__(81) } }, function(module, exports, __webpack_require__) { var Extend = __webpack_require__(19); var FilterMode = __webpack_require__(1088); var Textures = { FilterMode: FilterMode, Frame: __webpack_require__(120), Parsers: __webpack_require__(333), Texture: __webpack_require__(174), TextureManager: __webpack_require__(331), TextureSource: __webpack_require__(332) }; Textures = Extend(false, Textures, FilterMode); module.exports = Textures }, function(module, exports) { var CONST = { LINEAR: 0, NEAREST: 1 }; module.exports = CONST }, function(module, exports, __webpack_require__) { module.exports = { Components: __webpack_require__(133), Parsers: __webpack_require__(1119), Formats: __webpack_require__(31), ImageCollection: __webpack_require__(455), ParseToTilemap: __webpack_require__(215), Tile: __webpack_require__(72), Tilemap: __webpack_require__(459), TilemapCreator: __webpack_require__(1136), TilemapFactory: __webpack_require__(1137), Tileset: __webpack_require__(137), LayerData: __webpack_require__(105), MapData: __webpack_require__(106), ObjectLayer: __webpack_require__(457), DynamicTilemapLayer: __webpack_require__(460), StaticTilemapLayer: __webpack_require__(461) } }, function(module, exports, __webpack_require__) { var GetTilesWithin = __webpack_require__(21); var CalculateFacesWithin = __webpack_require__(53); var Copy = function(srcTileX, srcTileY, width, height, destTileX, destTileY, recalculateFaces, layer) { if (srcTileX < 0) { srcTileX = 0 } if (srcTileY < 0) { srcTileY = 0 } if (recalculateFaces === undefined) { recalculateFaces = true } var srcTiles = GetTilesWithin(srcTileX, srcTileY, width, height, null, layer); var offsetX = destTileX - srcTileX; var offsetY = destTileY - srcTileY; for (var i = 0; i < srcTiles.length; i++) { var tileX = srcTiles[i].x + offsetX; var tileY = srcTiles[i].y + offsetY; if (tileX >= 0 && tileX < layer.width && tileY >= 0 && tileY < layer.height) { if (layer.data[tileY][tileX]) { layer.data[tileY][tileX].copy(srcTiles[i]) } } } if (recalculateFaces) { CalculateFacesWithin(destTileX - 1, destTileY - 1, width + 2, height + 2, layer) } }; module.exports = Copy }, function(module, exports, __webpack_require__) { var TileToWorldX = __webpack_require__(135); var TileToWorldY = __webpack_require__(136); var GetTilesWithin = __webpack_require__(21); var ReplaceByIndex = __webpack_require__(448); var CreateFromTiles = function(indexes, replacements, spriteConfig, scene, camera, layer) { if (spriteConfig === undefined) { spriteConfig = {} } if (!Array.isArray(indexes)) { indexes = [indexes] } var tilemapLayer = layer.tilemapLayer; if (scene === undefined) { scene = tilemapLayer.scene } if (camera === undefined) { camera = scene.cameras.main } var tiles = GetTilesWithin(0, 0, layer.width, layer.height, null, layer); var sprites = []; var i; for (i = 0; i < tiles.length; i++) { var tile = tiles[i]; if (indexes.indexOf(tile.index) !== -1) { spriteConfig.x = TileToWorldX(tile.x, camera, layer); spriteConfig.y = TileToWorldY(tile.y, camera, layer); var sprite = scene.make.sprite(spriteConfig); sprites.push(sprite) } } if (typeof replacements === "number") { for (i = 0; i < indexes.length; i++) { ReplaceByIndex(indexes[i], replacements, 0, 0, layer.width, layer.height, layer) } } else if (Array.isArray(replacements)) { for (i = 0; i < indexes.length; i++) { ReplaceByIndex(indexes[i], replacements[i], 0, 0, layer.width, layer.height, layer) } } return sprites }; module.exports = CreateFromTiles }, function(module, exports, __webpack_require__) { var SnapFloor = __webpack_require__(198); var SnapCeil = __webpack_require__(408); var CullTiles = function(layer, camera, outputArray, renderOrder) { if (outputArray === undefined) { outputArray = [] } if (renderOrder === undefined) { renderOrder = 0 } outputArray.length = 0; var tilemap = layer.tilemapLayer.tilemap; var tilemapLayer = layer.tilemapLayer; var mapData = layer.data; var mapWidth = layer.width; var mapHeight = layer.height; var tileW = Math.floor(tilemap.tileWidth * tilemapLayer.scaleX); var tileH = Math.floor(tilemap.tileHeight * tilemapLayer.scaleY); var drawLeft = 0; var drawRight = mapWidth; var drawTop = 0; var drawBottom = mapHeight; if (!tilemapLayer.skipCull && tilemapLayer.scrollFactorX === 1 && tilemapLayer.scrollFactorY === 1) { var boundsLeft = SnapFloor(camera.worldView.x - tilemapLayer.x, tileW, 0, true) - tilemapLayer.cullPaddingX; var boundsRight = SnapCeil(camera.worldView.right - tilemapLayer.x, tileW, 0, true) + tilemapLayer.cullPaddingX; var boundsTop = SnapFloor(camera.worldView.y - tilemapLayer.y, tileH, 0, true) - tilemapLayer.cullPaddingY; var boundsBottom = SnapCeil(camera.worldView.bottom - tilemapLayer.y, tileH, 0, true) + tilemapLayer.cullPaddingY; drawLeft = Math.max(0, boundsLeft); drawRight = Math.min(mapWidth, boundsRight); drawTop = Math.max(0, boundsTop); drawBottom = Math.min(mapHeight, boundsBottom) } var x; var y; var tile; if (renderOrder === 0) { for (y = drawTop; y < drawBottom; y++) { for (x = drawLeft; x < drawRight; x++) { tile = mapData[y][x]; if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) { continue } outputArray.push(tile) } } } else if (renderOrder === 1) { for (y = drawTop; y < drawBottom; y++) { for (x = drawRight; x >= drawLeft; x--) { tile = mapData[y][x]; if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) { continue } outputArray.push(tile) } } } else if (renderOrder === 2) { for (y = drawBottom; y >= drawTop; y--) { for (x = drawLeft; x < drawRight; x++) { tile = mapData[y][x]; if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) { continue } outputArray.push(tile) } } } else if (renderOrder === 3) { for (y = drawBottom; y >= drawTop; y--) { for (x = drawRight; x >= drawLeft; x--) { tile = mapData[y][x]; if (!tile || tile.index === -1 || !tile.visible || tile.alpha === 0) { continue } outputArray.push(tile) } } } tilemapLayer.tilesDrawn = outputArray.length; tilemapLayer.tilesTotal = mapWidth * mapHeight; return outputArray }; module.exports = CullTiles }, function(module, exports, __webpack_require__) { var GetTilesWithin = __webpack_require__(21); var CalculateFacesWithin = __webpack_require__(53); var SetTileCollision = __webpack_require__(71); var Fill = function(index, tileX, tileY, width, height, recalculateFaces, layer) { var doesIndexCollide = layer.collideIndexes.indexOf(index) !== -1; var tiles = GetTilesWithin(tileX, tileY, width, height, null, layer); for (var i = 0; i < tiles.length; i++) { tiles[i].index = index; SetTileCollision(tiles[i], doesIndexCollide) } if (recalculateFaces) { CalculateFacesWithin(tileX - 1, tileY - 1, width + 2, height + 2, layer) } }; module.exports = Fill }, function(module, exports, __webpack_require__) { var GetTilesWithin = __webpack_require__(21); var FilterTiles = function(callback, context, tileX, tileY, width, height, filteringOptions, layer) { var tiles = GetTilesWithin(tileX, tileY, width, height, filteringOptions, layer); return tiles.filter(callback, context) }; module.exports = FilterTiles }, function(module, exports) { var FindByIndex = function(findIndex, skip, reverse, layer) { if (skip === undefined) { skip = 0 } if (reverse === undefined) { reverse = false } var count = 0; var tx; var ty; var tile; if (reverse) { for (ty = layer.height - 1; ty >= 0; ty--) { for (tx = layer.width - 1; tx >= 0; tx--) { tile = layer.data[ty][tx]; if (tile && tile.index === findIndex) { if (count === skip) { return tile } else { count += 1 } } } } } else { for (ty = 0; ty < layer.height; ty++) { for (tx = 0; tx < layer.width; tx++) { tile = layer.data[ty][tx]; if (tile && tile.index === findIndex) { if (count === skip) { return tile } else { count += 1 } } } } } return null }; module.exports = FindByIndex }, function(module, exports, __webpack_require__) { var GetTilesWithin = __webpack_require__(21); var FindTile = function(callback, context, tileX, tileY, width, height, filteringOptions, layer) { var tiles = GetTilesWithin(tileX, tileY, width, height, filteringOptions, layer); return tiles.find(callback, context) || null }; module.exports = FindTile }, function(module, exports, __webpack_require__) { var GetTilesWithin = __webpack_require__(21); var ForEachTile = function(callback, context, tileX, tileY, width, height, filteringOptions, layer) { var tiles = GetTilesWithin(tileX, tileY, width, height, filteringOptions, layer); tiles.forEach(callback, context) }; module.exports = ForEachTile }, function(module, exports, __webpack_require__) { var GetTileAt = __webpack_require__(134); var WorldToTileX = __webpack_require__(59); var WorldToTileY = __webpack_require__(60); var GetTileAtWorldXY = function(worldX, worldY, nonNull, camera, layer) { var tileX = WorldToTileX(worldX, true, camera, layer); var tileY = WorldToTileY(worldY, true, camera, layer); return GetTileAt(tileX, tileY, nonNull, layer) }; module.exports = GetTileAtWorldXY }, function(module, exports, __webpack_require__) { var Geom = __webpack_require__(377); var GetTilesWithin = __webpack_require__(21); var Intersects = __webpack_require__(378); var NOOP = __webpack_require__(2); var TileToWorldX = __webpack_require__(135); var TileToWorldY = __webpack_require__(136); var WorldToTileX = __webpack_require__(59); var WorldToTileY = __webpack_require__(60); var TriangleToRectangle = function(triangle, rect) { return Intersects.RectangleToTriangle(rect, triangle) }; var GetTilesWithinShape = function(shape, filteringOptions, camera, layer) { if (shape === undefined) { return [] } var intersectTest = NOOP; if (shape instanceof Geom.Circle) { intersectTest = Intersects.CircleToRectangle } else if (shape instanceof Geom.Rectangle) { intersectTest = Intersects.RectangleToRectangle } else if (shape instanceof Geom.Triangle) { intersectTest = TriangleToRectangle } else if (shape instanceof Geom.Line) { intersectTest = Intersects.LineToRectangle } var xStart = WorldToTileX(shape.left, true, camera, layer); var yStart = WorldToTileY(shape.top, true, camera, layer); var xEnd = Math.ceil(WorldToTileX(shape.right, false, camera, layer)); var yEnd = Math.ceil(WorldToTileY(shape.bottom, false, camera, layer)); var width = Math.max(xEnd - xStart, 1); var height = Math.max(yEnd - yStart, 1); var tiles = GetTilesWithin(xStart, yStart, width, height, filteringOptions, layer); var tileWidth = layer.tileWidth; var tileHeight = layer.tileHeight; if (layer.tilemapLayer) { tileWidth *= layer.tilemapLayer.scaleX; tileHeight *= layer.tilemapLayer.scaleY } var results = []; var tileRect = new Geom.Rectangle(0, 0, tileWidth, tileHeight); for (var i = 0; i < tiles.length; i++) { var tile = tiles[i]; tileRect.x = TileToWorldX(tile.x, camera, layer); tileRect.y = TileToWorldY(tile.y, camera, layer); if (intersectTest(shape, tileRect)) { results.push(tile) } } return results }; module.exports = GetTilesWithinShape }, function(module, exports, __webpack_require__) { var GetTilesWithin = __webpack_require__(21); var WorldToTileX = __webpack_require__(59); var WorldToTileY = __webpack_require__(60); var GetTilesWithinWorldXY = function(worldX, worldY, width, height, filteringOptions, camera, layer) { var xStart = WorldToTileX(worldX, true, camera, layer); var yStart = WorldToTileY(worldY, true, camera, layer); var xEnd = Math.ceil(WorldToTileX(worldX + width, false, camera, layer)); var yEnd = Math.ceil(WorldToTileY(worldY + height, false, camera, layer)); return GetTilesWithin(xStart, yStart, xEnd - xStart, yEnd - yStart, filteringOptions, layer) }; module.exports = GetTilesWithinWorldXY }, function(module, exports, __webpack_require__) { var HasTileAt = __webpack_require__(449); var WorldToTileX = __webpack_require__(59); var WorldToTileY = __webpack_require__(60); var HasTileAtWorldXY = function(worldX, worldY, camera, layer) { var tileX = WorldToTileX(worldX, true, camera, layer); var tileY = WorldToTileY(worldY, true, camera, layer); return HasTileAt(tileX, tileY, layer) }; module.exports = HasTileAtWorldXY }, function(module, exports, __webpack_require__) { var PutTileAt = __webpack_require__(212); var WorldToTileX = __webpack_require__(59); var WorldToTileY = __webpack_require__(60); var PutTileAtWorldXY = function(tile, worldX, worldY, recalculateFaces, camera, layer) { var tileX = WorldToTileX(worldX, true, camera, layer); var tileY = WorldToTileY(worldY, true, camera, layer); return PutTileAt(tile, tileX, tileY, recalculateFaces, layer) }; module.exports = PutTileAtWorldXY }, function(module, exports, __webpack_require__) { var CalculateFacesWithin = __webpack_require__(53); var PutTileAt = __webpack_require__(212); var PutTilesAt = function(tilesArray, tileX, tileY, recalculateFaces, layer) { if (!Array.isArray(tilesArray)) { return null } if (recalculateFaces === undefined) { recalculateFaces = true } if (!Array.isArray(tilesArray[0])) { tilesArray = [tilesArray] } var height = tilesArray.length; var width = tilesArray[0].length; for (var ty = 0; ty < height; ty++) { for (var tx = 0; tx < width; tx++) { var tile = tilesArray[ty][tx]; PutTileAt(tile, tileX + tx, tileY + ty, false, layer) } } if (recalculateFaces) { CalculateFacesWithin(tileX - 1, tileY - 1, width + 2, height + 2, layer) } }; module.exports = PutTilesAt }, function(module, exports, __webpack_require__) { var GetTilesWithin = __webpack_require__(21); var GetRandom = __webpack_require__(177); var Randomize = function(tileX, tileY, width, height, indexes, layer) { var i; var tiles = GetTilesWithin(tileX, tileY, width, height, null, layer); if (indexes === undefined) { indexes = []; for (i = 0; i < tiles.length; i++) { if (indexes.indexOf(tiles[i].index) === -1) { indexes.push(tiles[i].index) } } } for (i = 0; i < tiles.length; i++) { tiles[i].index = GetRandom(indexes) } }; module.exports = Randomize }, function(module, exports, __webpack_require__) { var RemoveTileAt = __webpack_require__(450); var WorldToTileX = __webpack_require__(59); var WorldToTileY = __webpack_require__(60); var RemoveTileAtWorldXY = function(worldX, worldY, replaceWithNull, recalculateFaces, camera, layer) { var tileX = WorldToTileX(worldX, true, camera, layer); var tileY = WorldToTileY(worldY, true, camera, layer); return RemoveTileAt(tileX, tileY, replaceWithNull, recalculateFaces, layer) }; module.exports = RemoveTileAtWorldXY }, function(module, exports, __webpack_require__) { var GetTilesWithin = __webpack_require__(21); var Color = __webpack_require__(296); var defaultTileColor = new Color(105, 210, 231, 150); var defaultCollidingTileColor = new Color(243, 134, 48, 200); var defaultFaceColor = new Color(40, 39, 37, 150); var RenderDebug = function(graphics, styleConfig, layer) { if (styleConfig === undefined) { styleConfig = {} } var tileColor = styleConfig.tileColor !== undefined ? styleConfig.tileColor : defaultTileColor; var collidingTileColor = styleConfig.collidingTileColor !== undefined ? styleConfig.collidingTileColor : defaultCollidingTileColor; var faceColor = styleConfig.faceColor !== undefined ? styleConfig.faceColor : defaultFaceColor; var tiles = GetTilesWithin(0, 0, layer.width, layer.height, null, layer); graphics.translate(layer.tilemapLayer.x, layer.tilemapLayer.y); graphics.scale(layer.tilemapLayer.scaleX, layer.tilemapLayer.scaleY); for (var i = 0; i < tiles.length; i++) { var tile = tiles[i]; var tw = tile.width; var th = tile.height; var x = tile.pixelX; var y = tile.pixelY; var color = tile.collides ? collidingTileColor : tileColor; if (color !== null) { graphics.fillStyle(color.color, color.alpha / 255); graphics.fillRect(x, y, tw, th) } x += 1; y += 1; tw -= 2; th -= 2; if (faceColor !== null) { graphics.lineStyle(1, faceColor.color, faceColor.alpha / 255); if (tile.faceTop) { graphics.lineBetween(x, y, x + tw, y) } if (tile.faceRight) { graphics.lineBetween(x + tw, y, x + tw, y + th) } if (tile.faceBottom) { graphics.lineBetween(x, y + th, x + tw, y + th) } if (tile.faceLeft) { graphics.lineBetween(x, y, x, y + th) } } } }; module.exports = RenderDebug }, function(module, exports, __webpack_require__) { var SetTileCollision = __webpack_require__(71); var CalculateFacesWithin = __webpack_require__(53); var SetLayerCollisionIndex = __webpack_require__(213); var SetCollision = function(indexes, collides, recalculateFaces, layer) { if (collides === undefined) { collides = true } if (recalculateFaces === undefined) { recalculateFaces = true } if (!Array.isArray(indexes)) { indexes = [indexes] } for (var i = 0; i < indexes.length; i++) { SetLayerCollisionIndex(indexes[i], collides, layer) } for (var ty = 0; ty < layer.height; ty++) { for (var tx = 0; tx < layer.width; tx++) { var tile = layer.data[ty][tx]; if (tile && indexes.indexOf(tile.index) !== -1) { SetTileCollision(tile, collides) } } } if (recalculateFaces) { CalculateFacesWithin(0, 0, layer.width, layer.height, layer) } }; module.exports = SetCollision }, function(module, exports, __webpack_require__) { var SetTileCollision = __webpack_require__(71); var CalculateFacesWithin = __webpack_require__(53); var SetLayerCollisionIndex = __webpack_require__(213); var SetCollisionBetween = function(start, stop, collides, recalculateFaces, layer) { if (collides === undefined) { collides = true } if (recalculateFaces === undefined) { recalculateFaces = true } if (start > stop) { return } for (var index = start; index <= stop; index++) { SetLayerCollisionIndex(index, collides, layer) } for (var ty = 0; ty < layer.height; ty++) { for (var tx = 0; tx < layer.width; tx++) { var tile = layer.data[ty][tx]; if (tile) { if (tile.index >= start && tile.index <= stop) { SetTileCollision(tile, collides) } } } } if (recalculateFaces) { CalculateFacesWithin(0, 0, layer.width, layer.height, layer) } }; module.exports = SetCollisionBetween }, function(module, exports, __webpack_require__) { var SetTileCollision = __webpack_require__(71); var CalculateFacesWithin = __webpack_require__(53); var SetLayerCollisionIndex = __webpack_require__(213); var SetCollisionByExclusion = function(indexes, collides, recalculateFaces, layer) { if (collides === undefined) { collides = true } if (recalculateFaces === undefined) { recalculateFaces = true } if (!Array.isArray(indexes)) { indexes = [indexes] } for (var ty = 0; ty < layer.height; ty++) { for (var tx = 0; tx < layer.width; tx++) { var tile = layer.data[ty][tx]; if (tile && indexes.indexOf(tile.index) === -1) { SetTileCollision(tile, collides); SetLayerCollisionIndex(tile.index, collides, layer) } } } if (recalculateFaces) { CalculateFacesWithin(0, 0, layer.width, layer.height, layer) } }; module.exports = SetCollisionByExclusion }, function(module, exports, __webpack_require__) { var SetTileCollision = __webpack_require__(71); var CalculateFacesWithin = __webpack_require__(53); var HasValue = __webpack_require__(83); var SetCollisionByProperty = function(properties, collides, recalculateFaces, layer) { if (collides === undefined) { collides = true } if (recalculateFaces === undefined) { recalculateFaces = true } for (var ty = 0; ty < layer.height; ty++) { for (var tx = 0; tx < layer.width; tx++) { var tile = layer.data[ty][tx]; if (!tile) { continue } for (var property in properties) { if (!HasValue(tile.properties, property)) { continue } var values = properties[property]; if (!Array.isArray(values)) { values = [values] } for (var i = 0; i < values.length; i++) { if (tile.properties[property] === values[i]) { SetTileCollision(tile, collides) } } } } } if (recalculateFaces) { CalculateFacesWithin(0, 0, layer.width, layer.height, layer) } }; module.exports = SetCollisionByProperty }, function(module, exports, __webpack_require__) { var SetTileCollision = __webpack_require__(71); var CalculateFacesWithin = __webpack_require__(53); var SetCollisionFromCollisionGroup = function(collides, recalculateFaces, layer) { if (collides === undefined) { collides = true } if (recalculateFaces === undefined) { recalculateFaces = true } for (var ty = 0; ty < layer.height; ty++) { for (var tx = 0; tx < layer.width; tx++) { var tile = layer.data[ty][tx]; if (!tile) { continue } var collisionGroup = tile.getCollisionGroup(); if (collisionGroup && collisionGroup.objects && collisionGroup.objects.length > 0) { SetTileCollision(tile, collides) } } } if (recalculateFaces) { CalculateFacesWithin(0, 0, layer.width, layer.height, layer) } }; module.exports = SetCollisionFromCollisionGroup }, function(module, exports) { var SetTileIndexCallback = function(indexes, callback, callbackContext, layer) { if (typeof indexes === "number") { layer.callbacks[indexes] = callback !== null ? { callback: callback, callbackContext: callbackContext } : undefined } else { for (var i = 0, len = indexes.length; i < len; i++) { layer.callbacks[indexes[i]] = callback !== null ? { callback: callback, callbackContext: callbackContext } : undefined } } }; module.exports = SetTileIndexCallback }, function(module, exports, __webpack_require__) { var GetTilesWithin = __webpack_require__(21); var SetTileLocationCallback = function(tileX, tileY, width, height, callback, callbackContext, layer) { var tiles = GetTilesWithin(tileX, tileY, width, height, null, layer); for (var i = 0; i < tiles.length; i++) { tiles[i].setCollisionCallback(callback, callbackContext) } }; module.exports = SetTileLocationCallback }, function(module, exports, __webpack_require__) { var GetTilesWithin = __webpack_require__(21); var ShuffleArray = __webpack_require__(110); var Shuffle = function(tileX, tileY, width, height, layer) { var tiles = GetTilesWithin(tileX, tileY, width, height, null, layer); var indexes = tiles.map(function(tile) { return tile.index }); ShuffleArray(indexes); for (var i = 0; i < tiles.length; i++) { tiles[i].index = indexes[i] } }; module.exports = Shuffle }, function(module, exports, __webpack_require__) { var GetTilesWithin = __webpack_require__(21); var SwapByIndex = function(indexA, indexB, tileX, tileY, width, height, layer) { var tiles = GetTilesWithin(tileX, tileY, width, height, null, layer); for (var i = 0; i < tiles.length; i++) { if (tiles[i]) { if (tiles[i].index === indexA) { tiles[i].index = indexB } else if (tiles[i].index === indexB) { tiles[i].index = indexA } } } }; module.exports = SwapByIndex }, function(module, exports, __webpack_require__) { var TileToWorldX = __webpack_require__(135); var TileToWorldY = __webpack_require__(136); var Vector2 = __webpack_require__(3); var TileToWorldXY = function(tileX, tileY, point, camera, layer) { if (point === undefined) { point = new Vector2(0, 0) } point.x = TileToWorldX(tileX, camera, layer); point.y = TileToWorldY(tileY, camera, layer); return point }; module.exports = TileToWorldXY }, function(module, exports, __webpack_require__) { var GetTilesWithin = __webpack_require__(21); var WeightedRandomize = function(tileX, tileY, width, height, weightedIndexes, layer) { if (weightedIndexes === undefined) { return } var i; var tiles = GetTilesWithin(tileX, tileY, width, height, null, layer); var weightTotal = 0; for (i = 0; i < weightedIndexes.length; i++) { weightTotal += weightedIndexes[i].weight } if (weightTotal <= 0) { return } for (i = 0; i < tiles.length; i++) { var rand = Math.random() * weightTotal; var sum = 0; var randomIndex = -1; for (var j = 0; j < weightedIndexes.length; j++) { sum += weightedIndexes[j].weight; if (rand <= sum) { var chosen = weightedIndexes[j].index; randomIndex = Array.isArray(chosen) ? chosen[Math.floor(Math.random() * chosen.length)] : chosen; break } } tiles[i].index = randomIndex } }; module.exports = WeightedRandomize }, function(module, exports, __webpack_require__) { var WorldToTileX = __webpack_require__(59); var WorldToTileY = __webpack_require__(60); var Vector2 = __webpack_require__(3); var WorldToTileXY = function(worldX, worldY, snapToFloor, point, camera, layer) { if (point === undefined) { point = new Vector2(0, 0) } point.x = WorldToTileX(worldX, snapToFloor, camera, layer); point.y = WorldToTileY(worldY, snapToFloor, camera, layer); return point }; module.exports = WorldToTileXY }, function(module, exports, __webpack_require__) { module.exports = { Parse: __webpack_require__(451), Parse2DArray: __webpack_require__(214), ParseCSV: __webpack_require__(452), Impact: __webpack_require__(458), Tiled: __webpack_require__(453) } }, function(module, exports, __webpack_require__) { var Base64Decode = __webpack_require__(1121); var GetFastValue = __webpack_require__(1); var LayerData = __webpack_require__(105); var ParseGID = __webpack_require__(454); var Tile = __webpack_require__(72); var ParseTileLayers = function(json, insertNull) { var tileLayers = []; for (var i = 0; i < json.layers.length; i++) { if (json.layers[i].type !== "tilelayer") { continue } var curl = json.layers[i]; if (curl.compression) { console.warn("TilemapParser.parseTiledJSON - Layer compression is unsupported, skipping layer '" + curl.name + "'"); continue } else if (curl.encoding && curl.encoding === "base64") { curl.data = Base64Decode(curl.data); delete curl.encoding } var layerData = new LayerData({ name: curl.name, x: GetFastValue(curl, "offsetx", 0) + curl.x, y: GetFastValue(curl, "offsety", 0) + curl.y, width: curl.width, height: curl.height, tileWidth: json.tilewidth, tileHeight: json.tileheight, alpha: curl.opacity, visible: curl.visible, properties: GetFastValue(curl, "properties", {}) }); var x = 0; var row = []; var output = []; for (var t = 0, len = curl.data.length; t < len; t++) { var gidInfo = ParseGID(curl.data[t]); if (gidInfo.gid > 0) { var tile = new Tile(layerData, gidInfo.gid, x, output.length, json.tilewidth, json.tileheight); tile.rotation = gidInfo.rotation; tile.flipX = gidInfo.flipped; row.push(tile) } else { var blankTile = insertNull ? null : new Tile(layerData, -1, x, output.length, json.tilewidth, json.tileheight); row.push(blankTile) } x++; if (x === curl.width) { output.push(row); x = 0; row = [] } } layerData.data = output; tileLayers.push(layerData) } return tileLayers }; module.exports = ParseTileLayers }, function(module, exports) { var Base64Decode = function(data) { var binaryString = window.atob(data); var len = binaryString.length; var bytes = new Array(len / 4); for (var i = 0; i < len; i += 4) { bytes[i / 4] = (binaryString.charCodeAt(i) | binaryString.charCodeAt(i + 1) << 8 | binaryString.charCodeAt(i + 2) << 16 | binaryString.charCodeAt(i + 3) << 24) >>> 0 } return bytes }; module.exports = Base64Decode }, function(module, exports, __webpack_require__) { var GetFastValue = __webpack_require__(1); var ParseImageLayers = function(json) { var images = []; for (var i = 0; i < json.layers.length; i++) { if (json.layers[i].type !== "imagelayer") { continue } var curi = json.layers[i]; images.push({ name: curi.name, image: curi.image, x: GetFastValue(curi, "offsetx", 0) + curi.x, y: GetFastValue(curi, "offsety", 0) + curi.y, alpha: curi.opacity, visible: curi.visible, properties: GetFastValue(curi, "properties", {}) }) } return images }; module.exports = ParseImageLayers }, function(module, exports, __webpack_require__) { var Tileset = __webpack_require__(137); var ImageCollection = __webpack_require__(455); var ParseObject = __webpack_require__(456); var ParseTilesets = function(json) { var tilesets = []; var imageCollections = []; var lastSet = null; var stringID; for (var i = 0; i < json.tilesets.length; i++) { var set = json.tilesets[i]; if (set.source) { console.warn("Phaser can't load external tilesets. Use the Embed Tileset button and then export the map again.") } else if (set.image) { var newSet = new Tileset(set.name, set.firstgid, set.tilewidth, set.tileheight, set.margin, set.spacing); if (json.version > 1) { if (Array.isArray(set.tiles)) { var tiles = {}; var props = {}; for (var t = 0; t < set.tiles.length; t++) { var tile = set.tiles[t]; if (tile.properties) { var newPropData = {}; tile.properties.forEach(function(propData) { newPropData[propData["name"]] = propData["value"] }); props[tile.id] = newPropData } if (tile.objectgroup) { tiles[tile.id] = { objectgroup: tile.objectgroup }; if (tile.objectgroup.objects) { var parsedObjects2 = tile.objectgroup.objects.map(function(obj) { return ParseObject(obj) }); tiles[tile.id].objectgroup.objects = parsedObjects2 } } } newSet.tileData = tiles; newSet.tileProperties = props } } else { if (set.tileproperties) { newSet.tileProperties = set.tileproperties } if (set.tiles) { newSet.tileData = set.tiles; for (stringID in newSet.tileData) { var objectGroup = newSet.tileData[stringID].objectgroup; if (objectGroup && objectGroup.objects) { var parsedObjects1 = objectGroup.objects.map(function(obj) { return ParseObject(obj) }); newSet.tileData[stringID].objectgroup.objects = parsedObjects1 } } } } newSet.updateTileData(set.imagewidth, set.imageheight); tilesets.push(newSet) } else { var newCollection = new ImageCollection(set.name, set.firstgid, set.tilewidth, set.tileheight, set.margin, set.spacing, set.properties); for (stringID in set.tiles) { var image = set.tiles[stringID].image; var gid = set.firstgid + parseInt(stringID, 10); newCollection.addImage(gid, image) } imageCollections.push(newCollection) } if (lastSet) { lastSet.lastgid = set.firstgid - 1 } lastSet = set } return { tilesets: tilesets, imageCollections: imageCollections } }; module.exports = ParseTilesets }, function(module, exports, __webpack_require__) { var HasValue = __webpack_require__(83); var Pick = function(object, keys) { var obj = {}; for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (HasValue(object, key)) { obj[key] = object[key] } } return obj }; module.exports = Pick }, function(module, exports, __webpack_require__) { var GetFastValue = __webpack_require__(1); var ParseObject = __webpack_require__(456); var ObjectLayer = __webpack_require__(457); var ParseObjectLayers = function(json) { var objectLayers = []; for (var i = 0; i < json.layers.length; i++) { if (json.layers[i].type !== "objectgroup") { continue } var curo = json.layers[i]; var offsetX = GetFastValue(curo, "offsetx", 0); var offsetY = GetFastValue(curo, "offsety", 0); var objects = []; for (var j = 0; j < curo.objects.length; j++) { var parsedObject = ParseObject(curo.objects[j], offsetX, offsetY); objects.push(parsedObject) } var objectLayer = new ObjectLayer(curo); objectLayer.objects = objects; objectLayers.push(objectLayer) } return objectLayers }; module.exports = ParseObjectLayers }, function(module, exports) { var BuildTilesetIndex = function(mapData) { var tiles = []; for (var i = 0; i < mapData.tilesets.length; i++) { var set = mapData.tilesets[i]; var x = set.tileMargin; var y = set.tileMargin; var count = 0; var countX = 0; var countY = 0; for (var t = set.firstgid; t < set.firstgid + set.total; t++) { tiles[t] = [x, y, i]; x += set.tileWidth + set.tileSpacing; count++; if (count === set.total) { break } countX++; if (countX === set.columns) { x = set.tileMargin; y += set.tileHeight + set.tileSpacing; countX = 0; countY++; if (countY === set.rows) { break } } } } return tiles }; module.exports = BuildTilesetIndex }, function(module, exports, __webpack_require__) { var Extend = __webpack_require__(19); var AssignTileProperties = function(mapData) { var layerData; var tile; var sid; var set; var row; for (var i = 0; i < mapData.layers.length; i++) { layerData = mapData.layers[i]; set = null; for (var j = 0; j < layerData.data.length; j++) { row = layerData.data[j]; for (var k = 0; k < row.length; k++) { tile = row[k]; if (tile === null || tile.index < 0) { continue } sid = mapData.tiles[tile.index][2]; set = mapData.tilesets[sid]; tile.width = set.tileWidth; tile.height = set.tileHeight; if (set.tileProperties && set.tileProperties[tile.index - set.firstgid]) { tile.properties = Extend(tile.properties, set.tileProperties[tile.index - set.firstgid]) } } } } }; module.exports = AssignTileProperties }, function(module, exports, __webpack_require__) { var LayerData = __webpack_require__(105); var Tile = __webpack_require__(72); var ParseTileLayers = function(json, insertNull) { var tileLayers = []; for (var i = 0; i < json.layer.length; i++) { var layer = json.layer[i]; var layerData = new LayerData({ name: layer.name, width: layer.width, height: layer.height, tileWidth: layer.tilesize, tileHeight: layer.tilesize, visible: layer.visible === 1 }); var row = []; var tileGrid = []; for (var y = 0; y < layer.data.length; y++) { for (var x = 0; x < layer.data[y].length; x++) { var index = layer.data[y][x] - 1; var tile; if (index > -1) { tile = new Tile(layerData, index, x, y, layer.tilesize, layer.tilesize) } else { tile = insertNull ? null : new Tile(layerData, -1, x, y, layer.tilesize, layer.tilesize) } row.push(tile) } tileGrid.push(row); row = [] } layerData.data = tileGrid; tileLayers.push(layerData) } return tileLayers }; module.exports = ParseTileLayers }, function(module, exports, __webpack_require__) { var Tileset = __webpack_require__(137); var ParseTilesets = function(json) { var tilesets = []; var tilesetsNames = []; for (var i = 0; i < json.layer.length; i++) { var layer = json.layer[i]; var tilesetName = layer.tilesetName; if (tilesetName !== "" && tilesetsNames.indexOf(tilesetName) === -1) { tilesetsNames.push(tilesetName); tilesets.push(new Tileset(tilesetName, 0, layer.tilesize, layer.tilesize, 0, 0)) } } return tilesets }; module.exports = ParseTilesets }, function(module, exports, __webpack_require__) { var renderWebGL = __webpack_require__(2); var renderCanvas = __webpack_require__(2); if (true) { renderWebGL = __webpack_require__(1131) } if (true) { renderCanvas = __webpack_require__(1132) } module.exports = { renderWebGL: renderWebGL, renderCanvas: renderCanvas } }, function(module, exports, __webpack_require__) { var Utils = __webpack_require__(10); var DynamicTilemapLayerWebGLRenderer = function(renderer, src, interpolationPercentage, camera) { src.cull(camera); var renderTiles = src.culledTiles; var tileCount = renderTiles.length; var alpha = camera.alpha * src.alpha; if (tileCount === 0 || alpha <= 0) { return } var gidMap = src.gidMap; var pipeline = src.pipeline; var getTint = Utils.getTintAppendFloatAlpha; var scrollFactorX = src.scrollFactorX; var scrollFactorY = src.scrollFactorY; var x = src.x; var y = src.y; var sx = src.scaleX; var sy = src.scaleY; var tilesets = src.tileset; for (var c = 0; c < tilesets.length; c++) { var currentSet = tilesets[c]; var texture = currentSet.glTexture; for (var i = 0; i < tileCount; i++) { var tile = renderTiles[i]; var tileset = gidMap[tile.index]; if (tileset !== currentSet) { continue } var tileTexCoords = tileset.getTileTextureCoordinates(tile.index); if (tileTexCoords === null) { continue } var frameWidth = tile.width; var frameHeight = tile.height; var frameX = tileTexCoords.x; var frameY = tileTexCoords.y; var tw = tile.width * .5; var th = tile.height * .5; var tint = getTint(tile.tint, alpha * tile.alpha); pipeline.batchTexture(src, texture, texture.width, texture.height, (tw + x + tile.pixelX) * sx, (th + y + tile.pixelY) * sy, tile.width, tile.height, sx, sy, tile.rotation, tile.flipX, tile.flipY, scrollFactorX, scrollFactorY, tw, th, frameX, frameY, frameWidth, frameHeight, tint, tint, tint, tint, false, 0, 0, camera, null, true) } } }; module.exports = DynamicTilemapLayerWebGLRenderer }, function(module, exports) { var DynamicTilemapLayerCanvasRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix) { src.cull(camera); var renderTiles = src.culledTiles; var tileCount = renderTiles.length; if (tileCount === 0) { return } var camMatrix = renderer._tempMatrix1; var layerMatrix = renderer._tempMatrix2; var calcMatrix = renderer._tempMatrix3; layerMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); camMatrix.copyFrom(camera.matrix); var ctx = renderer.currentContext; var gidMap = src.gidMap; ctx.save(); if (parentMatrix) { camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); layerMatrix.e = src.x; layerMatrix.f = src.y; camMatrix.multiply(layerMatrix, calcMatrix); calcMatrix.copyToContext(ctx) } else { layerMatrix.e -= camera.scrollX * src.scrollFactorX; layerMatrix.f -= camera.scrollY * src.scrollFactorY; layerMatrix.copyToContext(ctx) } var alpha = camera.alpha * src.alpha; for (var i = 0; i < tileCount; i++) { var tile = renderTiles[i]; var tileset = gidMap[tile.index]; if (!tileset) { continue } var image = tileset.image.getSourceImage(); var tileTexCoords = tileset.getTileTextureCoordinates(tile.index); if (tileTexCoords) { var halfWidth = tile.width / 2; var halfHeight = tile.height / 2; ctx.save(); ctx.translate(tile.pixelX + halfWidth, tile.pixelY + halfHeight); if (tile.rotation !== 0) { ctx.rotate(tile.rotation) } if (tile.flipX || tile.flipY) { ctx.scale(tile.flipX ? -1 : 1, tile.flipY ? -1 : 1) } ctx.globalAlpha = alpha * tile.alpha; ctx.drawImage(image, tileTexCoords.x, tileTexCoords.y, tile.width, tile.height, -halfWidth, -halfHeight, tile.width, tile.height); ctx.restore() } } ctx.restore() }; module.exports = DynamicTilemapLayerCanvasRenderer }, function(module, exports, __webpack_require__) { var renderWebGL = __webpack_require__(2); var renderCanvas = __webpack_require__(2); if (true) { renderWebGL = __webpack_require__(1134) } if (true) { renderCanvas = __webpack_require__(1135) } module.exports = { renderWebGL: renderWebGL, renderCanvas: renderCanvas } }, function(module, exports) { var StaticTilemapLayerWebGLRenderer = function(renderer, src, interpolationPercentage, camera) { var tilesets = src.tileset; var pipeline = src.pipeline; var pipelineVertexBuffer = pipeline.vertexBuffer; renderer.setPipeline(pipeline); pipeline.modelIdentity(); pipeline.modelTranslate(src.x - camera.scrollX * src.scrollFactorX, src.y - camera.scrollY * src.scrollFactorY, 0); pipeline.modelScale(src.scaleX, src.scaleY, 1); pipeline.viewLoad2D(camera.matrix.matrix); for (var i = 0; i < tilesets.length; i++) { src.upload(camera, i); if (src.vertexCount[i] > 0) { if (renderer.currentPipeline && renderer.currentPipeline.vertexCount > 0) { renderer.flush() } pipeline.vertexBuffer = src.vertexBuffer[i]; renderer.setPipeline(pipeline); renderer.setTexture2D(tilesets[i].glTexture, 0); renderer.gl.drawArrays(pipeline.topology, 0, src.vertexCount[i]) } } pipeline.vertexBuffer = pipelineVertexBuffer; pipeline.viewIdentity(); pipeline.modelIdentity() }; module.exports = StaticTilemapLayerWebGLRenderer }, function(module, exports) { var StaticTilemapLayerCanvasRenderer = function(renderer, src, interpolationPercentage, camera, parentMatrix) { src.cull(camera); var renderTiles = src.culledTiles; var tileCount = renderTiles.length; if (tileCount === 0) { return } var camMatrix = renderer._tempMatrix1; var layerMatrix = renderer._tempMatrix2; var calcMatrix = renderer._tempMatrix3; layerMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY); camMatrix.copyFrom(camera.matrix); var ctx = renderer.currentContext; var gidMap = src.gidMap; ctx.save(); if (parentMatrix) { camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY); layerMatrix.e = src.x; layerMatrix.f = src.y; camMatrix.multiply(layerMatrix, calcMatrix); calcMatrix.copyToContext(ctx) } else { layerMatrix.e -= camera.scrollX * src.scrollFactorX; layerMatrix.f -= camera.scrollY * src.scrollFactorY; layerMatrix.copyToContext(ctx) } var alpha = camera.alpha * src.alpha; ctx.globalAlpha = camera.alpha * src.alpha; for (var i = 0; i < tileCount; i++) { var tile = renderTiles[i]; var tileset = gidMap[tile.index]; if (!tileset) { continue } var image = tileset.image.getSourceImage(); var tileTexCoords = tileset.getTileTextureCoordinates(tile.index); if (tileTexCoords) { var halfWidth = tile.width / 2; var halfHeight = tile.height / 2; ctx.save(); ctx.translate(tile.pixelX + halfWidth, tile.pixelY + halfHeight); if (tile.rotation !== 0) { ctx.rotate(tile.rotation) } if (tile.flipX || tile.flipY) { ctx.scale(tile.flipX ? -1 : 1, tile.flipY ? -1 : 1) } ctx.globalAlpha = alpha * tile.alpha; ctx.drawImage(image, tileTexCoords.x, tileTexCoords.y, tile.width, tile.height, -halfWidth, -halfHeight, tile.width, tile.height); ctx.restore() } } ctx.restore() }; module.exports = StaticTilemapLayerCanvasRenderer }, function(module, exports, __webpack_require__) { var GameObjectCreator = __webpack_require__(16); var ParseToTilemap = __webpack_require__(215); GameObjectCreator.register("tilemap", function(config) { var c = config !== undefined ? config : {}; return ParseToTilemap(this.scene, c.key, c.tileWidth, c.tileHeight, c.width, c.height, c.data, c.insertNull) }) }, function(module, exports, __webpack_require__) { var GameObjectFactory = __webpack_require__(5); var ParseToTilemap = __webpack_require__(215); GameObjectFactory.register("tilemap", function(key, tileWidth, tileHeight, width, height, data, insertNull) { if (key === null) { key = undefined } if (tileWidth === null) { tileWidth = undefined } if (tileHeight === null) { tileHeight = undefined } if (width === null) { width = undefined } if (height === null) { height = undefined } return ParseToTilemap(this.scene, key, tileWidth, tileHeight, width, height, data, insertNull) }) }, function(module, exports, __webpack_require__) { module.exports = { Clock: __webpack_require__(1139), TimerEvent: __webpack_require__(462) } }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var PluginCache = __webpack_require__(15); var TimerEvent = __webpack_require__(462); var Clock = new Class({ initialize: function Clock(scene) { this.scene = scene; this.systems = scene.sys; this.now = Date.now(); this.timeScale = 1; this.paused = false; this._active = []; this._pendingInsertion = []; this._pendingRemoval = []; scene.sys.events.once("boot", this.boot, this); scene.sys.events.on("start", this.start, this) }, boot: function() { this.systems.events.once("destroy", this.destroy, this) }, start: function() { var eventEmitter = this.systems.events; eventEmitter.on("preupdate", this.preUpdate, this); eventEmitter.on("update", this.update, this); eventEmitter.once("shutdown", this.shutdown, this) }, addEvent: function(config) { var event = new TimerEvent(config); this._pendingInsertion.push(event); return event }, delayedCall: function(delay, callback, args, callbackScope) { return this.addEvent({ delay: delay, callback: callback, args: args, callbackScope: callbackScope }) }, clearPendingEvents: function() { this._pendingInsertion = []; return this }, removeAllEvents: function() { this._pendingRemoval = this._pendingRemoval.concat(this._active); return this }, preUpdate: function() { var toRemove = this._pendingRemoval.length; var toInsert = this._pendingInsertion.length; if (toRemove === 0 && toInsert === 0) { return } var i; var event; for (i = 0; i < toRemove; i++) { event = this._pendingRemoval[i]; var index = this._active.indexOf(event); if (index > -1) { this._active.splice(index, 1) } event.destroy() } for (i = 0; i < toInsert; i++) { event = this._pendingInsertion[i]; this._active.push(event) } this._pendingRemoval.length = 0; this._pendingInsertion.length = 0 }, update: function(time, delta) { this.now = time; if (this.paused) { return } delta *= this.timeScale; for (var i = 0; i < this._active.length; i++) { var event = this._active[i]; if (event.paused) { continue } event.elapsed += delta * event.timeScale; if (event.elapsed >= event.delay) { var remainder = event.elapsed - event.delay; event.elapsed = event.delay; if (!event.hasDispatched && event.callback) { event.hasDispatched = true; event.callback.apply(event.callbackScope, event.args) } if (event.repeatCount > 0) { event.repeatCount--; event.elapsed = remainder; event.hasDispatched = false } else { this._pendingRemoval.push(event) } } } }, shutdown: function() { var i; for (i = 0; i < this._pendingInsertion.length; i++) { this._pendingInsertion[i].destroy() } for (i = 0; i < this._active.length; i++) { this._active[i].destroy() } for (i = 0; i < this._pendingRemoval.length; i++) { this._pendingRemoval[i].destroy() } this._active.length = 0; this._pendingRemoval.length = 0; this._pendingInsertion.length = 0; var eventEmitter = this.systems.events; eventEmitter.off("preupdate", this.preUpdate, this); eventEmitter.off("update", this.update, this); eventEmitter.off("shutdown", this.shutdown, this) }, destroy: function() { this.shutdown(); this.scene.sys.events.off("start", this.start, this); this.scene = null; this.systems = null } }); PluginCache.register("Clock", Clock, "time"); module.exports = Clock }, function(module, exports, __webpack_require__) { var CONST = __webpack_require__(99); var Extend = __webpack_require__(19); var Tweens = { Builders: __webpack_require__(1141), TweenManager: __webpack_require__(1143), Tween: __webpack_require__(219), TweenData: __webpack_require__(220), Timeline: __webpack_require__(467) }; Tweens = Extend(false, Tweens, CONST); module.exports = Tweens }, function(module, exports, __webpack_require__) { module.exports = { GetBoolean: __webpack_require__(98), GetEaseFunction: __webpack_require__(97), GetNewValue: __webpack_require__(138), GetProps: __webpack_require__(463), GetTargets: __webpack_require__(216), GetTweens: __webpack_require__(464), GetValueOp: __webpack_require__(217), NumberTweenBuilder: __webpack_require__(465), TimelineBuilder: __webpack_require__(466), TweenBuilder: __webpack_require__(139) } }, function(module, exports) { module.exports = ["callbackScope", "completeDelay", "delay", "duration", "ease", "easeParams", "flipX", "flipY", "hold", "loop", "loopDelay", "offset", "onComplete", "onCompleteParams", "onCompleteScope", "onLoop", "onLoopParams", "onLoopScope", "onRepeat", "onRepeatParams", "onRepeatScope", "onStart", "onStartParams", "onStartScope", "onUpdate", "onUpdateParams", "onUpdateScope", "onYoyo", "onYoyoParams", "onYoyoScope", "paused", "props", "repeat", "repeatDelay", "targets", "useFrames", "yoyo"] }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var NumberTweenBuilder = __webpack_require__(465); var PluginCache = __webpack_require__(15); var TimelineBuilder = __webpack_require__(466); var TWEEN_CONST = __webpack_require__(99); var TweenBuilder = __webpack_require__(139); var TweenManager = new Class({ initialize: function TweenManager(scene) { this.scene = scene; this.systems = scene.sys; this.timeScale = 1; this._add = []; this._pending = []; this._active = []; this._destroy = []; this._toProcess = 0; scene.sys.events.once("boot", this.boot, this); scene.sys.events.on("start", this.start, this) }, boot: function() { this.systems.events.once("destroy", this.destroy, this) }, start: function() { var eventEmitter = this.systems.events; eventEmitter.on("preupdate", this.preUpdate, this); eventEmitter.on("update", this.update, this); eventEmitter.once("shutdown", this.shutdown, this); this.timeScale = 1 }, createTimeline: function(config) { return TimelineBuilder(this, config) }, timeline: function(config) { var timeline = TimelineBuilder(this, config); if (!timeline.paused) { this._add.push(timeline); this._toProcess++ } return timeline }, create: function(config) { return TweenBuilder(this, config) }, add: function(config) { var tween = TweenBuilder(this, config); this._add.push(tween); this._toProcess++; return tween }, existing: function(tween) { this._add.push(tween); this._toProcess++; return this }, addCounter: function(config) { var tween = NumberTweenBuilder(this, config); this._add.push(tween); this._toProcess++; return tween }, preUpdate: function() { if (this._toProcess === 0) { return } var list = this._destroy; var active = this._active; var pending = this._pending; var i; var tween; for (i = 0; i < list.length; i++) { tween = list[i]; var idx = active.indexOf(tween); if (idx === -1) { idx = pending.indexOf(tween); if (idx > -1) { tween.state = TWEEN_CONST.REMOVED; pending.splice(idx, 1) } } else { tween.state = TWEEN_CONST.REMOVED; active.splice(idx, 1) } } list.length = 0; list = this._add; for (i = 0; i < list.length; i++) { tween = list[i]; if (tween.state === TWEEN_CONST.PENDING_ADD) { if (tween.init()) { tween.play(); this._active.push(tween) } else { this._pending.push(tween) } } } list.length = 0; this._toProcess = 0 }, update: function(timestamp, delta) { var list = this._active; var tween; delta *= this.timeScale; for (var i = 0; i < list.length; i++) { tween = list[i]; if (tween.update(timestamp, delta)) { this._destroy.push(tween); this._toProcess++ } } }, makeActive: function(tween) { if (this._add.indexOf(tween) !== -1 || this._active.indexOf(tween) !== -1) { return } var idx = this._pending.indexOf(tween); if (idx !== -1) { this._pending.splice(idx, 1) } this._add.push(tween); tween.state = TWEEN_CONST.PENDING_ADD; this._toProcess++; return this }, each: function(callback, scope) { var args = [null]; for (var i = 1; i < arguments.length; i++) { args.push(arguments[i]) } for (var texture in this.list) { args[0] = this.list[texture]; callback.apply(scope, args) } }, getAllTweens: function() { var list = this._active; var output = []; for (var i = 0; i < list.length; i++) { output.push(list[i]) } return output }, getGlobalTimeScale: function() { return this.timeScale }, getTweensOf: function(target) { var list = this._active; var tween; var output = []; var i; if (Array.isArray(target)) { for (i = 0; i < list.length; i++) { tween = list[i]; for (var t = 0; t < target.length; t++) { if (tween.hasTarget(target[t])) { output.push(tween) } } } } else { for (i = 0; i < list.length; i++) { tween = list[i]; if (tween.hasTarget(target)) { output.push(tween) } } } return output }, isTweening: function(target) { var list = this._active; var tween; for (var i = 0; i < list.length; i++) { tween = list[i]; if (tween.hasTarget(target) && tween.isPlaying()) { return true } } return false }, killAll: function() { var tweens = this.getAllTweens(); for (var i = 0; i < tweens.length; i++) { tweens[i].stop() } return this }, killTweensOf: function(target) { var tweens = this.getTweensOf(target); for (var i = 0; i < tweens.length; i++) { tweens[i].stop() } return this }, pauseAll: function() { var list = this._active; for (var i = 0; i < list.length; i++) { list[i].pause() } return this }, resumeAll: function() { var list = this._active; for (var i = 0; i < list.length; i++) { list[i].resume() } return this }, setGlobalTimeScale: function(value) { this.timeScale = value; return this }, shutdown: function() { this.killAll(); this._add = []; this._pending = []; this._active = []; this._destroy = []; this._toProcess = 0; var eventEmitter = this.systems.events; eventEmitter.off("preupdate", this.preUpdate, this); eventEmitter.off("update", this.update, this); eventEmitter.off("shutdown", this.shutdown, this) }, destroy: function() { this.shutdown(); this.scene.sys.events.off("start", this.start, this); this.scene = null; this.systems = null } }); PluginCache.register("TweenManager", TweenManager, "tweens"); module.exports = TweenManager }, function(module, exports, __webpack_require__) { module.exports = { Array: __webpack_require__(175), Objects: __webpack_require__(1145), String: __webpack_require__(1149) } }, function(module, exports, __webpack_require__) { module.exports = { Clone: __webpack_require__(64), Extend: __webpack_require__(19), GetAdvancedValue: __webpack_require__(13), GetFastValue: __webpack_require__(1), GetMinMaxValue: __webpack_require__(1146), GetValue: __webpack_require__(4), HasAll: __webpack_require__(1147), HasAny: __webpack_require__(351), HasValue: __webpack_require__(83), IsPlainObject: __webpack_require__(7), Merge: __webpack_require__(80), MergeRight: __webpack_require__(1148) } }, function(module, exports, __webpack_require__) { var GetValue = __webpack_require__(4); var Clamp = __webpack_require__(23); var GetMinMaxValue = function(source, key, min, max, defaultValue) { if (defaultValue === undefined) { defaultValue = min } var value = GetValue(source, key, defaultValue); return Clamp(value, min, max) }; module.exports = GetMinMaxValue }, function(module, exports) { var HasAll = function(source, keys) { for (var i = 0; i < keys.length; i++) { if (!source.hasOwnProperty(keys[i])) { return false } } return true }; module.exports = HasAll }, function(module, exports, __webpack_require__) { var Clone = __webpack_require__(64); var MergeRight = function(obj1, obj2) { var clone = Clone(obj1); for (var key in obj2) { if (clone.hasOwnProperty(key)) { clone[key] = obj2[key] } } return clone }; module.exports = MergeRight }, function(module, exports, __webpack_require__) { module.exports = { Format: __webpack_require__(1150), Pad: __webpack_require__(158), Reverse: __webpack_require__(1151), UppercaseFirst: __webpack_require__(322), UUID: __webpack_require__(354) } }, function(module, exports) { var Format = function(string, values) { return string.replace(/%([0-9]+)/g, function(s, n) { return values[Number(n) - 1] }) }; module.exports = Format }, function(module, exports) { var ReverseString = function(string) { return string.split("").reverse().join("") }; module.exports = ReverseString }, function(module, exports, __webpack_require__) { module.exports = { Camera: __webpack_require__(221), CameraManager: __webpack_require__(1153), OrthographicCamera: __webpack_require__(468), PerspectiveCamera: __webpack_require__(469) } }, function(module, exports, __webpack_require__) { var Class = __webpack_require__(0); var OrthographicCamera = __webpack_require__(468); var PerspectiveCamera = __webpack_require__(469); var PluginCache = __webpack_require__(15); var CameraManager = new Class({ initialize: function CameraManager(scene) { this.scene = scene; this.systems = scene.sys; this.cameras = []; scene.sys.events.once("boot", this.boot, this); scene.sys.events.on("start", this.start, this) }, boot: function() { this.systems.events.once("destroy", this.destroy, this) }, start: function() { var eventEmitter = this.systems.events; eventEmitter.on("update", this.update, this); eventEmitter.once("shutdown", this.shutdown, this) }, add: function(fieldOfView, width, height) { return this.addPerspectiveCamera(fieldOfView, width, height) }, addOrthographicCamera: function(width, height) { var config = this.scene.sys.game.config; if (width === undefined) { width = config.width } if (height === undefined) { height = config.height } var camera = new OrthographicCamera(this.scene, width, height); this.cameras.push(camera); return camera }, addPerspectiveCamera: function(fieldOfView, width, height) { var config = this.scene.sys.game.config; if (fieldOfView === undefined) { fieldOfView = 80 } if (width === undefined) { width = config.width } if (height === undefined) { height = config.height } var camera = new PerspectiveCamera(this.scene, fieldOfView, width, height); this.cameras.push(camera); return camera }, getCamera: function(name) { for (var i = 0; i < this.cameras.length; i++) { if (this.cameras[i].name === name) { return this.cameras[i] } } return null }, removeCamera: function(camera) { var cameraIndex = this.cameras.indexOf(camera); if (cameraIndex !== -1) { this.cameras.splice(cameraIndex, 1) } }, removeAll: function() { while (this.cameras.length > 0) { var camera = this.cameras.pop(); camera.destroy() } return this.main }, update: function(timestep, delta) { for (var i = 0, l = this.cameras.length; i < l; ++i) { this.cameras[i].update(timestep, delta) } }, shutdown: function() { var eventEmitter = this.systems.events; eventEmitter.off("update", this.update, this); eventEmitter.off("shutdown", this.shutdown, this); this.removeAll() }, destroy: function() { this.shutdown(); this.scene.sys.events.off("start", this.start, this); this.scene = null; this.systems = null } }); PluginCache.register("CameraManager3D", CameraManager, "cameras3d"); module.exports = CameraManager }, function(module, exports, __webpack_require__) { var Sprite3D = __webpack_require__(140); var GameObjectFactory = __webpack_require__(5); GameObjectFactory.register("sprite3D", function(x, y, z, key, frame) { var sprite = new Sprite3D(this.scene, x, y, z, key, frame); this.displayList.add(sprite.gameObject); this.updateList.add(sprite.gameObject); return sprite }) }, function(module, exports, __webpack_require__) { var BuildGameObject = __webpack_require__(29); var BuildGameObjectAnimation = __webpack_require__(178); var GameObjectCreator = __webpack_require__(16); var GetAdvancedValue = __webpack_require__(13); var Sprite3D = __webpack_require__(140); GameObjectCreator.register("sprite3D", function(config, addToScene) { if (config === undefined) { config = {} } var key = GetAdvancedValue(config, "key", null); var frame = GetAdvancedValue(config, "frame", null); var sprite = new Sprite3D(this.scene, 0, 0, key, frame); if (addToScene !== undefined) { config.add = addToScene } BuildGameObject(this.scene, sprite, config); BuildGameObjectAnimation(sprite, config); return sprite }) }, function(module, exports) {}, function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); __webpack_require__.d(__webpack_exports__, "version", function() { return version }); __webpack_require__.d(__webpack_exports__, "parse", function() { return parse }); __webpack_require__.d(__webpack_exports__, "parseExpressionAt", function() { return parseExpressionAt }); __webpack_require__.d(__webpack_exports__, "tokenizer", function() { return tokenizer }); __webpack_require__.d(__webpack_exports__, "parse_dammit", function() { return parse_dammit }); __webpack_require__.d(__webpack_exports__, "LooseParser", function() { return LooseParser }); __webpack_require__.d(__webpack_exports__, "pluginsLoose", function() { return pluginsLoose }); __webpack_require__.d(__webpack_exports__, "addLooseExports", function() { return addLooseExports }); __webpack_require__.d(__webpack_exports__, "Parser", function() { return Parser }); __webpack_require__.d(__webpack_exports__, "plugins", function() { return plugins }); __webpack_require__.d(__webpack_exports__, "defaultOptions", function() { return defaultOptions }); __webpack_require__.d(__webpack_exports__, "Position", function() { return Position }); __webpack_require__.d(__webpack_exports__, "SourceLocation", function() { return SourceLocation }); __webpack_require__.d(__webpack_exports__, "getLineInfo", function() { return getLineInfo }); __webpack_require__.d(__webpack_exports__, "Node", function() { return Node }); __webpack_require__.d(__webpack_exports__, "TokenType", function() { return TokenType }); __webpack_require__.d(__webpack_exports__, "tokTypes", function() { return types }); __webpack_require__.d(__webpack_exports__, "keywordTypes", function() { return keywords$1 }); __webpack_require__.d(__webpack_exports__, "TokContext", function() { return TokContext }); __webpack_require__.d(__webpack_exports__, "tokContexts", function() { return types$1 }); __webpack_require__.d(__webpack_exports__, "isIdentifierChar", function() { return isIdentifierChar }); __webpack_require__.d(__webpack_exports__, "isIdentifierStart", function() { return isIdentifierStart }); __webpack_require__.d(__webpack_exports__, "Token", function() { return Token }); __webpack_require__.d(__webpack_exports__, "isNewLine", function() { return isNewLine }); __webpack_require__.d(__webpack_exports__, "lineBreak", function() { return lineBreak }); __webpack_require__.d(__webpack_exports__, "lineBreakG", function() { return lineBreakG }); __webpack_require__.d(__webpack_exports__, "nonASCIIwhitespace", function() { return nonASCIIwhitespace }); var reservedWords = { 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile", 5: "class enum extends super const export import", 6: "enum", strict: "implements interface let package private protected public static yield", strictBind: "eval arguments" }; var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this"; var keywords = { 5: ecma5AndLessKeywords, 6: ecma5AndLessKeywords + " const class extends export import super" }; var keywordRelationalOperator = /^in(stanceof)?$/; var nonASCIIidentifierStartChars = "ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙՠ-ֈא-תׯ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࡠ-ࡪࢠ-ࢴࢶ-ࢽऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡸᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-ᲈᲐ-ᲺᲽ-Ჿᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄯㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿯ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞹꟷ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꣾꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭥꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ"; var nonASCIIidentifierChars = "·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛࣓-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఄా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ංඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ູົຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭ᳲ-᳴᳷-᳹᷀-᷹᷻-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱ꣿ-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_"; var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 157, 310, 10, 21, 11, 7, 153, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 477, 28, 11, 0, 9, 21, 190, 52, 76, 44, 33, 24, 27, 35, 30, 0, 12, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 85, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 54, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 86, 26, 230, 43, 117, 63, 32, 0, 257, 0, 11, 39, 8, 0, 22, 0, 12, 39, 3, 3, 20, 0, 35, 56, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 270, 921, 103, 110, 18, 195, 2749, 1070, 4050, 582, 8634, 568, 8, 30, 114, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 68, 12, 0, 67, 12, 65, 1, 31, 6129, 15, 754, 9486, 286, 82, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 4149, 196, 60, 67, 1213, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42710, 42, 4148, 12, 221, 3, 5761, 15, 7472, 3104, 541]; var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 525, 10, 176, 2, 54, 14, 32, 9, 16, 3, 46, 10, 54, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 4, 9, 83, 11, 7, 0, 161, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 280, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 19306, 9, 135, 4, 60, 6, 26, 9, 1016, 45, 17, 3, 19723, 1, 5319, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 2214, 6, 110, 6, 6, 9, 792487, 239]; function isInAstralSet(code, set) { var pos = 65536; for (var i = 0; i < set.length; i += 2) { pos += set[i]; if (pos > code) { return false } pos += set[i + 1]; if (pos >= code) { return true } } } function isIdentifierStart(code, astral) { if (code < 65) { return code === 36 } if (code < 91) { return true } if (code < 97) { return code === 95 } if (code < 123) { return true } if (code <= 65535) { return code >= 170 && nonASCIIidentifierStart.test(String.fromCharCode(code)) } if (astral === false) { return false } return isInAstralSet(code, astralIdentifierStartCodes) } function isIdentifierChar(code, astral) { if (code < 48) { return code === 36 } if (code < 58) { return true } if (code < 65) { return false } if (code < 91) { return true } if (code < 97) { return code === 95 } if (code < 123) { return true } if (code <= 65535) { return code >= 170 && nonASCIIidentifier.test(String.fromCharCode(code)) } if (astral === false) { return false } return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes) } var TokenType = function TokenType(label, conf) { if (conf === void 0) conf = {}; this.label = label; this.keyword = conf.keyword; this.beforeExpr = !!conf.beforeExpr; this.startsExpr = !!conf.startsExpr; this.isLoop = !!conf.isLoop; this.isAssign = !!conf.isAssign; this.prefix = !!conf.prefix; this.postfix = !!conf.postfix; this.binop = conf.binop || null; this.updateContext = null }; function binop(name, prec) { return new TokenType(name, { beforeExpr: true, binop: prec }) } var beforeExpr = { beforeExpr: true }; var startsExpr = { startsExpr: true }; var keywords$1 = {}; function kw(name, options) { if (options === void 0) options = {}; options.keyword = name; return keywords$1[name] = new TokenType(name, options) } var types = { num: new TokenType("num", startsExpr), regexp: new TokenType("regexp", startsExpr), string: new TokenType("string", startsExpr), name: new TokenType("name", startsExpr), eof: new TokenType("eof"), bracketL: new TokenType("[", { beforeExpr: true, startsExpr: true }), bracketR: new TokenType("]"), braceL: new TokenType("{", { beforeExpr: true, startsExpr: true }), braceR: new TokenType("}"), parenL: new TokenType("(", { beforeExpr: true, startsExpr: true }), parenR: new TokenType(")"), comma: new TokenType(",", beforeExpr), semi: new TokenType(";", beforeExpr), colon: new TokenType(":", beforeExpr), dot: new TokenType("."), question: new TokenType("?", beforeExpr), arrow: new TokenType("=>", beforeExpr), template: new TokenType("template"), invalidTemplate: new TokenType("invalidTemplate"), ellipsis: new TokenType("...", beforeExpr), backQuote: new TokenType("`", startsExpr), dollarBraceL: new TokenType("${", { beforeExpr: true, startsExpr: true }), eq: new TokenType("=", { beforeExpr: true, isAssign: true }), assign: new TokenType("_=", { beforeExpr: true, isAssign: true }), incDec: new TokenType("++/--", { prefix: true, postfix: true, startsExpr: true }), prefix: new TokenType("!/~", { beforeExpr: true, prefix: true, startsExpr: true }), logicalOR: binop("||", 1), logicalAND: binop("&&", 2), bitwiseOR: binop("|", 3), bitwiseXOR: binop("^", 4), bitwiseAND: binop("&", 5), equality: binop("==/!=/===/!==", 6), relational: binop("</>/<=/>=", 7), bitShift: binop("<</>>/>>>", 8), plusMin: new TokenType("+/-", { beforeExpr: true, binop: 9, prefix: true, startsExpr: true }), modulo: binop("%", 10), star: binop("*", 10), slash: binop("/", 10), starstar: new TokenType("**", { beforeExpr: true }), _break: kw("break"), _case: kw("case", beforeExpr), _catch: kw("catch"), _continue: kw("continue"), _debugger: kw("debugger"), _default: kw("default", beforeExpr), _do: kw("do", { isLoop: true, beforeExpr: true }), _else: kw("else", beforeExpr), _finally: kw("finally"), _for: kw("for", { isLoop: true }), _function: kw("function", startsExpr), _if: kw("if"), _return: kw("return", beforeExpr), _switch: kw("switch"), _throw: kw("throw", beforeExpr), _try: kw("try"), _var: kw("var"), _const: kw("const"), _while: kw("while", { isLoop: true }), _with: kw("with"), _new: kw("new", { beforeExpr: true, startsExpr: true }), _this: kw("this", startsExpr), _super: kw("super", startsExpr), _class: kw("class", startsExpr), _extends: kw("extends", beforeExpr), _export: kw("export"), _import: kw("import"), _null: kw("null", startsExpr), _true: kw("true", startsExpr), _false: kw("false", startsExpr), _in: kw("in", { beforeExpr: true, binop: 7 }), _instanceof: kw("instanceof", { beforeExpr: true, binop: 7 }), _typeof: kw("typeof", { beforeExpr: true, prefix: true, startsExpr: true }), _void: kw("void", { beforeExpr: true, prefix: true, startsExpr: true }), _delete: kw("delete", { beforeExpr: true, prefix: true, startsExpr: true }) }; var lineBreak = /\r\n?|\n|\u2028|\u2029/; var lineBreakG = new RegExp(lineBreak.source, "g"); function isNewLine(code, ecma2019String) { return code === 10 || code === 13 || !ecma2019String && (code === 8232 || code === 8233) } var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/; var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; var ref = Object.prototype; var hasOwnProperty = ref.hasOwnProperty; var toString = ref.toString; function has(obj, propName) { return hasOwnProperty.call(obj, propName) } var isArray = Array.isArray || function(obj) { return toString.call(obj) === "[object Array]" }; var Position = function Position(line, col) { this.line = line; this.column = col }; Position.prototype.offset = function offset(n) { return new Position(this.line, this.column + n) }; var SourceLocation = function SourceLocation(p, start, end) { this.start = start; this.end = end; if (p.sourceFile !== null) { this.source = p.sourceFile } }; function getLineInfo(input, offset) { for (var line = 1, cur = 0;;) { lineBreakG.lastIndex = cur; var match = lineBreakG.exec(input); if (match && match.index < offset) { ++line; cur = match.index + match[0].length } else { return new Position(line, offset - cur) } } } var defaultOptions = { ecmaVersion: 7, sourceType: "script", onInsertedSemicolon: null, onTrailingComma: null, allowReserved: null, allowReturnOutsideFunction: false, allowImportExportEverywhere: false, allowAwaitOutsideFunction: false, allowHashBang: false, locations: false, onToken: null, onComment: null, ranges: false, program: null, sourceFile: null, directSourceFile: null, preserveParens: false, plugins: {} }; function getOptions(opts) { var options = {}; for (var opt in defaultOptions) { options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt] } if (options.ecmaVersion >= 2015) { options.ecmaVersion -= 2009 } if (options.allowReserved == null) { options.allowReserved = options.ecmaVersion < 5 } if (isArray(options.onToken)) { var tokens = options.onToken; options.onToken = function(token) { return tokens.push(token) } } if (isArray(options.onComment)) { options.onComment = pushComment(options, options.onComment) } return options } function pushComment(options, array) { return function(block, text, start, end, startLoc, endLoc) { var comment = { type: block ? "Block" : "Line", value: text, start: start, end: end }; if (options.locations) { comment.loc = new SourceLocation(this, startLoc, endLoc) } if (options.ranges) { comment.range = [start, end] } array.push(comment) } } var plugins = {}; function keywordRegexp(words) { return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$") } var Parser = function Parser(options, input, startPos) { this.options = options = getOptions(options); this.sourceFile = options.sourceFile; this.keywords = keywordRegexp(keywords[options.ecmaVersion >= 6 ? 6 : 5]); var reserved = ""; if (!options.allowReserved) { for (var v = options.ecmaVersion;; v--) { if (reserved = reservedWords[v]) { break } } if (options.sourceType === "module") { reserved += " await" } } this.reservedWords = keywordRegexp(reserved); var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict; this.reservedWordsStrict = keywordRegexp(reservedStrict); this.reservedWordsStrictBind = keywordRegexp(reservedStrict + " " + reservedWords.strictBind); this.input = String(input); this.containsEsc = false; this.loadPlugins(options.plugins); if (startPos) { this.pos = startPos; this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1; this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length } else { this.pos = this.lineStart = 0; this.curLine = 1 } this.type = types.eof; this.value = null; this.start = this.end = this.pos; this.startLoc = this.endLoc = this.curPosition(); this.lastTokEndLoc = this.lastTokStartLoc = null; this.lastTokStart = this.lastTokEnd = this.pos; this.context = this.initialContext(); this.exprAllowed = true; this.inModule = options.sourceType === "module"; this.strict = this.inModule || this.strictDirective(this.pos); this.potentialArrowAt = -1; this.inFunction = this.inGenerator = this.inAsync = false; this.yieldPos = this.awaitPos = 0; this.labels = []; if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!") { this.skipLineComment(2) } this.scopeStack = []; this.enterFunctionScope(); this.regexpState = null }; Parser.prototype.isKeyword = function isKeyword(word) { return this.keywords.test(word) }; Parser.prototype.isReservedWord = function isReservedWord(word) { return this.reservedWords.test(word) }; Parser.prototype.extend = function extend(name, f) { this[name] = f(this[name]) }; Parser.prototype.loadPlugins = function loadPlugins(pluginConfigs) { var this$1 = this; for (var name in pluginConfigs) { var plugin = plugins[name]; if (!plugin) { throw new Error("Plugin '" + name + "' not found") } plugin(this$1, pluginConfigs[name]) } }; Parser.prototype.parse = function parse() { var node = this.options.program || this.startNode(); this.nextToken(); return this.parseTopLevel(node) }; var pp = Parser.prototype; var literal = /^(?:'((?:\\.|[^'])*?)'|"((?:\\.|[^"])*?)"|;)/; pp.strictDirective = function(start) { var this$1 = this; for (;;) { skipWhiteSpace.lastIndex = start; start += skipWhiteSpace.exec(this$1.input)[0].length; var match = literal.exec(this$1.input.slice(start)); if (!match) { return false } if ((match[1] || match[2]) === "use strict") { return true } start += match[0].length } }; pp.eat = function(type) { if (this.type === type) { this.next(); return true } else { return false } }; pp.isContextual = function(name) { return this.type === types.name && this.value === name && !this.containsEsc }; pp.eatContextual = function(name) { if (!this.isContextual(name)) { return false } this.next(); return true }; pp.expectContextual = function(name) { if (!this.eatContextual(name)) { this.unexpected() } }; pp.canInsertSemicolon = function() { return this.type === types.eof || this.type === types.braceR || lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }; pp.insertSemicolon = function() { if (this.canInsertSemicolon()) { if (this.options.onInsertedSemicolon) { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc) } return true } }; pp.semicolon = function() { if (!this.eat(types.semi) && !this.insertSemicolon()) { this.unexpected() } }; pp.afterTrailingComma = function(tokType, notNext) { if (this.type === tokType) { if (this.options.onTrailingComma) { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc) } if (!notNext) { this.next() } return true } }; pp.expect = function(type) { this.eat(type) || this.unexpected() }; pp.unexpected = function(pos) { this.raise(pos != null ? pos : this.start, "Unexpected token") }; function DestructuringErrors() { this.shorthandAssign = this.trailingComma = this.parenthesizedAssign = this.parenthesizedBind = this.doubleProto = -1 } pp.checkPatternErrors = function(refDestructuringErrors, isAssign) { if (!refDestructuringErrors) { return } if (refDestructuringErrors.trailingComma > -1) { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element") } var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind; if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern") } }; pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) { if (!refDestructuringErrors) { return false } var shorthandAssign = refDestructuringErrors.shorthandAssign; var doubleProto = refDestructuringErrors.doubleProto; if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 } if (shorthandAssign >= 0) { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns") } if (doubleProto >= 0) { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property") } }; pp.checkYieldAwaitInDefaultParams = function() { if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) { this.raise(this.yieldPos, "Yield expression cannot be a default value") } if (this.awaitPos) { this.raise(this.awaitPos, "Await expression cannot be a default value") } }; pp.isSimpleAssignTarget = function(expr) { if (expr.type === "ParenthesizedExpression") { return this.isSimpleAssignTarget(expr.expression) } return expr.type === "Identifier" || expr.type === "MemberExpression" }; var pp$1 = Parser.prototype; pp$1.parseTopLevel = function(node) { var this$1 = this; var exports = {}; if (!node.body) { node.body = [] } while (this.type !== types.eof) { var stmt = this$1.parseStatement(true, true, exports); node.body.push(stmt) } this.adaptDirectivePrologue(node.body); this.next(); if (this.options.ecmaVersion >= 6) { node.sourceType = this.options.sourceType } return this.finishNode(node, "Program") }; var loopLabel = { kind: "loop" }; var switchLabel = { kind: "switch" }; pp$1.isLet = function() { if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false } skipWhiteSpace.lastIndex = this.pos; var skip = skipWhiteSpace.exec(this.input); var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); if (nextCh === 91 || nextCh === 123) { return true } if (isIdentifierStart(nextCh, true)) { var pos = next + 1; while (isIdentifierChar(this.input.charCodeAt(pos), true)) { ++pos } var ident = this.input.slice(next, pos); if (!keywordRelationalOperator.test(ident)) { return true } } return false }; pp$1.isAsyncFunction = function() { if (this.options.ecmaVersion < 8 || !this.isContextual("async")) { return false } skipWhiteSpace.lastIndex = this.pos; var skip = skipWhiteSpace.exec(this.input); var next = this.pos + skip[0].length; return !lineBreak.test(this.input.slice(this.pos, next)) && this.input.slice(next, next + 8) === "function" && (next + 8 === this.input.length || !isIdentifierChar(this.input.charAt(next + 8))) }; pp$1.parseStatement = function(declaration, topLevel, exports) { var starttype = this.type, node = this.startNode(), kind; if (this.isLet()) { starttype = types._var; kind = "let" } switch (starttype) { case types._break: case types._continue: return this.parseBreakContinueStatement(node, starttype.keyword); case types._debugger: return this.parseDebuggerStatement(node); case types._do: return this.parseDoStatement(node); case types._for: return this.parseForStatement(node); case types._function: if (!declaration && this.options.ecmaVersion >= 6) { this.unexpected() } return this.parseFunctionStatement(node, false); case types._class: if (!declaration) { this.unexpected() } return this.parseClass(node, true); case types._if: return this.parseIfStatement(node); case types._return: return this.parseReturnStatement(node); case types._switch: return this.parseSwitchStatement(node); case types._throw: return this.parseThrowStatement(node); case types._try: return this.parseTryStatement(node); case types._const: case types._var: kind = kind || this.value; if (!declaration && kind !== "var") { this.unexpected() } return this.parseVarStatement(node, kind); case types._while: return this.parseWhileStatement(node); case types._with: return this.parseWithStatement(node); case types.braceL: return this.parseBlock(); case types.semi: return this.parseEmptyStatement(node); case types._export: case types._import: if (!this.options.allowImportExportEverywhere) { if (!topLevel) { this.raise(this.start, "'import' and 'export' may only appear at the top level") } if (!this.inModule) { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'") } } return starttype === types._import ? this.parseImport(node) : this.parseExport(node, exports); default: if (this.isAsyncFunction()) { if (!declaration) { this.unexpected() } this.next(); return this.parseFunctionStatement(node, true) } var maybeName = this.value, expr = this.parseExpression(); if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon)) { return this.parseLabeledStatement(node, maybeName, expr) } else { return this.parseExpressionStatement(node, expr) } } }; pp$1.parseBreakContinueStatement = function(node, keyword) { var this$1 = this; var isBreak = keyword === "break"; this.next(); if (this.eat(types.semi) || this.insertSemicolon()) { node.label = null } else if (this.type !== types.name) { this.unexpected() } else { node.label = this.parseIdent(); this.semicolon() } var i = 0; for (; i < this.labels.length; ++i) { var lab = this$1.labels[i]; if (node.label == null || lab.name === node.label.name) { if (lab.kind != null && (isBreak || lab.kind === "loop")) { break } if (node.label && isBreak) { break } } } if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword) } return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement") }; pp$1.parseDebuggerStatement = function(node) { this.next(); this.semicolon(); return this.finishNode(node, "DebuggerStatement") }; pp$1.parseDoStatement = function(node) { this.next(); this.labels.push(loopLabel); node.body = this.parseStatement(false); this.labels.pop(); this.expect(types._while); node.test = this.parseParenExpression(); if (this.options.ecmaVersion >= 6) { this.eat(types.semi) } else { this.semicolon() } return this.finishNode(node, "DoWhileStatement") }; pp$1.parseForStatement = function(node) { this.next(); var awaitAt = this.options.ecmaVersion >= 9 && this.inAsync && this.eatContextual("await") ? this.lastTokStart : -1; this.labels.push(loopLabel); this.enterLexicalScope(); this.expect(types.parenL); if (this.type === types.semi) { if (awaitAt > -1) { this.unexpected(awaitAt) } return this.parseFor(node, null) } var isLet = this.isLet(); if (this.type === types._var || this.type === types._const || isLet) { var init$1 = this.startNode(), kind = isLet ? "let" : this.value; this.next(); this.parseVar(init$1, true, kind); this.finishNode(init$1, "VariableDeclaration"); if ((this.type === types._in || this.options.ecmaVersion >= 6 && this.isContextual("of")) && init$1.declarations.length === 1 && !(kind !== "var" && init$1.declarations[0].init)) { if (this.options.ecmaVersion >= 9) { if (this.type === types._in) { if (awaitAt > -1) { this.unexpected(awaitAt) } } else { node.await = awaitAt > -1 } } return this.parseForIn(node, init$1) } if (awaitAt > -1) { this.unexpected(awaitAt) } return this.parseFor(node, init$1) } var refDestructuringErrors = new DestructuringErrors; var init = this.parseExpression(true, refDestructuringErrors); if (this.type === types._in || this.options.ecmaVersion >= 6 && this.isContextual("of")) { if (this.options.ecmaVersion >= 9) { if (this.type === types._in) { if (awaitAt > -1) { this.unexpected(awaitAt) } } else { node.await = awaitAt > -1 } } this.toAssignable(init, false, refDestructuringErrors); this.checkLVal(init); return this.parseForIn(node, init) } else { this.checkExpressionErrors(refDestructuringErrors, true) } if (awaitAt > -1) { this.unexpected(awaitAt) } return this.parseFor(node, init) }; pp$1.parseFunctionStatement = function(node, isAsync) { this.next(); return this.parseFunction(node, true, false, isAsync) }; pp$1.parseIfStatement = function(node) { this.next(); node.test = this.parseParenExpression(); node.consequent = this.parseStatement(!this.strict && this.type === types._function); node.alternate = this.eat(types._else) ? this.parseStatement(!this.strict && this.type === types._function) : null; return this.finishNode(node, "IfStatement") }; pp$1.parseReturnStatement = function(node) { if (!this.inFunction && !this.options.allowReturnOutsideFunction) { this.raise(this.start, "'return' outside of function") } this.next(); if (this.eat(types.semi) || this.insertSemicolon()) { node.argument = null } else { node.argument = this.parseExpression(); this.semicolon() } return this.finishNode(node, "ReturnStatement") }; pp$1.parseSwitchStatement = function(node) { var this$1 = this; this.next(); node.discriminant = this.parseParenExpression(); node.cases = []; this.expect(types.braceL); this.labels.push(switchLabel); this.enterLexicalScope(); var cur; for (var sawDefault = false; this.type !== types.braceR;) { if (this$1.type === types._case || this$1.type === types._default) { var isCase = this$1.type === types._case; if (cur) { this$1.finishNode(cur, "SwitchCase") } node.cases.push(cur = this$1.startNode()); cur.consequent = []; this$1.next(); if (isCase) { cur.test = this$1.parseExpression() } else { if (sawDefault) { this$1.raiseRecoverable(this$1.lastTokStart, "Multiple default clauses") } sawDefault = true; cur.test = null } this$1.expect(types.colon) } else { if (!cur) { this$1.unexpected() } cur.consequent.push(this$1.parseStatement(true)) } } this.exitLexicalScope(); if (cur) { this.finishNode(cur, "SwitchCase") } this.next(); this.labels.pop(); return this.finishNode(node, "SwitchStatement") }; pp$1.parseThrowStatement = function(node) { this.next(); if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) { this.raise(this.lastTokEnd, "Illegal newline after throw") } node.argument = this.parseExpression(); this.semicolon(); return this.finishNode(node, "ThrowStatement") }; var empty = []; pp$1.parseTryStatement = function(node) { this.next(); node.block = this.parseBlock(); node.handler = null; if (this.type === types._catch) { var clause = this.startNode(); this.next(); if (this.eat(types.parenL)) { clause.param = this.parseBindingAtom(); this.enterLexicalScope(); this.checkLVal(clause.param, "let"); this.expect(types.parenR) } else { if (this.options.ecmaVersion < 10) { this.unexpected() } clause.param = null; this.enterLexicalScope() } clause.body = this.parseBlock(false); this.exitLexicalScope(); node.handler = this.finishNode(clause, "CatchClause") } node.finalizer = this.eat(types._finally) ? this.parseBlock() : null; if (!node.handler && !node.finalizer) { this.raise(node.start, "Missing catch or finally clause") } return this.finishNode(node, "TryStatement") }; pp$1.parseVarStatement = function(node, kind) { this.next(); this.parseVar(node, false, kind); this.semicolon(); return this.finishNode(node, "VariableDeclaration") }; pp$1.parseWhileStatement = function(node) { this.next(); node.test = this.parseParenExpression(); this.labels.push(loopLabel); node.body = this.parseStatement(false); this.labels.pop(); return this.finishNode(node, "WhileStatement") }; pp$1.parseWithStatement = function(node) { if (this.strict) { this.raise(this.start, "'with' in strict mode") } this.next(); node.object = this.parseParenExpression(); node.body = this.parseStatement(false); return this.finishNode(node, "WithStatement") }; pp$1.parseEmptyStatement = function(node) { this.next(); return this.finishNode(node, "EmptyStatement") }; pp$1.parseLabeledStatement = function(node, maybeName, expr) { var this$1 = this; for (var i$1 = 0, list = this$1.labels; i$1 < list.length; i$1 += 1) { var label = list[i$1]; if (label.name === maybeName) { this$1.raise(expr.start, "Label '" + maybeName + "' is already declared") } } var kind = this.type.isLoop ? "loop" : this.type === types._switch ? "switch" : null; for (var i = this.labels.length - 1; i >= 0; i--) { var label$1 = this$1.labels[i]; if (label$1.statementStart === node.start) { label$1.statementStart = this$1.start; label$1.kind = kind } else { break } } this.labels.push({ name: maybeName, kind: kind, statementStart: this.start }); node.body = this.parseStatement(true); if (node.body.type === "ClassDeclaration" || node.body.type === "VariableDeclaration" && node.body.kind !== "var" || node.body.type === "FunctionDeclaration" && (this.strict || node.body.generator)) { this.raiseRecoverable(node.body.start, "Invalid labeled declaration") } this.labels.pop(); node.label = expr; return this.finishNode(node, "LabeledStatement") }; pp$1.parseExpressionStatement = function(node, expr) { node.expression = expr; this.semicolon(); return this.finishNode(node, "ExpressionStatement") }; pp$1.parseBlock = function(createNewLexicalScope) { var this$1 = this; if (createNewLexicalScope === void 0) createNewLexicalScope = true; var node = this.startNode(); node.body = []; this.expect(types.braceL); if (createNewLexicalScope) { this.enterLexicalScope() } while (!this.eat(types.braceR)) { var stmt = this$1.parseStatement(true); node.body.push(stmt) } if (createNewLexicalScope) { this.exitLexicalScope() } return this.finishNode(node, "BlockStatement") }; pp$1.parseFor = function(node, init) { node.init = init; this.expect(types.semi); node.test = this.type === types.semi ? null : this.parseExpression(); this.expect(types.semi); node.update = this.type === types.parenR ? null : this.parseExpression(); this.expect(types.parenR); this.exitLexicalScope(); node.body = this.parseStatement(false); this.labels.pop(); return this.finishNode(node, "ForStatement") }; pp$1.parseForIn = function(node, init) { var type = this.type === types._in ? "ForInStatement" : "ForOfStatement"; this.next(); if (type === "ForInStatement") { if (init.type === "AssignmentPattern" || init.type === "VariableDeclaration" && init.declarations[0].init != null && (this.strict || init.declarations[0].id.type !== "Identifier")) { this.raise(init.start, "Invalid assignment in for-in loop head") } } node.left = init; node.right = type === "ForInStatement" ? this.parseExpression() : this.parseMaybeAssign(); this.expect(types.parenR); this.exitLexicalScope(); node.body = this.parseStatement(false); this.labels.pop(); return this.finishNode(node, type) }; pp$1.parseVar = function(node, isFor, kind) { var this$1 = this; node.declarations = []; node.kind = kind; for (;;) { var decl = this$1.startNode(); this$1.parseVarId(decl, kind); if (this$1.eat(types.eq)) { decl.init = this$1.parseMaybeAssign(isFor) } else if (kind === "const" && !(this$1.type === types._in || this$1.options.ecmaVersion >= 6 && this$1.isContextual("of"))) { this$1.unexpected() } else if (decl.id.type !== "Identifier" && !(isFor && (this$1.type === types._in || this$1.isContextual("of")))) { this$1.raise(this$1.lastTokEnd, "Complex binding patterns require an initialization value") } else { decl.init = null } node.declarations.push(this$1.finishNode(decl, "VariableDeclarator")); if (!this$1.eat(types.comma)) { break } } return node }; pp$1.parseVarId = function(decl, kind) { decl.id = this.parseBindingAtom(kind); this.checkLVal(decl.id, kind, false) }; pp$1.parseFunction = function(node, isStatement, allowExpressionBody, isAsync) { this.initFunction(node); if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) { node.generator = this.eat(types.star) } if (this.options.ecmaVersion >= 8) { node.async = !!isAsync } if (isStatement) { node.id = isStatement === "nullableID" && this.type !== types.name ? null : this.parseIdent(); if (node.id) { this.checkLVal(node.id, "var") } } var oldInGen = this.inGenerator, oldInAsync = this.inAsync, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldInFunc = this.inFunction; this.inGenerator = node.generator; this.inAsync = node.async; this.yieldPos = 0; this.awaitPos = 0; this.inFunction = true; this.enterFunctionScope(); if (!isStatement) { node.id = this.type === types.name ? this.parseIdent() : null } this.parseFunctionParams(node); this.parseFunctionBody(node, allowExpressionBody); this.inGenerator = oldInGen; this.inAsync = oldInAsync; this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; this.inFunction = oldInFunc; return this.finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression") }; pp$1.parseFunctionParams = function(node) { this.expect(types.parenL); node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8); this.checkYieldAwaitInDefaultParams() }; pp$1.parseClass = function(node, isStatement) { var this$1 = this; this.next(); this.parseClassId(node, isStatement); this.parseClassSuper(node); var classBody = this.startNode(); var hadConstructor = false; classBody.body = []; this.expect(types.braceL); while (!this.eat(types.braceR)) { var member = this$1.parseClassMember(classBody); if (member && member.type === "MethodDefinition" && member.kind === "constructor") { if (hadConstructor) { this$1.raise(member.start, "Duplicate constructor in the same class") } hadConstructor = true } } node.body = this.finishNode(classBody, "ClassBody"); return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression") }; pp$1.parseClassMember = function(classBody) { var this$1 = this; if (this.eat(types.semi)) { return null } var method = this.startNode(); var tryContextual = function(k, noLineBreak) { if (noLineBreak === void 0) noLineBreak = false; var start = this$1.start, startLoc = this$1.startLoc; if (!this$1.eatContextual(k)) { return false } if (this$1.type !== types.parenL && (!noLineBreak || !this$1.canInsertSemicolon())) { return true } if (method.key) { this$1.unexpected() } method.computed = false; method.key = this$1.startNodeAt(start, startLoc); method.key.name = k; this$1.finishNode(method.key, "Identifier"); return false }; method.kind = "method"; method.static = tryContextual("static"); var isGenerator = this.eat(types.star); var isAsync = false; if (!isGenerator) { if (this.options.ecmaVersion >= 8 && tryContextual("async", true)) { isAsync = true; isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star) } else if (tryContextual("get")) { method.kind = "get" } else if (tryContextual("set")) { method.kind = "set" } } if (!method.key) { this.parsePropertyName(method) } var key = method.key; if (!method.computed && !method.static && (key.type === "Identifier" && key.name === "constructor" || key.type === "Literal" && key.value === "constructor")) { if (method.kind !== "method") { this.raise(key.start, "Constructor can't have get/set modifier") } if (isGenerator) { this.raise(key.start, "Constructor can't be a generator") } if (isAsync) { this.raise(key.start, "Constructor can't be an async method") } method.kind = "constructor" } else if (method.static && key.type === "Identifier" && key.name === "prototype") { this.raise(key.start, "Classes may not have a static property named prototype") } this.parseClassMethod(classBody, method, isGenerator, isAsync); if (method.kind === "get" && method.value.params.length !== 0) { this.raiseRecoverable(method.value.start, "getter should have no params") } if (method.kind === "set" && method.value.params.length !== 1) { this.raiseRecoverable(method.value.start, "setter should have exactly one param") } if (method.kind === "set" && method.value.params[0].type === "RestElement") { this.raiseRecoverable(method.value.params[0].start, "Setter cannot use rest params") } return method }; pp$1.parseClassMethod = function(classBody, method, isGenerator, isAsync) { method.value = this.parseMethod(isGenerator, isAsync); classBody.body.push(this.finishNode(method, "MethodDefinition")) }; pp$1.parseClassId = function(node, isStatement) { node.id = this.type === types.name ? this.parseIdent() : isStatement === true ? this.unexpected() : null }; pp$1.parseClassSuper = function(node) { node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null }; pp$1.parseExport = function(node, exports) { var this$1 = this; this.next(); if (this.eat(types.star)) { this.expectContextual("from"); if (this.type !== types.string) { this.unexpected() } node.source = this.parseExprAtom(); this.semicolon(); return this.finishNode(node, "ExportAllDeclaration") } if (this.eat(types._default)) { this.checkExport(exports, "default", this.lastTokStart); var isAsync; if (this.type === types._function || (isAsync = this.isAsyncFunction())) { var fNode = this.startNode(); this.next(); if (isAsync) { this.next() } node.declaration = this.parseFunction(fNode, "nullableID", false, isAsync) } else if (this.type === types._class) { var cNode = this.startNode(); node.declaration = this.parseClass(cNode, "nullableID") } else { node.declaration = this.parseMaybeAssign(); this.semicolon() } return this.finishNode(node, "ExportDefaultDeclaration") } if (this.shouldParseExportStatement()) { node.declaration = this.parseStatement(true); if (node.declaration.type === "VariableDeclaration") { this.checkVariableExport(exports, node.declaration.declarations) } else { this.checkExport(exports, node.declaration.id.name, node.declaration.id.start) } node.specifiers = []; node.source = null } else { node.declaration = null; node.specifiers = this.parseExportSpecifiers(exports); if (this.eatContextual("from")) { if (this.type !== types.string) { this.unexpected() } node.source = this.parseExprAtom() } else { for (var i = 0, list = node.specifiers; i < list.length; i += 1) { var spec = list[i]; this$1.checkUnreserved(spec.local) } node.source = null } this.semicolon() } return this.finishNode(node, "ExportNamedDeclaration") }; pp$1.checkExport = function(exports, name, pos) { if (!exports) { return } if (has(exports, name)) { this.raiseRecoverable(pos, "Duplicate export '" + name + "'") } exports[name] = true }; pp$1.checkPatternExport = function(exports, pat) { var this$1 = this; var type = pat.type; if (type === "Identifier") { this.checkExport(exports, pat.name, pat.start) } else if (type === "ObjectPattern") { for (var i = 0, list = pat.properties; i < list.length; i += 1) { var prop = list[i]; this$1.checkPatternExport(exports, prop) } } else if (type === "ArrayPattern") { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) { var elt = list$1[i$1]; if (elt) { this$1.checkPatternExport(exports, elt) } } } else if (type === "Property") { this.checkPatternExport(exports, pat.value) } else if (type === "AssignmentPattern") { this.checkPatternExport(exports, pat.left) } else if (type === "RestElement") { this.checkPatternExport(exports, pat.argument) } else if (type === "ParenthesizedExpression") { this.checkPatternExport(exports, pat.expression) } }; pp$1.checkVariableExport = function(exports, decls) { var this$1 = this; if (!exports) { return } for (var i = 0, list = decls; i < list.length; i += 1) { var decl = list[i]; this$1.checkPatternExport(exports, decl.id) } }; pp$1.shouldParseExportStatement = function() { return this.type.keyword === "var" || this.type.keyword === "const" || this.type.keyword === "class" || this.type.keyword === "function" || this.isLet() || this.isAsyncFunction() }; pp$1.parseExportSpecifiers = function(exports) { var this$1 = this; var nodes = [], first = true; this.expect(types.braceL); while (!this.eat(types.braceR)) { if (!first) { this$1.expect(types.comma); if (this$1.afterTrailingComma(types.braceR)) { break } } else { first = false } var node = this$1.startNode(); node.local = this$1.parseIdent(true); node.exported = this$1.eatContextual("as") ? this$1.parseIdent(true) : node.local; this$1.checkExport(exports, node.exported.name, node.exported.start); nodes.push(this$1.finishNode(node, "ExportSpecifier")) } return nodes }; pp$1.parseImport = function(node) { this.next(); if (this.type === types.string) { node.specifiers = empty; node.source = this.parseExprAtom() } else { node.specifiers = this.parseImportSpecifiers(); this.expectContextual("from"); node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected() } this.semicolon(); return this.finishNode(node, "ImportDeclaration") }; pp$1.parseImportSpecifiers = function() { var this$1 = this; var nodes = [], first = true; if (this.type === types.name) { var node = this.startNode(); node.local = this.parseIdent(); this.checkLVal(node.local, "let"); nodes.push(this.finishNode(node, "ImportDefaultSpecifier")); if (!this.eat(types.comma)) { return nodes } } if (this.type === types.star) { var node$1 = this.startNode(); this.next(); this.expectContextual("as"); node$1.local = this.parseIdent(); this.checkLVal(node$1.local, "let"); nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier")); return nodes } this.expect(types.braceL); while (!this.eat(types.braceR)) { if (!first) { this$1.expect(types.comma); if (this$1.afterTrailingComma(types.braceR)) { break } } else { first = false } var node$2 = this$1.startNode(); node$2.imported = this$1.parseIdent(true); if (this$1.eatContextual("as")) { node$2.local = this$1.parseIdent() } else { this$1.checkUnreserved(node$2.imported); node$2.local = node$2.imported } this$1.checkLVal(node$2.local, "let"); nodes.push(this$1.finishNode(node$2, "ImportSpecifier")) } return nodes }; pp$1.adaptDirectivePrologue = function(statements) { for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) { statements[i].directive = statements[i].expression.raw.slice(1, -1) } }; pp$1.isDirectiveCandidate = function(statement) { return statement.type === "ExpressionStatement" && statement.expression.type === "Literal" && typeof statement.expression.value === "string" && (this.input[statement.start] === '"' || this.input[statement.start] === "'") }; var pp$2 = Parser.prototype; pp$2.toAssignable = function(node, isBinding, refDestructuringErrors) { var this$1 = this; if (this.options.ecmaVersion >= 6 && node) { switch (node.type) { case "Identifier": if (this.inAsync && node.name === "await") { this.raise(node.start, "Can not use 'await' as identifier inside an async function") } break; case "ObjectPattern": case "ArrayPattern": case "RestElement": break; case "ObjectExpression": node.type = "ObjectPattern"; if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true) } for (var i = 0, list = node.properties; i < list.length; i += 1) { var prop = list[i]; this$1.toAssignable(prop, isBinding); if (prop.type === "RestElement" && (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")) { this$1.raise(prop.argument.start, "Unexpected token") } } break; case "Property": if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter") } this.toAssignable(node.value, isBinding); break; case "ArrayExpression": node.type = "ArrayPattern"; if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true) } this.toAssignableList(node.elements, isBinding); break; case "SpreadElement": node.type = "RestElement"; this.toAssignable(node.argument, isBinding); if (node.argument.type === "AssignmentPattern") { this.raise(node.argument.start, "Rest elements cannot have a default value") } break; case "AssignmentExpression": if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value.") } node.type = "AssignmentPattern"; delete node.operator; this.toAssignable(node.left, isBinding); case "AssignmentPattern": break; case "ParenthesizedExpression": this.toAssignable(node.expression, isBinding); break; case "MemberExpression": if (!isBinding) { break } default: this.raise(node.start, "Assigning to rvalue") } } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true) } return node }; pp$2.toAssignableList = function(exprList, isBinding) { var this$1 = this; var end = exprList.length; for (var i = 0; i < end; i++) { var elt = exprList[i]; if (elt) { this$1.toAssignable(elt, isBinding) } } if (end) { var last = exprList[end - 1]; if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") { this.unexpected(last.argument.start) } } return exprList }; pp$2.parseSpread = function(refDestructuringErrors) { var node = this.startNode(); this.next(); node.argument = this.parseMaybeAssign(false, refDestructuringErrors); return this.finishNode(node, "SpreadElement") }; pp$2.parseRestBinding = function() { var node = this.startNode(); this.next(); if (this.options.ecmaVersion === 6 && this.type !== types.name) { this.unexpected() } node.argument = this.parseBindingAtom(); return this.finishNode(node, "RestElement") }; pp$2.parseBindingAtom = function() { if (this.options.ecmaVersion >= 6) { switch (this.type) { case types.bracketL: var node = this.startNode(); this.next(); node.elements = this.parseBindingList(types.bracketR, true, true); return this.finishNode(node, "ArrayPattern"); case types.braceL: return this.parseObj(true) } } return this.parseIdent() }; pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma) { var this$1 = this; var elts = [], first = true; while (!this.eat(close)) { if (first) { first = false } else { this$1.expect(types.comma) } if (allowEmpty && this$1.type === types.comma) { elts.push(null) } else if (allowTrailingComma && this$1.afterTrailingComma(close)) { break } else if (this$1.type === types.ellipsis) { var rest = this$1.parseRestBinding(); this$1.parseBindingListItem(rest); elts.push(rest); if (this$1.type === types.comma) { this$1.raise(this$1.start, "Comma is not permitted after the rest element") } this$1.expect(close); break } else { var elem = this$1.parseMaybeDefault(this$1.start, this$1.startLoc); this$1.parseBindingListItem(elem); elts.push(elem) } } return elts }; pp$2.parseBindingListItem = function(param) { return param }; pp$2.parseMaybeDefault = function(startPos, startLoc, left) { left = left || this.parseBindingAtom(); if (this.options.ecmaVersion < 6 || !this.eat(types.eq)) { return left } var node = this.startNodeAt(startPos, startLoc); node.left = left; node.right = this.parseMaybeAssign(); return this.finishNode(node, "AssignmentPattern") }; pp$2.checkLVal = function(expr, bindingType, checkClashes) { var this$1 = this; switch (expr.type) { case "Identifier": if (this.strict && this.reservedWordsStrictBind.test(expr.name)) { this.raiseRecoverable(expr.start, (bindingType ? "Binding " : "Assigning to ") + expr.name + " in strict mode") } if (checkClashes) { if (has(checkClashes, expr.name)) { this.raiseRecoverable(expr.start, "Argument name clash") } checkClashes[expr.name] = true } if (bindingType && bindingType !== "none") { if (bindingType === "var" && !this.canDeclareVarName(expr.name) || bindingType !== "var" && !this.canDeclareLexicalName(expr.name)) { this.raiseRecoverable(expr.start, "Identifier '" + expr.name + "' has already been declared") } if (bindingType === "var") { this.declareVarName(expr.name) } else { this.declareLexicalName(expr.name) } } break; case "MemberExpression": if (bindingType) { this.raiseRecoverable(expr.start, "Binding member expression") } break; case "ObjectPattern": for (var i = 0, list = expr.properties; i < list.length; i += 1) { var prop = list[i]; this$1.checkLVal(prop, bindingType, checkClashes) } break; case "Property": this.checkLVal(expr.value, bindingType, checkClashes); break; case "ArrayPattern": for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) { var elem = list$1[i$1]; if (elem) { this$1.checkLVal(elem, bindingType, checkClashes) } } break; case "AssignmentPattern": this.checkLVal(expr.left, bindingType, checkClashes); break; case "RestElement": this.checkLVal(expr.argument, bindingType, checkClashes); break; case "ParenthesizedExpression": this.checkLVal(expr.expression, bindingType, checkClashes); break; default: this.raise(expr.start, (bindingType ? "Binding" : "Assigning to") + " rvalue") } }; var pp$3 = Parser.prototype; pp$3.checkPropClash = function(prop, propHash, refDestructuringErrors) { if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement") { return } if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) { return } var key = prop.key; var name; switch (key.type) { case "Identifier": name = key.name; break; case "Literal": name = String(key.value); break; default: return } var kind = prop.kind; if (this.options.ecmaVersion >= 6) { if (name === "__proto__" && kind === "init") { if (propHash.proto) { if (refDestructuringErrors && refDestructuringErrors.doubleProto < 0) { refDestructuringErrors.doubleProto = key.start } else { this.raiseRecoverable(key.start, "Redefinition of __proto__ property") } } propHash.proto = true } return } name = "$" + name; var other = propHash[name]; if (other) { var redefinition; if (kind === "init") { redefinition = this.strict && other.init || other.get || other.set } else { redefinition = other.init || other[kind] } if (redefinition) { this.raiseRecoverable(key.start, "Redefinition of property") } } else { other = propHash[name] = { init: false, get: false, set: false } } other[kind] = true }; pp$3.parseExpression = function(noIn, refDestructuringErrors) { var this$1 = this; var startPos = this.start, startLoc = this.startLoc; var expr = this.parseMaybeAssign(noIn, refDestructuringErrors); if (this.type === types.comma) { var node = this.startNodeAt(startPos, startLoc); node.expressions = [expr]; while (this.eat(types.comma)) { node.expressions.push(this$1.parseMaybeAssign(noIn, refDestructuringErrors)) } return this.finishNode(node, "SequenceExpression") } return expr }; pp$3.parseMaybeAssign = function(noIn, refDestructuringErrors, afterLeftParse) { if (this.inGenerator && this.isContextual("yield")) { return this.parseYield() } var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1; if (refDestructuringErrors) { oldParenAssign = refDestructuringErrors.parenthesizedAssign; oldTrailingComma = refDestructuringErrors.trailingComma; refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1 } else { refDestructuringErrors = new DestructuringErrors; ownDestructuringErrors = true } var startPos = this.start, startLoc = this.startLoc; if (this.type === types.parenL || this.type === types.name) { this.potentialArrowAt = this.start } var left = this.parseMaybeConditional(noIn, refDestructuringErrors); if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc) } if (this.type.isAssign) { var node = this.startNodeAt(startPos, startLoc); node.operator = this.value; node.left = this.type === types.eq ? this.toAssignable(left, false, refDestructuringErrors) : left; if (!ownDestructuringErrors) { DestructuringErrors.call(refDestructuringErrors) } refDestructuringErrors.shorthandAssign = -1; this.checkLVal(left); this.next(); node.right = this.parseMaybeAssign(noIn); return this.finishNode(node, "AssignmentExpression") } else { if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true) } } if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign } if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma } return left }; pp$3.parseMaybeConditional = function(noIn, refDestructuringErrors) { var startPos = this.start, startLoc = this.startLoc; var expr = this.parseExprOps(noIn, refDestructuringErrors); if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } if (this.eat(types.question)) { var node = this.startNodeAt(startPos, startLoc); node.test = expr; node.consequent = this.parseMaybeAssign(); this.expect(types.colon); node.alternate = this.parseMaybeAssign(noIn); return this.finishNode(node, "ConditionalExpression") } return expr }; pp$3.parseExprOps = function(noIn, refDestructuringErrors) { var startPos = this.start, startLoc = this.startLoc; var expr = this.parseMaybeUnary(refDestructuringErrors, false); if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, noIn) }; pp$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, noIn) { var prec = this.type.binop; if (prec != null && (!noIn || this.type !== types._in)) { if (prec > minPrec) { var logical = this.type === types.logicalOR || this.type === types.logicalAND; var op = this.value; this.next(); var startPos = this.start, startLoc = this.startLoc; var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, noIn); var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical); return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn) } } return left }; pp$3.buildBinary = function(startPos, startLoc, left, right, op, logical) { var node = this.startNodeAt(startPos, startLoc); node.left = left; node.operator = op; node.right = right; return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression") }; pp$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary) { var this$1 = this; var startPos = this.start, startLoc = this.startLoc, expr; if (this.isContextual("await") && (this.inAsync || !this.inFunction && this.options.allowAwaitOutsideFunction)) { expr = this.parseAwait(); sawUnary = true } else if (this.type.prefix) { var node = this.startNode(), update = this.type === types.incDec; node.operator = this.value; node.prefix = true; this.next(); node.argument = this.parseMaybeUnary(null, true); this.checkExpressionErrors(refDestructuringErrors, true); if (update) { this.checkLVal(node.argument) } else if (this.strict && node.operator === "delete" && node.argument.type === "Identifier") { this.raiseRecoverable(node.start, "Deleting local variable in strict mode") } else { sawUnary = true } expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression") } else { expr = this.parseExprSubscripts(refDestructuringErrors); if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } while (this.type.postfix && !this.canInsertSemicolon()) { var node$1 = this$1.startNodeAt(startPos, startLoc); node$1.operator = this$1.value; node$1.prefix = false; node$1.argument = expr; this$1.checkLVal(expr); this$1.next(); expr = this$1.finishNode(node$1, "UpdateExpression") } } if (!sawUnary && this.eat(types.starstar)) { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false) } else { return expr } }; pp$3.parseExprSubscripts = function(refDestructuringErrors) { var startPos = this.start, startLoc = this.startLoc; var expr = this.parseExprAtom(refDestructuringErrors); var skipArrowSubscripts = expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")"; if (this.checkExpressionErrors(refDestructuringErrors) || skipArrowSubscripts) { return expr } var result = this.parseSubscripts(expr, startPos, startLoc); if (refDestructuringErrors && result.type === "MemberExpression") { if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1 } if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1 } } return result }; pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) { var this$1 = this; var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" && this.lastTokEnd === base.end && !this.canInsertSemicolon() && this.input.slice(base.start, base.end) === "async"; for (var computed = void 0;;) { if ((computed = this$1.eat(types.bracketL)) || this$1.eat(types.dot)) { var node = this$1.startNodeAt(startPos, startLoc); node.object = base; node.property = computed ? this$1.parseExpression() : this$1.parseIdent(true); node.computed = !!computed; if (computed) { this$1.expect(types.bracketR) } base = this$1.finishNode(node, "MemberExpression") } else if (!noCalls && this$1.eat(types.parenL)) { var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this$1.yieldPos, oldAwaitPos = this$1.awaitPos; this$1.yieldPos = 0; this$1.awaitPos = 0; var exprList = this$1.parseExprList(types.parenR, this$1.options.ecmaVersion >= 8, false, refDestructuringErrors); if (maybeAsyncArrow && !this$1.canInsertSemicolon() && this$1.eat(types.arrow)) { this$1.checkPatternErrors(refDestructuringErrors, false); this$1.checkYieldAwaitInDefaultParams(); this$1.yieldPos = oldYieldPos; this$1.awaitPos = oldAwaitPos; return this$1.parseArrowExpression(this$1.startNodeAt(startPos, startLoc), exprList, true) } this$1.checkExpressionErrors(refDestructuringErrors, true); this$1.yieldPos = oldYieldPos || this$1.yieldPos; this$1.awaitPos = oldAwaitPos || this$1.awaitPos; var node$1 = this$1.startNodeAt(startPos, startLoc); node$1.callee = base; node$1.arguments = exprList; base = this$1.finishNode(node$1, "CallExpression") } else if (this$1.type === types.backQuote) { var node$2 = this$1.startNodeAt(startPos, startLoc); node$2.tag = base; node$2.quasi = this$1.parseTemplate({ isTagged: true }); base = this$1.finishNode(node$2, "TaggedTemplateExpression") } else { return base } } }; pp$3.parseExprAtom = function(refDestructuringErrors) { var node, canBeArrow = this.potentialArrowAt === this.start; switch (this.type) { case types._super: if (!this.inFunction) { this.raise(this.start, "'super' outside of function or class") } node = this.startNode(); this.next(); if (this.type !== types.dot && this.type !== types.bracketL && this.type !== types.parenL) { this.unexpected() } return this.finishNode(node, "Super"); case types._this: node = this.startNode(); this.next(); return this.finishNode(node, "ThisExpression"); case types.name: var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc; var id = this.parseIdent(this.type !== types.name); if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types._function)) { return this.parseFunction(this.startNodeAt(startPos, startLoc), false, false, true) } if (canBeArrow && !this.canInsertSemicolon()) { if (this.eat(types.arrow)) { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false) } if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types.name && !containsEsc) { id = this.parseIdent(); if (this.canInsertSemicolon() || !this.eat(types.arrow)) { this.unexpected() } return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true) } } return id; case types.regexp: var value = this.value; node = this.parseLiteral(value.value); node.regex = { pattern: value.pattern, flags: value.flags }; return node; case types.num: case types.string: return this.parseLiteral(this.value); case types._null: case types._true: case types._false: node = this.startNode(); node.value = this.type === types._null ? null : this.type === types._true; node.raw = this.type.keyword; this.next(); return this.finishNode(node, "Literal"); case types.parenL: var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow); if (refDestructuringErrors) { if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr)) { refDestructuringErrors.parenthesizedAssign = start } if (refDestructuringErrors.parenthesizedBind < 0) { refDestructuringErrors.parenthesizedBind = start } } return expr; case types.bracketL: node = this.startNode(); this.next(); node.elements = this.parseExprList(types.bracketR, true, true, refDestructuringErrors); return this.finishNode(node, "ArrayExpression"); case types.braceL: return this.parseObj(false, refDestructuringErrors); case types._function: node = this.startNode(); this.next(); return this.parseFunction(node, false); case types._class: return this.parseClass(this.startNode(), false); case types._new: return this.parseNew(); case types.backQuote: return this.parseTemplate(); default: this.unexpected() } }; pp$3.parseLiteral = function(value) { var node = this.startNode(); node.value = value; node.raw = this.input.slice(this.start, this.end); this.next(); return this.finishNode(node, "Literal") }; pp$3.parseParenExpression = function() { this.expect(types.parenL); var val = this.parseExpression(); this.expect(types.parenR); return val }; pp$3.parseParenAndDistinguishExpression = function(canBeArrow) { var this$1 = this; var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8; if (this.options.ecmaVersion >= 6) { this.next(); var innerStartPos = this.start, innerStartLoc = this.startLoc; var exprList = [], first = true, lastIsComma = false; var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart; this.yieldPos = 0; this.awaitPos = 0; while (this.type !== types.parenR) { first ? first = false : this$1.expect(types.comma); if (allowTrailingComma && this$1.afterTrailingComma(types.parenR, true)) { lastIsComma = true; break } else if (this$1.type === types.ellipsis) { spreadStart = this$1.start; exprList.push(this$1.parseParenItem(this$1.parseRestBinding())); if (this$1.type === types.comma) { this$1.raise(this$1.start, "Comma is not permitted after the rest element") } break } else { exprList.push(this$1.parseMaybeAssign(false, refDestructuringErrors, this$1.parseParenItem)) } } var innerEndPos = this.start, innerEndLoc = this.startLoc; this.expect(types.parenR); if (canBeArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) { this.checkPatternErrors(refDestructuringErrors, false); this.checkYieldAwaitInDefaultParams(); this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; return this.parseParenArrowList(startPos, startLoc, exprList) } if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart) } if (spreadStart) { this.unexpected(spreadStart) } this.checkExpressionErrors(refDestructuringErrors, true); this.yieldPos = oldYieldPos || this.yieldPos; this.awaitPos = oldAwaitPos || this.awaitPos; if (exprList.length > 1) { val = this.startNodeAt(innerStartPos, innerStartLoc); val.expressions = exprList; this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc) } else { val = exprList[0] } } else { val = this.parseParenExpression() } if (this.options.preserveParens) { var par = this.startNodeAt(startPos, startLoc); par.expression = val; return this.finishNode(par, "ParenthesizedExpression") } else { return val } }; pp$3.parseParenItem = function(item) { return item }; pp$3.parseParenArrowList = function(startPos, startLoc, exprList) { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList) }; var empty$1 = []; pp$3.parseNew = function() { var node = this.startNode(); var meta = this.parseIdent(true); if (this.options.ecmaVersion >= 6 && this.eat(types.dot)) { node.meta = meta; var containsEsc = this.containsEsc; node.property = this.parseIdent(true); if (node.property.name !== "target" || containsEsc) { this.raiseRecoverable(node.property.start, "The only valid meta property for new is new.target") } if (!this.inFunction) { this.raiseRecoverable(node.start, "new.target can only be used in functions") } return this.finishNode(node, "MetaProperty") } var startPos = this.start, startLoc = this.startLoc; node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true); if (this.eat(types.parenL)) { node.arguments = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false) } else { node.arguments = empty$1 } return this.finishNode(node, "NewExpression") }; pp$3.parseTemplateElement = function(ref) { var isTagged = ref.isTagged; var elem = this.startNode(); if (this.type === types.invalidTemplate) { if (!isTagged) { this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal") } elem.value = { raw: this.value, cooked: null } } else { elem.value = { raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"), cooked: this.value } } this.next(); elem.tail = this.type === types.backQuote; return this.finishNode(elem, "TemplateElement") }; pp$3.parseTemplate = function(ref) { var this$1 = this; if (ref === void 0) ref = {}; var isTagged = ref.isTagged; if (isTagged === void 0) isTagged = false; var node = this.startNode(); this.next(); node.expressions = []; var curElt = this.parseTemplateElement({ isTagged: isTagged }); node.quasis = [curElt]; while (!curElt.tail) { this$1.expect(types.dollarBraceL); node.expressions.push(this$1.parseExpression()); this$1.expect(types.braceR); node.quasis.push(curElt = this$1.parseTemplateElement({ isTagged: isTagged })) } this.next(); return this.finishNode(node, "TemplateLiteral") }; pp$3.isAsyncProp = function(prop) { return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && (this.type === types.name || this.type === types.num || this.type === types.string || this.type === types.bracketL || this.type.keyword || this.options.ecmaVersion >= 9 && this.type === types.star) && !lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }; pp$3.parseObj = function(isPattern, refDestructuringErrors) { var this$1 = this; var node = this.startNode(), first = true, propHash = {}; node.properties = []; this.next(); while (!this.eat(types.braceR)) { if (!first) { this$1.expect(types.comma); if (this$1.afterTrailingComma(types.braceR)) { break } } else { first = false } var prop = this$1.parseProperty(isPattern, refDestructuringErrors); if (!isPattern) { this$1.checkPropClash(prop, propHash, refDestructuringErrors) } node.properties.push(prop) } return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression") }; pp$3.parseProperty = function(isPattern, refDestructuringErrors) { var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc; if (this.options.ecmaVersion >= 9 && this.eat(types.ellipsis)) { if (isPattern) { prop.argument = this.parseIdent(false); if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element") } return this.finishNode(prop, "RestElement") } if (this.type === types.parenL && refDestructuringErrors) { if (refDestructuringErrors.parenthesizedAssign < 0) { refDestructuringErrors.parenthesizedAssign = this.start } if (refDestructuringErrors.parenthesizedBind < 0) { refDestructuringErrors.parenthesizedBind = this.start } } prop.argument = this.parseMaybeAssign(false, refDestructuringErrors); if (this.type === types.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) { refDestructuringErrors.trailingComma = this.start } return this.finishNode(prop, "SpreadElement") } if (this.options.ecmaVersion >= 6) { prop.method = false; prop.shorthand = false; if (isPattern || refDestructuringErrors) { startPos = this.start; startLoc = this.startLoc } if (!isPattern) { isGenerator = this.eat(types.star) } } var containsEsc = this.containsEsc; this.parsePropertyName(prop); if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) { isAsync = true; isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star); this.parsePropertyName(prop, refDestructuringErrors) } else { isAsync = false } this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc); return this.finishNode(prop, "Property") }; pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) { if ((isGenerator || isAsync) && this.type === types.colon) { this.unexpected() } if (this.eat(types.colon)) { prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors); prop.kind = "init" } else if (this.options.ecmaVersion >= 6 && this.type === types.parenL) { if (isPattern) { this.unexpected() } prop.kind = "init"; prop.method = true; prop.value = this.parseMethod(isGenerator, isAsync) } else if (!isPattern && !containsEsc && this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && (prop.key.name === "get" || prop.key.name === "set") && (this.type !== types.comma && this.type !== types.braceR)) { if (isGenerator || isAsync) { this.unexpected() } prop.kind = prop.key.name; this.parsePropertyName(prop); prop.value = this.parseMethod(false); var paramCount = prop.kind === "get" ? 0 : 1; if (prop.value.params.length !== paramCount) { var start = prop.value.start; if (prop.kind === "get") { this.raiseRecoverable(start, "getter should have no params") } else { this.raiseRecoverable(start, "setter should have exactly one param") } } else { if (prop.kind === "set" && prop.value.params[0].type === "RestElement") { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params") } } } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") { this.checkUnreserved(prop.key); prop.kind = "init"; if (isPattern) { prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key) } else if (this.type === types.eq && refDestructuringErrors) { if (refDestructuringErrors.shorthandAssign < 0) { refDestructuringErrors.shorthandAssign = this.start } prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key) } else { prop.value = prop.key } prop.shorthand = true } else { this.unexpected() } }; pp$3.parsePropertyName = function(prop) { if (this.options.ecmaVersion >= 6) { if (this.eat(types.bracketL)) { prop.computed = true; prop.key = this.parseMaybeAssign(); this.expect(types.bracketR); return prop.key } else { prop.computed = false } } return prop.key = this.type === types.num || this.type === types.string ? this.parseExprAtom() : this.parseIdent(true) }; pp$3.initFunction = function(node) { node.id = null; if (this.options.ecmaVersion >= 6) { node.generator = false; node.expression = false } if (this.options.ecmaVersion >= 8) { node.async = false } }; pp$3.parseMethod = function(isGenerator, isAsync) { var node = this.startNode(), oldInGen = this.inGenerator, oldInAsync = this.inAsync, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldInFunc = this.inFunction; this.initFunction(node); if (this.options.ecmaVersion >= 6) { node.generator = isGenerator } if (this.options.ecmaVersion >= 8) { node.async = !!isAsync } this.inGenerator = node.generator; this.inAsync = node.async; this.yieldPos = 0; this.awaitPos = 0; this.inFunction = true; this.enterFunctionScope(); this.expect(types.parenL); node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8); this.checkYieldAwaitInDefaultParams(); this.parseFunctionBody(node, false); this.inGenerator = oldInGen; this.inAsync = oldInAsync; this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; this.inFunction = oldInFunc; return this.finishNode(node, "FunctionExpression") }; pp$3.parseArrowExpression = function(node, params, isAsync) { var oldInGen = this.inGenerator, oldInAsync = this.inAsync, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldInFunc = this.inFunction; this.enterFunctionScope(); this.initFunction(node); if (this.options.ecmaVersion >= 8) { node.async = !!isAsync } this.inGenerator = false; this.inAsync = node.async; this.yieldPos = 0; this.awaitPos = 0; this.inFunction = true; node.params = this.toAssignableList(params, true); this.parseFunctionBody(node, true); this.inGenerator = oldInGen; this.inAsync = oldInAsync; this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; this.inFunction = oldInFunc; return this.finishNode(node, "ArrowFunctionExpression") }; pp$3.parseFunctionBody = function(node, isArrowFunction) { var isExpression = isArrowFunction && this.type !== types.braceL; var oldStrict = this.strict, useStrict = false; if (isExpression) { node.body = this.parseMaybeAssign(); node.expression = true; this.checkParams(node, false) } else { var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params); if (!oldStrict || nonSimple) { useStrict = this.strictDirective(this.end); if (useStrict && nonSimple) { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list") } } var oldLabels = this.labels; this.labels = []; if (useStrict) { this.strict = true } this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && this.isSimpleParamList(node.params)); node.body = this.parseBlock(false); node.expression = false; this.adaptDirectivePrologue(node.body.body); this.labels = oldLabels } this.exitFunctionScope(); if (this.strict && node.id) { this.checkLVal(node.id, "none") } this.strict = oldStrict }; pp$3.isSimpleParamList = function(params) { for (var i = 0, list = params; i < list.length; i += 1) { var param = list[i]; if (param.type !== "Identifier") { return false } } return true }; pp$3.checkParams = function(node, allowDuplicates) { var this$1 = this; var nameHash = {}; for (var i = 0, list = node.params; i < list.length; i += 1) { var param = list[i]; this$1.checkLVal(param, "var", allowDuplicates ? null : nameHash) } }; pp$3.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) { var this$1 = this; var elts = [], first = true; while (!this.eat(close)) { if (!first) { this$1.expect(types.comma); if (allowTrailingComma && this$1.afterTrailingComma(close)) { break } } else { first = false } var elt = void 0; if (allowEmpty && this$1.type === types.comma) { elt = null } else if (this$1.type === types.ellipsis) { elt = this$1.parseSpread(refDestructuringErrors); if (refDestructuringErrors && this$1.type === types.comma && refDestructuringErrors.trailingComma < 0) { refDestructuringErrors.trailingComma = this$1.start } } else { elt = this$1.parseMaybeAssign(false, refDestructuringErrors) } elts.push(elt) } return elts }; pp$3.checkUnreserved = function(ref) { var start = ref.start; var end = ref.end; var name = ref.name; if (this.inGenerator && name === "yield") { this.raiseRecoverable(start, "Can not use 'yield' as identifier inside a generator") } if (this.inAsync && name === "await") { this.raiseRecoverable(start, "Can not use 'await' as identifier inside an async function") } if (this.isKeyword(name)) { this.raise(start, "Unexpected keyword '" + name + "'") } if (this.options.ecmaVersion < 6 && this.input.slice(start, end).indexOf("\\") !== -1) { return } var re = this.strict ? this.reservedWordsStrict : this.reservedWords; if (re.test(name)) { if (!this.inAsync && name === "await") { this.raiseRecoverable(start, "Can not use keyword 'await' outside an async function") } this.raiseRecoverable(start, "The keyword '" + name + "' is reserved") } }; pp$3.parseIdent = function(liberal, isBinding) { var node = this.startNode(); if (liberal && this.options.allowReserved === "never") { liberal = false } if (this.type === types.name) { node.name = this.value } else if (this.type.keyword) { node.name = this.type.keyword; if ((node.name === "class" || node.name === "function") && (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) { this.context.pop() } } else { this.unexpected() } this.next(); this.finishNode(node, "Identifier"); if (!liberal) { this.checkUnreserved(node) } return node }; pp$3.parseYield = function() { if (!this.yieldPos) { this.yieldPos = this.start } var node = this.startNode(); this.next(); if (this.type === types.semi || this.canInsertSemicolon() || this.type !== types.star && !this.type.startsExpr) { node.delegate = false; node.argument = null } else { node.delegate = this.eat(types.star); node.argument = this.parseMaybeAssign() } return this.finishNode(node, "YieldExpression") }; pp$3.parseAwait = function() { if (!this.awaitPos) { this.awaitPos = this.start } var node = this.startNode(); this.next(); node.argument = this.parseMaybeUnary(null, true); return this.finishNode(node, "AwaitExpression") }; var pp$4 = Parser.prototype; pp$4.raise = function(pos, message) { var loc = getLineInfo(this.input, pos); message += " (" + loc.line + ":" + loc.column + ")"; var err = new SyntaxError(message); err.pos = pos; err.loc = loc; err.raisedAt = this.pos; throw err }; pp$4.raiseRecoverable = pp$4.raise; pp$4.curPosition = function() { if (this.options.locations) { return new Position(this.curLine, this.pos - this.lineStart) } }; var pp$5 = Parser.prototype; var assign = Object.assign || function(target) { var sources = [], len = arguments.length - 1; while (len-- > 0) sources[len] = arguments[len + 1]; for (var i = 0, list = sources; i < list.length; i += 1) { var source = list[i]; for (var key in source) { if (has(source, key)) { target[key] = source[key] } } } return target }; pp$5.enterFunctionScope = function() { this.scopeStack.push({ var: {}, lexical: {}, childVar: {}, parentLexical: {} }) }; pp$5.exitFunctionScope = function() { this.scopeStack.pop() }; pp$5.enterLexicalScope = function() { var parentScope = this.scopeStack[this.scopeStack.length - 1]; var childScope = { var: {}, lexical: {}, childVar: {}, parentLexical: {} }; this.scopeStack.push(childScope); assign(childScope.parentLexical, parentScope.lexical, parentScope.parentLexical) }; pp$5.exitLexicalScope = function() { var childScope = this.scopeStack.pop(); var parentScope = this.scopeStack[this.scopeStack.length - 1]; assign(parentScope.childVar, childScope.var, childScope.childVar) }; pp$5.canDeclareVarName = function(name) { var currentScope = this.scopeStack[this.scopeStack.length - 1]; return !has(currentScope.lexical, name) && !has(currentScope.parentLexical, name) }; pp$5.canDeclareLexicalName = function(name) { var currentScope = this.scopeStack[this.scopeStack.length - 1]; return !has(currentScope.lexical, name) && !has(currentScope.var, name) && !has(currentScope.childVar, name) }; pp$5.declareVarName = function(name) { this.scopeStack[this.scopeStack.length - 1].var[name] = true }; pp$5.declareLexicalName = function(name) { this.scopeStack[this.scopeStack.length - 1].lexical[name] = true }; var Node = function Node(parser, pos, loc) { this.type = ""; this.start = pos; this.end = 0; if (parser.options.locations) { this.loc = new SourceLocation(parser, loc) } if (parser.options.directSourceFile) { this.sourceFile = parser.options.directSourceFile } if (parser.options.ranges) { this.range = [pos, 0] } }; var pp$6 = Parser.prototype; pp$6.startNode = function() { return new Node(this, this.start, this.startLoc) }; pp$6.startNodeAt = function(pos, loc) { return new Node(this, pos, loc) }; function finishNodeAt(node, type, pos, loc) { node.type = type; node.end = pos; if (this.options.locations) { node.loc.end = loc } if (this.options.ranges) { node.range[1] = pos } return node } pp$6.finishNode = function(node, type) { return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc) }; pp$6.finishNodeAt = function(node, type, pos, loc) { return finishNodeAt.call(this, node, type, pos, loc) }; var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) { this.token = token; this.isExpr = !!isExpr; this.preserveSpace = !!preserveSpace; this.override = override; this.generator = !!generator }; var types$1 = { b_stat: new TokContext("{", false), b_expr: new TokContext("{", true), b_tmpl: new TokContext("${", false), p_stat: new TokContext("(", false), p_expr: new TokContext("(", true), q_tmpl: new TokContext("`", true, true, function(p) { return p.tryReadTemplateToken() }), f_stat: new TokContext("function", false), f_expr: new TokContext("function", true), f_expr_gen: new TokContext("function", true, false, null, true), f_gen: new TokContext("function", false, false, null, true) }; var pp$7 = Parser.prototype; pp$7.initialContext = function() { return [types$1.b_stat] }; pp$7.braceIsBlock = function(prevType) { var parent = this.curContext(); if (parent === types$1.f_expr || parent === types$1.f_stat) { return true } if (prevType === types.colon && (parent === types$1.b_stat || parent === types$1.b_expr)) { return !parent.isExpr } if (prevType === types._return || prevType === types.name && this.exprAllowed) { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) } if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow) { return true } if (prevType === types.braceL) { return parent === types$1.b_stat } if (prevType === types._var || prevType === types.name) { return false } return !this.exprAllowed }; pp$7.inGeneratorContext = function() { var this$1 = this; for (var i = this.context.length - 1; i >= 1; i--) { var context = this$1.context[i]; if (context.token === "function") { return context.generator } } return false }; pp$7.updateContext = function(prevType) { var update, type = this.type; if (type.keyword && prevType === types.dot) { this.exprAllowed = false } else if (update = type.updateContext) { update.call(this, prevType) } else { this.exprAllowed = type.beforeExpr } }; types.parenR.updateContext = types.braceR.updateContext = function() { if (this.context.length === 1) { this.exprAllowed = true; return } var out = this.context.pop(); if (out === types$1.b_stat && this.curContext().token === "function") { out = this.context.pop() } this.exprAllowed = !out.isExpr }; types.braceL.updateContext = function(prevType) { this.context.push(this.braceIsBlock(prevType) ? types$1.b_stat : types$1.b_expr); this.exprAllowed = true }; types.dollarBraceL.updateContext = function() { this.context.push(types$1.b_tmpl); this.exprAllowed = true }; types.parenL.updateContext = function(prevType) { var statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while; this.context.push(statementParens ? types$1.p_stat : types$1.p_expr); this.exprAllowed = true }; types.incDec.updateContext = function() {}; types._function.updateContext = types._class.updateContext = function(prevType) { if (prevType.beforeExpr && prevType !== types.semi && prevType !== types._else && !((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat)) { this.context.push(types$1.f_expr) } else { this.context.push(types$1.f_stat) } this.exprAllowed = false }; types.backQuote.updateContext = function() { if (this.curContext() === types$1.q_tmpl) { this.context.pop() } else { this.context.push(types$1.q_tmpl) } this.exprAllowed = false }; types.star.updateContext = function(prevType) { if (prevType === types._function) { var index = this.context.length - 1; if (this.context[index] === types$1.f_expr) { this.context[index] = types$1.f_expr_gen } else { this.context[index] = types$1.f_gen } } this.exprAllowed = true }; types.name.updateContext = function(prevType) { var allowed = false; if (this.options.ecmaVersion >= 6) { if (this.value === "of" && !this.exprAllowed || this.value === "yield" && this.inGeneratorContext()) { allowed = true } } this.exprAllowed = allowed }; var data = { $LONE: ["ASCII", "ASCII_Hex_Digit", "AHex", "Alphabetic", "Alpha", "Any", "Assigned", "Bidi_Control", "Bidi_C", "Bidi_Mirrored", "Bidi_M", "Case_Ignorable", "CI", "Cased", "Changes_When_Casefolded", "CWCF", "Changes_When_Casemapped", "CWCM", "Changes_When_Lowercased", "CWL", "Changes_When_NFKC_Casefolded", "CWKCF", "Changes_When_Titlecased", "CWT", "Changes_When_Uppercased", "CWU", "Dash", "Default_Ignorable_Code_Point", "DI", "Deprecated", "Dep", "Diacritic", "Dia", "Emoji", "Emoji_Component", "Emoji_Modifier", "Emoji_Modifier_Base", "Emoji_Presentation", "Extender", "Ext", "Grapheme_Base", "Gr_Base", "Grapheme_Extend", "Gr_Ext", "Hex_Digit", "Hex", "IDS_Binary_Operator", "IDSB", "IDS_Trinary_Operator", "IDST", "ID_Continue", "IDC", "ID_Start", "IDS", "Ideographic", "Ideo", "Join_Control", "Join_C", "Logical_Order_Exception", "LOE", "Lowercase", "Lower", "Math", "Noncharacter_Code_Point", "NChar", "Pattern_Syntax", "Pat_Syn", "Pattern_White_Space", "Pat_WS", "Quotation_Mark", "QMark", "Radical", "Regional_Indicator", "RI", "Sentence_Terminal", "STerm", "Soft_Dotted", "SD", "Terminal_Punctuation", "Term", "Unified_Ideograph", "UIdeo", "Uppercase", "Upper", "Variation_Selector", "VS", "White_Space", "space", "XID_Continue", "XIDC", "XID_Start", "XIDS"], General_Category: ["Cased_Letter", "LC", "Close_Punctuation", "Pe", "Connector_Punctuation", "Pc", "Control", "Cc", "cntrl", "Currency_Symbol", "Sc", "Dash_Punctuation", "Pd", "Decimal_Number", "Nd", "digit", "Enclosing_Mark", "Me", "Final_Punctuation", "Pf", "Format", "Cf", "Initial_Punctuation", "Pi", "Letter", "L", "Letter_Number", "Nl", "Line_Separator", "Zl", "Lowercase_Letter", "Ll", "Mark", "M", "Combining_Mark", "Math_Symbol", "Sm", "Modifier_Letter", "Lm", "Modifier_Symbol", "Sk", "Nonspacing_Mark", "Mn", "Number", "N", "Open_Punctuation", "Ps", "Other", "C", "Other_Letter", "Lo", "Other_Number", "No", "Other_Punctuation", "Po", "Other_Symbol", "So", "Paragraph_Separator", "Zp", "Private_Use", "Co", "Punctuation", "P", "punct", "Separator", "Z", "Space_Separator", "Zs", "Spacing_Mark", "Mc", "Surrogate", "Cs", "Symbol", "S", "Titlecase_Letter", "Lt", "Unassigned", "Cn", "Uppercase_Letter", "Lu"], Script: ["Adlam", "Adlm", "Ahom", "Anatolian_Hieroglyphs", "Hluw", "Arabic", "Arab", "Armenian", "Armn", "Avestan", "Avst", "Balinese", "Bali", "Bamum", "Bamu", "Bassa_Vah", "Bass", "Batak", "Batk", "Bengali", "Beng", "Bhaiksuki", "Bhks", "Bopomofo", "Bopo", "Brahmi", "Brah", "Braille", "Brai", "Buginese", "Bugi", "Buhid", "Buhd", "Canadian_Aboriginal", "Cans", "Carian", "Cari", "Caucasian_Albanian", "Aghb", "Chakma", "Cakm", "Cham", "Cherokee", "Cher", "Common", "Zyyy", "Coptic", "Copt", "Qaac", "Cuneiform", "Xsux", "Cypriot", "Cprt", "Cyrillic", "Cyrl", "Deseret", "Dsrt", "Devanagari", "Deva", "Duployan", "Dupl", "Egyptian_Hieroglyphs", "Egyp", "Elbasan", "Elba", "Ethiopic", "Ethi", "Georgian", "Geor", "Glagolitic", "Glag", "Gothic", "Goth", "Grantha", "Gran", "Greek", "Grek", "Gujarati", "Gujr", "Gurmukhi", "Guru", "Han", "Hani", "Hangul", "Hang", "Hanunoo", "Hano", "Hatran", "Hatr", "Hebrew", "Hebr", "Hiragana", "Hira", "Imperial_Aramaic", "Armi", "Inherited", "Zinh", "Qaai", "Inscriptional_Pahlavi", "Phli", "Inscriptional_Parthian", "Prti", "Javanese", "Java", "Kaithi", "Kthi", "Kannada", "Knda", "Katakana", "Kana", "Kayah_Li", "Kali", "Kharoshthi", "Khar", "Khmer", "Khmr", "Khojki", "Khoj", "Khudawadi", "Sind", "Lao", "Laoo", "Latin", "Latn", "Lepcha", "Lepc", "Limbu", "Limb", "Linear_A", "Lina", "Linear_B", "Linb", "Lisu", "Lycian", "Lyci", "Lydian", "Lydi", "Mahajani", "Mahj", "Malayalam", "Mlym", "Mandaic", "Mand", "Manichaean", "Mani", "Marchen", "Marc", "Masaram_Gondi", "Gonm", "Meetei_Mayek", "Mtei", "Mende_Kikakui", "Mend", "Meroitic_Cursive", "Merc", "Meroitic_Hieroglyphs", "Mero", "Miao", "Plrd", "Modi", "Mongolian", "Mong", "Mro", "Mroo", "Multani", "Mult", "Myanmar", "Mymr", "Nabataean", "Nbat", "New_Tai_Lue", "Talu", "Newa", "Nko", "Nkoo", "Nushu", "Nshu", "Ogham", "Ogam", "Ol_Chiki", "Olck", "Old_Hungarian", "Hung", "Old_Italic", "Ital", "Old_North_Arabian", "Narb", "Old_Permic", "Perm", "Old_Persian", "Xpeo", "Old_South_Arabian", "Sarb", "Old_Turkic", "Orkh", "Oriya", "Orya", "Osage", "Osge", "Osmanya", "Osma", "Pahawh_Hmong", "Hmng", "Palmyrene", "Palm", "Pau_Cin_Hau", "Pauc", "Phags_Pa", "Phag", "Phoenician", "Phnx", "Psalter_Pahlavi", "Phlp", "Rejang", "Rjng", "Runic", "Runr", "Samaritan", "Samr", "Saurashtra", "Saur", "Sharada", "Shrd", "Shavian", "Shaw", "Siddham", "Sidd", "SignWriting", "Sgnw", "Sinhala", "Sinh", "Sora_Sompeng", "Sora", "Soyombo", "Soyo", "Sundanese", "Sund", "Syloti_Nagri", "Sylo", "Syriac", "Syrc", "Tagalog", "Tglg", "Tagbanwa", "Tagb", "Tai_Le", "Tale", "Tai_Tham", "Lana", "Tai_Viet", "Tavt", "Takri", "Takr", "Tamil", "Taml", "Tangut", "Tang", "Telugu", "Telu", "Thaana", "Thaa", "Thai", "Tibetan", "Tibt", "Tifinagh", "Tfng", "Tirhuta", "Tirh", "Ugaritic", "Ugar", "Vai", "Vaii", "Warang_Citi", "Wara", "Yi", "Yiii", "Zanabazar_Square", "Zanb"] }; Array.prototype.push.apply(data.$LONE, data.General_Category); data.gc = data.General_Category; data.sc = data.Script_Extensions = data.scx = data.Script; var pp$9 = Parser.prototype; var RegExpValidationState = function RegExpValidationState(parser) { this.parser = parser; this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : ""); this.source = ""; this.flags = ""; this.start = 0; this.switchU = false; this.switchN = false; this.pos = 0; this.lastIntValue = 0; this.lastStringValue = ""; this.lastAssertionIsQuantifiable = false; this.numCapturingParens = 0; this.maxBackReference = 0; this.groupNames = []; this.backReferenceNames = [] }; RegExpValidationState.prototype.reset = function reset(start, pattern, flags) { var unicode = flags.indexOf("u") !== -1; this.start = start | 0; this.source = pattern + ""; this.flags = flags; this.switchU = unicode && this.parser.options.ecmaVersion >= 6; this.switchN = unicode && this.parser.options.ecmaVersion >= 9 }; RegExpValidationState.prototype.raise = function raise(message) { this.parser.raiseRecoverable(this.start, "Invalid regular expression: /" + this.source + "/: " + message) }; RegExpValidationState.prototype.at = function at(i) { var s = this.source; var l = s.length; if (i >= l) { return -1 } var c = s.charCodeAt(i); if (!this.switchU || c <= 55295 || c >= 57344 || i + 1 >= l) { return c } return (c << 10) + s.charCodeAt(i + 1) - 56613888 }; RegExpValidationState.prototype.nextIndex = function nextIndex(i) { var s = this.source; var l = s.length; if (i >= l) { return l } var c = s.charCodeAt(i); if (!this.switchU || c <= 55295 || c >= 57344 || i + 1 >= l) { return i + 1 } return i + 2 }; RegExpValidationState.prototype.current = function current() { return this.at(this.pos) }; RegExpValidationState.prototype.lookahead = function lookahead() { return this.at(this.nextIndex(this.pos)) }; RegExpValidationState.prototype.advance = function advance() { this.pos = this.nextIndex(this.pos) }; RegExpValidationState.prototype.eat = function eat(ch) { if (this.current() === ch) { this.advance(); return true } return false }; function codePointToString$1(ch) { if (ch <= 65535) { return String.fromCharCode(ch) } ch -= 65536; return String.fromCharCode((ch >> 10) + 55296, (ch & 1023) + 56320) } pp$9.validateRegExpFlags = function(state) { var this$1 = this; var validFlags = state.validFlags; var flags = state.flags; for (var i = 0; i < flags.length; i++) { var flag = flags.charAt(i); if (validFlags.indexOf(flag) === -1) { this$1.raise(state.start, "Invalid regular expression flag") } if (flags.indexOf(flag, i + 1) > -1) { this$1.raise(state.start, "Duplicate regular expression flag") } } }; pp$9.validateRegExpPattern = function(state) { this.regexp_pattern(state); if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) { state.switchN = true; this.regexp_pattern(state) } }; pp$9.regexp_pattern = function(state) { state.pos = 0; state.lastIntValue = 0; state.lastStringValue = ""; state.lastAssertionIsQuantifiable = false; state.numCapturingParens = 0; state.maxBackReference = 0; state.groupNames.length = 0; state.backReferenceNames.length = 0; this.regexp_disjunction(state); if (state.pos !== state.source.length) { if (state.eat(41)) { state.raise("Unmatched ')'") } if (state.eat(93) || state.eat(125)) { state.raise("Lone quantifier brackets") } } if (state.maxBackReference > state.numCapturingParens) { state.raise("Invalid escape") } for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) { var name = list[i]; if (state.groupNames.indexOf(name) === -1) { state.raise("Invalid named capture referenced") } } }; pp$9.regexp_disjunction = function(state) { var this$1 = this; this.regexp_alternative(state); while (state.eat(124)) { this$1.regexp_alternative(state) } if (this.regexp_eatQuantifier(state, true)) { state.raise("Nothing to repeat") } if (state.eat(123)) { state.raise("Lone quantifier brackets") } }; pp$9.regexp_alternative = function(state) { while (state.pos < state.source.length && this.regexp_eatTerm(state)) {} }; pp$9.regexp_eatTerm = function(state) { if (this.regexp_eatAssertion(state)) { if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) { if (state.switchU) { state.raise("Invalid quantifier") } } return true } if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) { this.regexp_eatQuantifier(state); return true } return false }; pp$9.regexp_eatAssertion = function(state) { var start = state.pos; state.lastAssertionIsQuantifiable = false; if (state.eat(94) || state.eat(36)) { return true } if (state.eat(92)) { if (state.eat(66) || state.eat(98)) { return true } state.pos = start } if (state.eat(40) && state.eat(63)) { var lookbehind = false; if (this.options.ecmaVersion >= 9) { lookbehind = state.eat(60) } if (state.eat(61) || state.eat(33)) { this.regexp_disjunction(state); if (!state.eat(41)) { state.raise("Unterminated group") } state.lastAssertionIsQuantifiable = !lookbehind; return true } } state.pos = start; return false }; pp$9.regexp_eatQuantifier = function(state, noError) { if (noError === void 0) noError = false; if (this.regexp_eatQuantifierPrefix(state, noError)) { state.eat(63); return true } return false }; pp$9.regexp_eatQuantifierPrefix = function(state, noError) { return state.eat(42) || state.eat(43) || state.eat(63) || this.regexp_eatBracedQuantifier(state, noError) }; pp$9.regexp_eatBracedQuantifier = function(state, noError) { var start = state.pos; if (state.eat(123)) { var min = 0, max = -1; if (this.regexp_eatDecimalDigits(state)) { min = state.lastIntValue; if (state.eat(44) && this.regexp_eatDecimalDigits(state)) { max = state.lastIntValue } if (state.eat(125)) { if (max !== -1 && max < min && !noError) { state.raise("numbers out of order in {} quantifier") } return true } } if (state.switchU && !noError) { state.raise("Incomplete quantifier") } state.pos = start } return false }; pp$9.regexp_eatAtom = function(state) { return this.regexp_eatPatternCharacters(state) || state.eat(46) || this.regexp_eatReverseSolidusAtomEscape(state) || this.regexp_eatCharacterClass(state) || this.regexp_eatUncapturingGroup(state) || this.regexp_eatCapturingGroup(state) }; pp$9.regexp_eatReverseSolidusAtomEscape = function(state) { var start = state.pos; if (state.eat(92)) { if (this.regexp_eatAtomEscape(state)) { return true } state.pos = start } return false }; pp$9.regexp_eatUncapturingGroup = function(state) { var start = state.pos; if (state.eat(40)) { if (state.eat(63) && state.eat(58)) { this.regexp_disjunction(state); if (state.eat(41)) { return true } state.raise("Unterminated group") } state.pos = start } return false }; pp$9.regexp_eatCapturingGroup = function(state) { if (state.eat(40)) { if (this.options.ecmaVersion >= 9) { this.regexp_groupSpecifier(state) } else if (state.current() === 63) { state.raise("Invalid group") } this.regexp_disjunction(state); if (state.eat(41)) { state.numCapturingParens += 1; return true } state.raise("Unterminated group") } return false }; pp$9.regexp_eatExtendedAtom = function(state) { return state.eat(46) || this.regexp_eatReverseSolidusAtomEscape(state) || this.regexp_eatCharacterClass(state) || this.regexp_eatUncapturingGroup(state) || this.regexp_eatCapturingGroup(state) || this.regexp_eatInvalidBracedQuantifier(state) || this.regexp_eatExtendedPatternCharacter(state) }; pp$9.regexp_eatInvalidBracedQuantifier = function(state) { if (this.regexp_eatBracedQuantifier(state, true)) { state.raise("Nothing to repeat") } return false }; pp$9.regexp_eatSyntaxCharacter = function(state) { var ch = state.current(); if (isSyntaxCharacter(ch)) { state.lastIntValue = ch; state.advance(); return true } return false }; function isSyntaxCharacter(ch) { return ch === 36 || ch >= 40 && ch <= 43 || ch === 46 || ch === 63 || ch >= 91 && ch <= 94 || ch >= 123 && ch <= 125 } pp$9.regexp_eatPatternCharacters = function(state) { var start = state.pos; var ch = 0; while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) { state.advance() } return state.pos !== start }; pp$9.regexp_eatExtendedPatternCharacter = function(state) { var ch = state.current(); if (ch !== -1 && ch !== 36 && !(ch >= 40 && ch <= 43) && ch !== 46 && ch !== 63 && ch !== 91 && ch !== 94 && ch !== 124) { state.advance(); return true } return false }; pp$9.regexp_groupSpecifier = function(state) { if (state.eat(63)) { if (this.regexp_eatGroupName(state)) { if (state.groupNames.indexOf(state.lastStringValue) !== -1) { state.raise("Duplicate capture group name") } state.groupNames.push(state.lastStringValue); return } state.raise("Invalid group") } }; pp$9.regexp_eatGroupName = function(state) { state.lastStringValue = ""; if (state.eat(60)) { if (this.regexp_eatRegExpIdentifierName(state) && state.eat(62)) { return true } state.raise("Invalid capture group name") } return false }; pp$9.regexp_eatRegExpIdentifierName = function(state) { state.lastStringValue = ""; if (this.regexp_eatRegExpIdentifierStart(state)) { state.lastStringValue += codePointToString$1(state.lastIntValue); while (this.regexp_eatRegExpIdentifierPart(state)) { state.lastStringValue += codePointToString$1(state.lastIntValue) } return true } return false }; pp$9.regexp_eatRegExpIdentifierStart = function(state) { var start = state.pos; var ch = state.current(); state.advance(); if (ch === 92 && this.regexp_eatRegExpUnicodeEscapeSequence(state)) { ch = state.lastIntValue } if (isRegExpIdentifierStart(ch)) { state.lastIntValue = ch; return true } state.pos = start; return false }; function isRegExpIdentifierStart(ch) { return isIdentifierStart(ch, true) || ch === 36 || ch === 95 } pp$9.regexp_eatRegExpIdentifierPart = function(state) { var start = state.pos; var ch = state.current(); state.advance(); if (ch === 92 && this.regexp_eatRegExpUnicodeEscapeSequence(state)) { ch = state.lastIntValue } if (isRegExpIdentifierPart(ch)) { state.lastIntValue = ch; return true } state.pos = start; return false }; function isRegExpIdentifierPart(ch) { return isIdentifierChar(ch, true) || ch === 36 || ch === 95 || ch === 8204 || ch === 8205 } pp$9.regexp_eatAtomEscape = function(state) { if (this.regexp_eatBackReference(state) || this.regexp_eatCharacterClassEscape(state) || this.regexp_eatCharacterEscape(state) || state.switchN && this.regexp_eatKGroupName(state)) { return true } if (state.switchU) { if (state.current() === 99) { state.raise("Invalid unicode escape") } state.raise("Invalid escape") } return false }; pp$9.regexp_eatBackReference = function(state) { var start = state.pos; if (this.regexp_eatDecimalEscape(state)) { var n = state.lastIntValue; if (state.switchU) { if (n > state.maxBackReference) { state.maxBackReference = n } return true } if (n <= state.numCapturingParens) { return true } state.pos = start } return false }; pp$9.regexp_eatKGroupName = function(state) { if (state.eat(107)) { if (this.regexp_eatGroupName(state)) { state.backReferenceNames.push(state.lastStringValue); return true } state.raise("Invalid named reference") } return false }; pp$9.regexp_eatCharacterEscape = function(state) { return this.regexp_eatControlEscape(state) || this.regexp_eatCControlLetter(state) || this.regexp_eatZero(state) || this.regexp_eatHexEscapeSequence(state) || this.regexp_eatRegExpUnicodeEscapeSequence(state) || !state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state) || this.regexp_eatIdentityEscape(state) }; pp$9.regexp_eatCControlLetter = function(state) { var start = state.pos; if (state.eat(99)) { if (this.regexp_eatControlLetter(state)) { return true } state.pos = start } return false }; pp$9.regexp_eatZero = function(state) { if (state.current() === 48 && !isDecimalDigit(state.lookahead())) { state.lastIntValue = 0; state.advance(); return true } return false }; pp$9.regexp_eatControlEscape = function(state) { var ch = state.current(); if (ch === 116) { state.lastIntValue = 9; state.advance(); return true } if (ch === 110) { state.lastIntValue = 10; state.advance(); return true } if (ch === 118) { state.lastIntValue = 11; state.advance(); return true } if (ch === 102) { state.lastIntValue = 12; state.advance(); return true } if (ch === 114) { state.lastIntValue = 13; state.advance(); return true } return false }; pp$9.regexp_eatControlLetter = function(state) { var ch = state.current(); if (isControlLetter(ch)) { state.lastIntValue = ch % 32; state.advance(); return true } return false }; function isControlLetter(ch) { return ch >= 65 && ch <= 90 || ch >= 97 && ch <= 122 } pp$9.regexp_eatRegExpUnicodeEscapeSequence = function(state) { var start = state.pos; if (state.eat(117)) { if (this.regexp_eatFixedHexDigits(state, 4)) { var lead = state.lastIntValue; if (state.switchU && lead >= 55296 && lead <= 56319) { var leadSurrogateEnd = state.pos; if (state.eat(92) && state.eat(117) && this.regexp_eatFixedHexDigits(state, 4)) { var trail = state.lastIntValue; if (trail >= 56320 && trail <= 57343) { state.lastIntValue = (lead - 55296) * 1024 + (trail - 56320) + 65536; return true } } state.pos = leadSurrogateEnd; state.lastIntValue = lead } return true } if (state.switchU && state.eat(123) && this.regexp_eatHexDigits(state) && state.eat(125) && isValidUnicode(state.lastIntValue)) { return true } if (state.switchU) { state.raise("Invalid unicode escape") } state.pos = start } return false }; function isValidUnicode(ch) { return ch >= 0 && ch <= 1114111 } pp$9.regexp_eatIdentityEscape = function(state) { if (state.switchU) { if (this.regexp_eatSyntaxCharacter(state)) { return true } if (state.eat(47)) { state.lastIntValue = 47; return true } return false } var ch = state.current(); if (ch !== 99 && (!state.switchN || ch !== 107)) { state.lastIntValue = ch; state.advance(); return true } return false }; pp$9.regexp_eatDecimalEscape = function(state) { state.lastIntValue = 0; var ch = state.current(); if (ch >= 49 && ch <= 57) { do { state.lastIntValue = 10 * state.lastIntValue + (ch - 48); state.advance() } while ((ch = state.current()) >= 48 && ch <= 57); return true } return false }; pp$9.regexp_eatCharacterClassEscape = function(state) { var ch = state.current(); if (isCharacterClassEscape(ch)) { state.lastIntValue = -1; state.advance(); return true } if (state.switchU && this.options.ecmaVersion >= 9 && (ch === 80 || ch === 112)) { state.lastIntValue = -1; state.advance(); if (state.eat(123) && this.regexp_eatUnicodePropertyValueExpression(state) && state.eat(125)) { return true } state.raise("Invalid property name") } return false }; function isCharacterClassEscape(ch) { return ch === 100 || ch === 68 || ch === 115 || ch === 83 || ch === 119 || ch === 87 } pp$9.regexp_eatUnicodePropertyValueExpression = function(state) { var start = state.pos; if (this.regexp_eatUnicodePropertyName(state) && state.eat(61)) { var name = state.lastStringValue; if (this.regexp_eatUnicodePropertyValue(state)) { var value = state.lastStringValue; this.regexp_validateUnicodePropertyNameAndValue(state, name, value); return true } } state.pos = start; if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) { var nameOrValue = state.lastStringValue; this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue); return true } return false }; pp$9.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) { if (!data.hasOwnProperty(name) || data[name].indexOf(value) === -1) { state.raise("Invalid property name") } }; pp$9.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) { if (data.$LONE.indexOf(nameOrValue) === -1) { state.raise("Invalid property name") } }; pp$9.regexp_eatUnicodePropertyName = function(state) { var ch = 0; state.lastStringValue = ""; while (isUnicodePropertyNameCharacter(ch = state.current())) { state.lastStringValue += codePointToString$1(ch); state.advance() } return state.lastStringValue !== "" }; function isUnicodePropertyNameCharacter(ch) { return isControlLetter(ch) || ch === 95 } pp$9.regexp_eatUnicodePropertyValue = function(state) { var ch = 0; state.lastStringValue = ""; while (isUnicodePropertyValueCharacter(ch = state.current())) { state.lastStringValue += codePointToString$1(ch); state.advance() } return state.lastStringValue !== "" }; function isUnicodePropertyValueCharacter(ch) { return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch) } pp$9.regexp_eatLoneUnicodePropertyNameOrValue = function(state) { return this.regexp_eatUnicodePropertyValue(state) }; pp$9.regexp_eatCharacterClass = function(state) { if (state.eat(91)) { state.eat(94); this.regexp_classRanges(state); if (state.eat(93)) { return true } state.raise("Unterminated character class") } return false }; pp$9.regexp_classRanges = function(state) { var this$1 = this; while (this.regexp_eatClassAtom(state)) { var left = state.lastIntValue; if (state.eat(45) && this$1.regexp_eatClassAtom(state)) { var right = state.lastIntValue; if (state.switchU && (left === -1 || right === -1)) { state.raise("Invalid character class") } if (left !== -1 && right !== -1 && left > right) { state.raise("Range out of order in character class") } } } }; pp$9.regexp_eatClassAtom = function(state) { var start = state.pos; if (state.eat(92)) { if (this.regexp_eatClassEscape(state)) { return true } if (state.switchU) { var ch$1 = state.current(); if (ch$1 === 99 || isOctalDigit(ch$1)) { state.raise("Invalid class escape") } state.raise("Invalid escape") } state.pos = start } var ch = state.current(); if (ch !== 93) { state.lastIntValue = ch; state.advance(); return true } return false }; pp$9.regexp_eatClassEscape = function(state) { var start = state.pos; if (state.eat(98)) { state.lastIntValue = 8; return true } if (state.switchU && state.eat(45)) { state.lastIntValue = 45; return true } if (!state.switchU && state.eat(99)) { if (this.regexp_eatClassControlLetter(state)) { return true } state.pos = start } return this.regexp_eatCharacterClassEscape(state) || this.regexp_eatCharacterEscape(state) }; pp$9.regexp_eatClassControlLetter = function(state) { var ch = state.current(); if (isDecimalDigit(ch) || ch === 95) { state.lastIntValue = ch % 32; state.advance(); return true } return false }; pp$9.regexp_eatHexEscapeSequence = function(state) { var start = state.pos; if (state.eat(120)) { if (this.regexp_eatFixedHexDigits(state, 2)) { return true } if (state.switchU) { state.raise("Invalid escape") } state.pos = start } return false }; pp$9.regexp_eatDecimalDigits = function(state) { var start = state.pos; var ch = 0; state.lastIntValue = 0; while (isDecimalDigit(ch = state.current())) { state.lastIntValue = 10 * state.lastIntValue + (ch - 48); state.advance() } return state.pos !== start }; function isDecimalDigit(ch) { return ch >= 48 && ch <= 57 } pp$9.regexp_eatHexDigits = function(state) { var start = state.pos; var ch = 0; state.lastIntValue = 0; while (isHexDigit(ch = state.current())) { state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); state.advance() } return state.pos !== start }; function isHexDigit(ch) { return ch >= 48 && ch <= 57 || ch >= 65 && ch <= 70 || ch >= 97 && ch <= 102 } function hexToInt(ch) { if (ch >= 65 && ch <= 70) { return 10 + (ch - 65) } if (ch >= 97 && ch <= 102) { return 10 + (ch - 97) } return ch - 48 } pp$9.regexp_eatLegacyOctalEscapeSequence = function(state) { if (this.regexp_eatOctalDigit(state)) { var n1 = state.lastIntValue; if (this.regexp_eatOctalDigit(state)) { var n2 = state.lastIntValue; if (n1 <= 3 && this.regexp_eatOctalDigit(state)) { state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue } else { state.lastIntValue = n1 * 8 + n2 } } else { state.lastIntValue = n1 } return true } return false }; pp$9.regexp_eatOctalDigit = function(state) { var ch = state.current(); if (isOctalDigit(ch)) { state.lastIntValue = ch - 48; state.advance(); return true } state.lastIntValue = 0; return false }; function isOctalDigit(ch) { return ch >= 48 && ch <= 55 } pp$9.regexp_eatFixedHexDigits = function(state, length) { var start = state.pos; state.lastIntValue = 0; for (var i = 0; i < length; ++i) { var ch = state.current(); if (!isHexDigit(ch)) { state.pos = start; return false } state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); state.advance() } return true }; var Token = function Token(p) { this.type = p.type; this.value = p.value; this.start = p.start; this.end = p.end; if (p.options.locations) { this.loc = new SourceLocation(p, p.startLoc, p.endLoc) } if (p.options.ranges) { this.range = [p.start, p.end] } }; var pp$8 = Parser.prototype; pp$8.next = function() { if (this.options.onToken) { this.options.onToken(new Token(this)) } this.lastTokEnd = this.end; this.lastTokStart = this.start; this.lastTokEndLoc = this.endLoc; this.lastTokStartLoc = this.startLoc; this.nextToken() }; pp$8.getToken = function() { this.next(); return new Token(this) }; if (typeof Symbol !== "undefined") { pp$8[Symbol.iterator] = function() { var this$1 = this; return { next: function() { var token = this$1.getToken(); return { done: token.type === types.eof, value: token } } } } } pp$8.curContext = function() { return this.context[this.context.length - 1] }; pp$8.nextToken = function() { var curContext = this.curContext(); if (!curContext || !curContext.preserveSpace) { this.skipSpace() } this.start = this.pos; if (this.options.locations) { this.startLoc = this.curPosition() } if (this.pos >= this.input.length) { return this.finishToken(types.eof) } if (curContext.override) { return curContext.override(this) } else { this.readToken(this.fullCharCodeAtPos()) } }; pp$8.readToken = function(code) { if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92) { return this.readWord() } return this.getTokenFromCode(code) }; pp$8.fullCharCodeAtPos = function() { var code = this.input.charCodeAt(this.pos); if (code <= 55295 || code >= 57344) { return code } var next = this.input.charCodeAt(this.pos + 1); return (code << 10) + next - 56613888 }; pp$8.skipBlockComment = function() { var this$1 = this; var startLoc = this.options.onComment && this.curPosition(); var start = this.pos, end = this.input.indexOf("*/", this.pos += 2); if (end === -1) { this.raise(this.pos - 2, "Unterminated comment") } this.pos = end + 2; if (this.options.locations) { lineBreakG.lastIndex = start; var match; while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) { ++this$1.curLine; this$1.lineStart = match.index + match[0].length } } if (this.options.onComment) { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, startLoc, this.curPosition()) } }; pp$8.skipLineComment = function(startSkip) { var this$1 = this; var start = this.pos; var startLoc = this.options.onComment && this.curPosition(); var ch = this.input.charCodeAt(this.pos += startSkip); while (this.pos < this.input.length && !isNewLine(ch)) { ch = this$1.input.charCodeAt(++this$1.pos) } if (this.options.onComment) { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, startLoc, this.curPosition()) } }; pp$8.skipSpace = function() { var this$1 = this; loop: while (this.pos < this.input.length) { var ch = this$1.input.charCodeAt(this$1.pos); switch (ch) { case 32: case 160: ++this$1.pos; break; case 13: if (this$1.input.charCodeAt(this$1.pos + 1) === 10) { ++this$1.pos } case 10: case 8232: case 8233: ++this$1.pos; if (this$1.options.locations) { ++this$1.curLine; this$1.lineStart = this$1.pos } break; case 47: switch (this$1.input.charCodeAt(this$1.pos + 1)) { case 42: this$1.skipBlockComment(); break; case 47: this$1.skipLineComment(2); break; default: break loop } break; default: if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) { ++this$1.pos } else { break loop } } } }; pp$8.finishToken = function(type, val) { this.end = this.pos; if (this.options.locations) { this.endLoc = this.curPosition() } var prevType = this.type; this.type = type; this.value = val; this.updateContext(prevType) }; pp$8.readToken_dot = function() { var next = this.input.charCodeAt(this.pos + 1); if (next >= 48 && next <= 57) { return this.readNumber(true) } var next2 = this.input.charCodeAt(this.pos + 2); if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { this.pos += 3; return this.finishToken(types.ellipsis) } else { ++this.pos; return this.finishToken(types.dot) } }; pp$8.readToken_slash = function() { var next = this.input.charCodeAt(this.pos + 1); if (this.exprAllowed) { ++this.pos; return this.readRegexp() } if (next === 61) { return this.finishOp(types.assign, 2) } return this.finishOp(types.slash, 1) }; pp$8.readToken_mult_modulo_exp = function(code) { var next = this.input.charCodeAt(this.pos + 1); var size = 1; var tokentype = code === 42 ? types.star : types.modulo; if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) { ++size; tokentype = types.starstar; next = this.input.charCodeAt(this.pos + 2) } if (next === 61) { return this.finishOp(types.assign, size + 1) } return this.finishOp(tokentype, size) }; pp$8.readToken_pipe_amp = function(code) { var next = this.input.charCodeAt(this.pos + 1); if (next === code) { return this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2) } if (next === 61) { return this.finishOp(types.assign, 2) } return this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1) }; pp$8.readToken_caret = function() { var next = this.input.charCodeAt(this.pos + 1); if (next === 61) { return this.finishOp(types.assign, 2) } return this.finishOp(types.bitwiseXOR, 1) }; pp$8.readToken_plus_min = function(code) { var next = this.input.charCodeAt(this.pos + 1); if (next === code) { if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 && (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) { this.skipLineComment(3); this.skipSpace(); return this.nextToken() } return this.finishOp(types.incDec, 2) } if (next === 61) { return this.finishOp(types.assign, 2) } return this.finishOp(types.plusMin, 1) }; pp$8.readToken_lt_gt = function(code) { var next = this.input.charCodeAt(this.pos + 1); var size = 1; if (next === code) { size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2; if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types.assign, size + 1) } return this.finishOp(types.bitShift, size) } if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && this.input.charCodeAt(this.pos + 3) === 45) { this.skipLineComment(4); this.skipSpace(); return this.nextToken() } if (next === 61) { size = 2 } return this.finishOp(types.relational, size) }; pp$8.readToken_eq_excl = function(code) { var next = this.input.charCodeAt(this.pos + 1); if (next === 61) { return this.finishOp(types.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) } if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { this.pos += 2; return this.finishToken(types.arrow) } return this.finishOp(code === 61 ? types.eq : types.prefix, 1) }; pp$8.getTokenFromCode = function(code) { switch (code) { case 46: return this.readToken_dot(); case 40: ++this.pos; return this.finishToken(types.parenL); case 41: ++this.pos; return this.finishToken(types.parenR); case 59: ++this.pos; return this.finishToken(types.semi); case 44: ++this.pos; return this.finishToken(types.comma); case 91: ++this.pos; return this.finishToken(types.bracketL); case 93: ++this.pos; return this.finishToken(types.bracketR); case 123: ++this.pos; return this.finishToken(types.braceL); case 125: ++this.pos; return this.finishToken(types.braceR); case 58: ++this.pos; return this.finishToken(types.colon); case 63: ++this.pos; return this.finishToken(types.question); case 96: if (this.options.ecmaVersion < 6) { break }++this.pos; return this.finishToken(types.backQuote); case 48: var next = this.input.charCodeAt(this.pos + 1); if (next === 120 || next === 88) { return this.readRadixNumber(16) } if (this.options.ecmaVersion >= 6) { if (next === 111 || next === 79) { return this.readRadixNumber(8) } if (next === 98 || next === 66) { return this.readRadixNumber(2) } } case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: return this.readNumber(false); case 34: case 39: return this.readString(code); case 47: return this.readToken_slash(); case 37: case 42: return this.readToken_mult_modulo_exp(code); case 124: case 38: return this.readToken_pipe_amp(code); case 94: return this.readToken_caret(); case 43: case 45: return this.readToken_plus_min(code); case 60: case 62: return this.readToken_lt_gt(code); case 61: case 33: return this.readToken_eq_excl(code); case 126: return this.finishOp(types.prefix, 1) } this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'") }; pp$8.finishOp = function(type, size) { var str = this.input.slice(this.pos, this.pos + size); this.pos += size; return this.finishToken(type, str) }; pp$8.readRegexp = function() { var this$1 = this; var escaped, inClass, start = this.pos; for (;;) { if (this$1.pos >= this$1.input.length) { this$1.raise(start, "Unterminated regular expression") } var ch = this$1.input.charAt(this$1.pos); if (lineBreak.test(ch)) { this$1.raise(start, "Unterminated regular expression") } if (!escaped) { if (ch === "[") { inClass = true } else if (ch === "]" && inClass) { inClass = false } else if (ch === "/" && !inClass) { break } escaped = ch === "\\" } else { escaped = false }++this$1.pos } var pattern = this.input.slice(start, this.pos); ++this.pos; var flagsStart = this.pos; var flags = this.readWord1(); if (this.containsEsc) { this.unexpected(flagsStart) } var state = this.regexpState || (this.regexpState = new RegExpValidationState(this)); state.reset(start, pattern, flags); this.validateRegExpFlags(state); this.validateRegExpPattern(state); var value = null; try { value = new RegExp(pattern, flags) } catch (e) {} return this.finishToken(types.regexp, { pattern: pattern, flags: flags, value: value }) }; pp$8.readInt = function(radix, len) { var this$1 = this; var start = this.pos, total = 0; for (var i = 0, e = len == null ? Infinity : len; i < e; ++i) { var code = this$1.input.charCodeAt(this$1.pos), val = void 0; if (code >= 97) { val = code - 97 + 10 } else if (code >= 65) { val = code - 65 + 10 } else if (code >= 48 && code <= 57) { val = code - 48 } else { val = Infinity } if (val >= radix) { break }++this$1.pos; total = total * radix + val } if (this.pos === start || len != null && this.pos - start !== len) { return null } return total }; pp$8.readRadixNumber = function(radix) { this.pos += 2; var val = this.readInt(radix); if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix) } if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number") } return this.finishToken(types.num, val) }; pp$8.readNumber = function(startsWithDot) { var start = this.pos; if (!startsWithDot && this.readInt(10) === null) { this.raise(start, "Invalid number") } var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48; if (octal && this.strict) { this.raise(start, "Invalid number") } if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false } var next = this.input.charCodeAt(this.pos); if (next === 46 && !octal) { ++this.pos; this.readInt(10); next = this.input.charCodeAt(this.pos) } if ((next === 69 || next === 101) && !octal) { next = this.input.charCodeAt(++this.pos); if (next === 43 || next === 45) { ++this.pos } if (this.readInt(10) === null) { this.raise(start, "Invalid number") } } if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number") } var str = this.input.slice(start, this.pos); var val = octal ? parseInt(str, 8) : parseFloat(str); return this.finishToken(types.num, val) }; pp$8.readCodePoint = function() { var ch = this.input.charCodeAt(this.pos), code; if (ch === 123) { if (this.options.ecmaVersion < 6) { this.unexpected() } var codePos = ++this.pos; code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos); ++this.pos; if (code > 1114111) { this.invalidStringToken(codePos, "Code point out of bounds") } } else { code = this.readHexChar(4) } return code }; function codePointToString(code) { if (code <= 65535) { return String.fromCharCode(code) } code -= 65536; return String.fromCharCode((code >> 10) + 55296, (code & 1023) + 56320) } pp$8.readString = function(quote) { var this$1 = this; var out = "", chunkStart = ++this.pos; for (;;) { if (this$1.pos >= this$1.input.length) { this$1.raise(this$1.start, "Unterminated string constant") } var ch = this$1.input.charCodeAt(this$1.pos); if (ch === quote) { break } if (ch === 92) { out += this$1.input.slice(chunkStart, this$1.pos); out += this$1.readEscapedChar(false); chunkStart = this$1.pos } else { if (isNewLine(ch, this$1.options.ecmaVersion >= 10)) { this$1.raise(this$1.start, "Unterminated string constant") }++this$1.pos } } out += this.input.slice(chunkStart, this.pos++); return this.finishToken(types.string, out) }; var INVALID_TEMPLATE_ESCAPE_ERROR = {}; pp$8.tryReadTemplateToken = function() { this.inTemplateElement = true; try { this.readTmplToken() } catch (err) { if (err === INVALID_TEMPLATE_ESCAPE_ERROR) { this.readInvalidTemplateToken() } else { throw err } } this.inTemplateElement = false }; pp$8.invalidStringToken = function(position, message) { if (this.inTemplateElement && this.options.ecmaVersion >= 9) { throw INVALID_TEMPLATE_ESCAPE_ERROR } else { this.raise(position, message) } }; pp$8.readTmplToken = function() { var this$1 = this; var out = "", chunkStart = this.pos; for (;;) { if (this$1.pos >= this$1.input.length) { this$1.raise(this$1.start, "Unterminated template") } var ch = this$1.input.charCodeAt(this$1.pos); if (ch === 96 || ch === 36 && this$1.input.charCodeAt(this$1.pos + 1) === 123) { if (this$1.pos === this$1.start && (this$1.type === types.template || this$1.type === types.invalidTemplate)) { if (ch === 36) { this$1.pos += 2; return this$1.finishToken(types.dollarBraceL) } else { ++this$1.pos; return this$1.finishToken(types.backQuote) } } out += this$1.input.slice(chunkStart, this$1.pos); return this$1.finishToken(types.template, out) } if (ch === 92) { out += this$1.input.slice(chunkStart, this$1.pos); out += this$1.readEscapedChar(true); chunkStart = this$1.pos } else if (isNewLine(ch)) { out += this$1.input.slice(chunkStart, this$1.pos); ++this$1.pos; switch (ch) { case 13: if (this$1.input.charCodeAt(this$1.pos) === 10) { ++this$1.pos } case 10: out += "\n"; break; default: out += String.fromCharCode(ch); break } if (this$1.options.locations) { ++this$1.curLine; this$1.lineStart = this$1.pos } chunkStart = this$1.pos } else { ++this$1.pos } } }; pp$8.readInvalidTemplateToken = function() { var this$1 = this; for (; this.pos < this.input.length; this.pos++) { switch (this$1.input[this$1.pos]) { case "\\": ++this$1.pos; break; case "$": if (this$1.input[this$1.pos + 1] !== "{") { break } case "`": return this$1.finishToken(types.invalidTemplate, this$1.input.slice(this$1.start, this$1.pos)) } } this.raise(this.start, "Unterminated template") }; pp$8.readEscapedChar = function(inTemplate) { var ch = this.input.charCodeAt(++this.pos); ++this.pos; switch (ch) { case 110: return "\n"; case 114: return "\r"; case 120: return String.fromCharCode(this.readHexChar(2)); case 117: return codePointToString(this.readCodePoint()); case 116: return "\t"; case 98: return "\b"; case 118: return "\v"; case 102: return "\f"; case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos } case 10: if (this.options.locations) { this.lineStart = this.pos; ++this.curLine } return ""; default: if (ch >= 48 && ch <= 55) { var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0]; var octal = parseInt(octalStr, 8); if (octal > 255) { octalStr = octalStr.slice(0, -1); octal = parseInt(octalStr, 8) } this.pos += octalStr.length - 1; ch = this.input.charCodeAt(this.pos); if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) { this.invalidStringToken(this.pos - 1 - octalStr.length, inTemplate ? "Octal literal in template string" : "Octal literal in strict mode") } return String.fromCharCode(octal) } return String.fromCharCode(ch) } }; pp$8.readHexChar = function(len) { var codePos = this.pos; var n = this.readInt(16, len); if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence") } return n }; pp$8.readWord1 = function() { var this$1 = this; this.containsEsc = false; var word = "", first = true, chunkStart = this.pos; var astral = this.options.ecmaVersion >= 6; while (this.pos < this.input.length) { var ch = this$1.fullCharCodeAtPos(); if (isIdentifierChar(ch, astral)) { this$1.pos += ch <= 65535 ? 1 : 2 } else if (ch === 92) { this$1.containsEsc = true; word += this$1.input.slice(chunkStart, this$1.pos); var escStart = this$1.pos; if (this$1.input.charCodeAt(++this$1.pos) !== 117) { this$1.invalidStringToken(this$1.pos, "Expecting Unicode escape sequence \\uXXXX") }++this$1.pos; var esc = this$1.readCodePoint(); if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral)) { this$1.invalidStringToken(escStart, "Invalid Unicode escape") } word += codePointToString(esc); chunkStart = this$1.pos } else { break } first = false } return word + this.input.slice(chunkStart, this.pos) }; pp$8.readWord = function() { var word = this.readWord1(); var type = types.name; if (this.keywords.test(word)) { if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword " + word) } type = keywords$1[word] } return this.finishToken(type, word) }; var version = "5.7.1"; function parse(input, options) { return new Parser(options, input).parse() } function parseExpressionAt(input, pos, options) { var p = new Parser(options, input, pos); p.nextToken(); return p.parseExpression() } function tokenizer(input, options) { return new Parser(options, input) } var parse_dammit; var LooseParser; var pluginsLoose; function addLooseExports(parse, Parser$$1, plugins$$1) { parse_dammit = parse; LooseParser = Parser$$1; pluginsLoose = plugins$$1 } }, function(module, exports) {}, , , , , , , , , , , , , , function(module, exports, __webpack_require__) { __webpack_require__(224); module.exports = __webpack_require__(222) }]); webpackJsonp([0], { 1159: function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor) } } return function(Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor } }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function") } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called") } return call && (typeof call === "object" || typeof call === "function") ? call : self } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass) } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass } var PlainCollider = __webpack_require__(223); var wallGenerator = __webpack_require__(73); var Wall = __webpack_require__(141); var FreeDoor = __webpack_require__(1163); var MetalBox = __webpack_require__(1164); var WoodBox = __webpack_require__(471); var Bouncy = __webpack_require__(472); var Finish = __webpack_require__(1165); var LavaWall = __webpack_require__(473); var Floor = __webpack_require__(1166); var FuelCan = __webpack_require__(1167); var PlayScene = exports.PlayScene = function(_Phaser$Scene) { _inherits(PlayScene, _Phaser$Scene); function PlayScene() { _classCallCheck(this, PlayScene); return _possibleConstructorReturn(this, (PlayScene.__proto__ || Object.getPrototypeOf(PlayScene)).call(this, "PlayScene")) } _createClass(PlayScene, [{ key: "create", value: function create() { var gameWidth = this.game.config.width, gameHeight = this.game.config.height; PlainCollider.initiate(); this.staticWallsCollGroup = PlainCollider.registerNewCollGroup("staticWallsCollGroup"); this.gravityWallsCollGroup = PlainCollider.registerNewCollGroup("gravityWallsCollGroup"); this.bouncyCollGroup = PlainCollider.registerNewCollGroup("bouncyCollGroup"); this.fuelCanCollGroup = PlainCollider.registerNewCollGroup("fuelCanCollGroup"); this.playPortrait = this.add.image(gameWidth * .5 - 1e4, gameHeight * .5 - 1e4, "playPortrait"); this.playPortrait.setDepth(200); this.playPortrait.alpha = 0; this.maze = this.add.group(); this.respawnFuelSpots = []; this.fuelSpawned = false; var levelName = "level" + this.game.levelNumber; this.level = this.cache.json.get(levelName); this.loadLevel(this.level); var mainWall = this.maze.children.entries[0]; this.cameras.main.startFollow(mainWall, true); var scale = Math.min(this.cameras.main.width / (mainWall.width + 80), this.cameras.main.height / (mainWall.height + 80)); this.cameras.main.setZoom(scale); this.input.on("pointerdown", function(pointer) {}, this); this.leftKey = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.LEFT); this.rightKey = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.RIGHT); this.upKey = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.UP); this.rKey = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.R); this.nKey = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.N); this.playing = true; this.guiContainer = this.add.container(1e4, 1e4); this.fuelLevelBack = this.add.image(1e4 + gameWidth * .87, 1e4 + gameHeight * .08, "fuelIndicatorBack"); this.fuelLevel = this.add.image(1e4 + gameWidth * .87, 1e4 + gameHeight * .08, "fuelIndicatorLevel"); this.fuelLevelLogo = this.add.image(1e4 + gameWidth * .87, 1e4 + gameHeight * .08, "fuelIndicatorLogo"); this.noFuelTween = this.tweens.add({ targets: this.noFuelSignal, props: { alpha: { value: 1, ease: "Quad.easeOut" } }, yoyo: true, duration: 300, paused: true }); this.fuelLevelBack.setDepth(20); this.fuelLevelLogo.setDepth(21); this.pauseButton = this.makeButton("pauseButton", "", gameWidth * .13, gameHeight * .08, this.pauseGame); this.guiContainer.add(this.pauseButton); this.levelLabelBack = this.add.image(this.game.config.width / 2, gameHeight * .03, "levelLabelBack"); this.levelLabel = this.add.bitmapText(this.levelLabelBack.x, this.levelLabelBack.y, "peachFont", "Level " + this.game.levelNumber, 28); this.levelLabel.setOrigin(.5); this.guiContainer.add(this.levelLabelBack); this.guiContainer.add(this.levelLabel); this.levelLabel.setTintFill(15645293); if (!this.game.device.os.desktop) { this.rotateCClButton = this.makeButton("rotateCClButton", "", gameWidth * .85, gameHeight * .935, this.rotateMazeLeftTween); this.rotateClButton = this.makeButton("rotateClButton", "", gameWidth * .15, gameHeight * .935, this.rotateMazeRightTween); this.thrustButton = this.makePressButton("thrustButton", "", gameWidth * .5, gameHeight * .935, this.switchContinuousThrust); var buttonsFrameGraphics = this.make.graphics(); buttonsFrameGraphics.fillStyle(4932454); buttonsFrameGraphics.fillRect(0, 0, gameWidth, gameHeight - this.thrustButton.getTopLeft().y * .98); buttonsFrameGraphics.generateTexture("buttonsFrame", gameWidth, gameHeight - this.thrustButton.getTopLeft().y * .98); this.buttonsFrame = this.add.image(0, this.thrustButton.getTopLeft().y * .98, "buttonsFrame"); this.buttonsFrame.setOrigin(0); this.guiContainer.add(this.buttonsFrame); this.guiContainer.add(this.rotateCClButton); this.guiContainer.add(this.rotateClButton); this.guiContainer.add(this.thrustButton); var scale = Math.min(this.cameras.main.width / (mainWall.width + 120), this.cameras.main.height / (mainWall.height + this.buttonsFrame.displayHeight)); this.cameras.main.setZoom(scale) } if (this.game.levelNumber === 1) { if (this.game.device.os.desktop) { this.tutRotCCl = this.add.image(gameWidth * .5, gameHeight * .98, "tutRotCCl"); this.tutRotCCl.setOrigin(.5, 1); this.tutRotCl = this.add.image(gameWidth * .5, gameHeight * .98, "tutRotCl"); this.tutRotCl.setOrigin(.5, 1); this.guiContainer.add(this.tutRotCl); this.guiContainer.add(this.tutRotCCl); this.tutRotCl.alpha = 0 } else { this.tutRotCCl = this.add.image(this.rotateCClButton.getBottomRight().x - 10, this.rotateCClButton.getTopLeft().y + 10, "mobTutRotCCl"); this.tutRotCCl.setOrigin(1, 1); this.tutRotCl = this.add.image(this.rotateClButton.getTopLeft().x + 10, this.rotateClButton.getTopLeft().y + 10, "mobTutRotCl"); this.tutRotCl.setOrigin(0, 1); this.guiContainer.add(this.tutRotCl); this.guiContainer.add(this.tutRotCCl); this.tutRotCl.alpha = 0 } } else if (this.game.levelNumber === 2) { if (this.game.device.os.desktop) { this.tutThrust = this.add.image(gameWidth * .5, gameHeight * .98, "tutThrust"); this.tutThrust.setOrigin(.5, 1); this.guiContainer.add(this.tutThrust) } else { this.tutThrust = this.add.image(gameWidth * .5, this.thrustButton.getTopLeft().y + 10, "mobTutThrust"); this.tutThrust.setOrigin(.5, 1); this.guiContainer.add(this.tutThrust) } } this.HUDCamera = this.cameras.add(0, 0, gameWidth, gameHeight); this.HUDCamera.setScroll(1e4, 1e4); this.bouncy.on("tankUp", this.tankUpBouncy, this); PlainCollider.refreshPairs(); this.popupCamera = this.cameras.add(0, 0, gameWidth, gameHeight); this.popupCamera.setScroll(-1e4, -1e4); this.winPopup = this.add.container(-1e4, -1e4); this.winPopupBack = this.add.image(gameWidth * .5, gameHeight * .5, "winPopupBack"); this.winPopupImage = this.add.image(gameWidth * .5, gameHeight * .35, "winPopupImage"); this.nextLevelButton = this.makeButton("nextLevelButton", "", gameWidth * .5 + 80, gameHeight * .65, this.launchNextLevel); this.replayButton = this.makeButton("replayButton", "", gameWidth * .5 - 80, gameHeight * .65, this.replayLevel); this.moreGamesButton = this.makeButton("moreGamesButton", "", gameWidth * .5, gameHeight * .85, this.showMoreGames); this.winPopup.add(this.winPopupBack); this.winPopup.add(this.winPopupImage); this.winPopup.add(this.nextLevelButton); this.winPopup.add(this.replayButton); this.winPopup.add(this.moreGamesButton); if (this.game.device.os.desktop) { this.winPressN = this.add.image(this.nextLevelButton.x, this.nextLevelButton.getBottomRight().y, "pressN"); this.winPressN.setOrigin(.5, 0); this.winPressR = this.add.image(this.replayButton.x, this.replayButton.getBottomRight().y, "pressR"); this.winPressR.setOrigin(.5, 0); this.winPopup.add(this.winPressR); this.winPopup.add(this.winPressN) } this.winPopup.setDepth(20); this.winPopup.alpha = 0; this.nextLevelButton.disableInteractive(); this.replayButton.disableInteractive(); this.moreGamesButton.disableInteractive(); this.finalPopup = this.add.container(-1e4, -1e4); this.finalPopupBack = this.add.image(gameWidth * .5, gameHeight * .5, "winPopupBack"); this.finalPopupImage = this.add.image(gameWidth * .5, gameHeight * .35, "finalPopupImage"); this.finalPopupImage.setScale(.9); this.finalGoLevelChoiceButton = this.makeButton("goLevelChoiceButton", "", gameWidth * .5 - 80, gameHeight * .72, this.goLevelChoice); this.finalReplayButton = this.makeButton("replayButton", "", gameWidth * .5 + 80, gameHeight * .72, this.replayLevel); this.moreGamesFinalButton = this.makeButton("moreGamesButton", "", gameWidth * .5, gameHeight * .87, this.showMoreGames); this.finalPopup.add(this.finalPopupBack); this.finalPopup.add(this.finalPopupImage); this.finalPopup.add(this.finalGoLevelChoiceButton); this.finalPopup.add(this.finalReplayButton); this.finalPopup.add(this.moreGamesFinalButton); this.finalPopup.setDepth(20); this.finalPopup.alpha = 0; this.finalGoLevelChoiceButton.disableInteractive(); this.finalReplayButton.disableInteractive(); this.moreGamesFinalButton.disableInteractive(); this.losePopup = this.add.container(-1e4, -1e4); this.losePopupBack = this.add.image(gameWidth * .5, gameHeight * .5, "losePopupBack"); this.losePopupImage = this.add.image(gameWidth * .5, gameHeight * .4, "losePopupImage"); this.loseReplayButton = this.makeButton("replayButton", "", gameWidth * .5, gameHeight * .7, this.replayLevel); this.losePopup.add(this.losePopupBack); this.losePopup.add(this.losePopupImage); this.losePopup.add(this.loseReplayButton); if (this.game.device.os.desktop) { this.losePressR = this.add.image(this.loseReplayButton.x, this.loseReplayButton.getBottomRight().y, "pressR"); this.losePressR.setOrigin(.5, 0); this.losePopup.add(this.losePressR) } this.losePopup.setDepth(20); this.losePopup.alpha = 0; this.loseReplayButton.disableInteractive(); this.pausePopup = this.add.container(-1e4, -1e4); this.pausePopupBack = this.add.image(gameWidth * .5, gameHeight * .5, "pausePopupBack"); this.pausePopupImage = this.add.image(gameWidth * .5, gameHeight * .35, "pausePopupImage"); this.pauseReplayButton = this.makeButton("replayButton", "", gameWidth * .5 - 80, gameHeight * .67, this.replayLevel); this.pauseContinueButton = this.makeButton("nextLevelButton", "", gameWidth * .5 + 80, gameHeight * .67, this.continueGame); this.pauseMuteButton = this.makeMuteButton("muteButton", "", gameWidth * .5 + 90, gameHeight * .84); this.pausePopup.add(this.pausePopupBack); this.pausePopup.add(this.pausePopupImage); this.pausePopup.add(this.pauseReplayButton); this.pausePopup.add(this.pauseContinueButton); this.pausePopup.add(this.pauseMuteButton); if (this.game.device.os.desktop) { this.pausePressR = this.add.image(this.pauseReplayButton.x, this.pauseReplayButton.getBottomRight().y, "pressR"); this.pausePressR.setOrigin(.5, 0); this.pausePopup.add(this.pausePressR) } this.pausePopup.setDepth(20); this.pausePopup.alpha = 0; this.pauseReplayButton.disableInteractive(); this.pauseContinueButton.disableInteractive(); this.pauseMuteButton.disableInteractive(); this.rocketLaunch = this.add.sprite(this.bouncy.x, this.bouncy.y, "launch"); this.rocketLaunch.alpha = 0; this.rocketLaunch.setOrigin(.5, 1); var launchAnimFrames = this.anims.generateFrameNames("launch", { start: 1, end: 9 }); this.maze.add(this.rocketLaunch); this.rocketLaunchAnimation = this.anims.create({ key: "rocketLaunch", frames: launchAnimFrames, repeat: 0, frameRate: 10 }); this.rocketLaunch.on("animationcomplete", this.hideLaunch, this); this.rocketLaunch.setDepth(11); if (this.freezed) { this.freezed = false } this.pendingAction = false; this.continuousThrust = false; this.buttonSound = this.sound.add("buttonSound"); this.loseSound = this.sound.add("loseSound"); this.winSound = this.sound.add("winSound"); this.jetSound = this.sound.add("jetSound"); this.fuelSound = this.sound.add("fuelSound"); this.rotateSound = this.sound.add("rotateSound"); this.shockSound = this.sound.add("shockSound"); if (this.game.backgroundMusic.isPaused) this.game.backgroundMusic.resume(); GameAnalytics("addProgressionEvent", "Start", levelName) } }, { key: "showFinalPopup", value: function showFinalPopup() { if (this.finalPopup.alpha === 0) { this.winSound.play(); this.finalPopup.alpha = 1; this.finalGoLevelChoiceButton.setInteractive(); this.finalReplayButton.setInteractive(); this.moreGamesFinalButton.setInteractive(); this.freezed = true; this.pauseButton.disableInteractive() } } }, { key: "loadLevel", value: function loadLevel(level) { wallGenerator.clearBin(); for (var wallI in level) { var wall = level[wallI]; switch (wall.wallType) { case "start": this.bouncy = new Bouncy(this, wall.edges[0][0], wall.edges[0][1]); PlainCollider.addObject(this.bouncy, this.bouncy.vertices); PlainCollider.assignCollGroup(this.bouncy, "bouncyCollGroup"); this.bouncy.collWith = [this.staticWallsCollGroup, this.gravityWallsCollGroup, this.fuelCanCollGroup]; this.bouncy.on("animationcomplete", this.showLosePopup, this); break; case "finish": this.finish = new Finish(this, wall.edges[0][0], wall.edges[0][1]); this.maze.add(this.finish); break; case "wall": var wallSprite = new Wall(this, wall.edges, wallI); this.maze.add(wallSprite); PlainCollider.addObject(wallSprite, wallSprite.vertices); PlainCollider.assignCollGroup(wallSprite, "staticWallsCollGroup"); wallSprite.collWith = [this.bouncyCollGroup, this.gravityWallsCollGroup]; break; case "gWall": var wallSprite = new Wall(this, wall.edges, wallI); this.maze.add(wallSprite); PlainCollider.addObject(wallSprite, wallSprite.vertices); PlainCollider.assignCollGroup(wallSprite, "gravityWallsCollGroup"); wallSprite.collWith = [this.bouncyCollGroup, this.gravityWallsCollGroup, this.staticWallsCollGroup]; break; case "freeDoor": var wallSprite = new FreeDoor(this, wall.edges, wallI); this.maze.add(wallSprite); PlainCollider.addObject(wallSprite, wallSprite.vertices); PlainCollider.assignCollGroup(wallSprite, "gravityWallsCollGroup"); wallSprite.collWith = [this.bouncyCollGroup, this.gravityWallsCollGroup, this.staticWallsCollGroup]; break; case "metalBox": var box = new MetalBox(this, wall.edges, wallI); this.maze.add(box); PlainCollider.addObject(box, box.vertices); PlainCollider.assignCollGroup(box, "gravityWallsCollGroup"); box.collWith = [this.bouncyCollGroup, this.gravityWallsCollGroup, this.staticWallsCollGroup]; break; case "woodBox": var box = new WoodBox(this, wall.edges, wallI); this.maze.add(box); PlainCollider.addObject(box, box.vertices); PlainCollider.assignCollGroup(box, "gravityWallsCollGroup"); box.collWith = [this.bouncyCollGroup, this.gravityWallsCollGroup, this.staticWallsCollGroup]; break; case "lavaWall": var wallSprite = new LavaWall(this, wall.edges, wallI); this.maze.add(wallSprite); PlainCollider.addObject(wallSprite, wallSprite.vertices); PlainCollider.assignCollGroup(wallSprite, "staticWallsCollGroup"); wallSprite.collWith = [this.bouncyCollGroup, this.gravityWallsCollGroup]; break; case "floor": this.floor = new Floor(this, wall.edges, wallI); this.maze.add(this.floor); break; case "respawnFuel": var spot = this.add.image(wall.edges[0][0], wall.edges[0][1], "fuelCan"); spot.alpha = 0; this.respawnFuelSpots.push(spot); this.maze.add(spot); break } } } }, { key: "rotateMazeRightTween", value: function rotateMazeRightTween() { if (!this.freezed) { if (this.tutRotCl && this.tutRotCl.alpha > 0) { this.tutRotCl.alpha = 0 } this.freezeForRotation(); this.maze.children.each(function(wall) { var rotTween = this.tweens.add({ targets: wall, props: { rotation: { value: wall.rotation + Math.PI / 2, ease: "Linear" } }, duration: 900 }); var prevRotation = wall.rotation; rotTween.callbacks.onUpdate = { func: function func() { var rotDelta = wall.rotation - prevRotation, newCenter = new Phaser.Math.Vector2(wall.x - this.bouncy.x, wall.y - this.bouncy.y), rotateMatrix = new Phaser.Math.Matrix3; rotateMatrix.fromArray([Math.cos(rotDelta), Math.sin(rotDelta), 0, -Math.sin(rotDelta), Math.cos(rotDelta), 0, 0, 0]); newCenter.transformMat3(rotateMatrix); newCenter.add(new Phaser.Math.Vector2(this.bouncy.x, this.bouncy.y)); prevRotation = wall.rotation; wall.x = newCenter.x; wall.y = newCenter.y }, scope: this, params: [rotTween] }; if (wall.collider) { rotTween.callbacks.onComplete = { func: function func() { PlainCollider.rotateCollider(wall, Math.PI / 2, new Phaser.Math.Vector2(this.bouncy.x, this.bouncy.y)); if (wall.__proto__.constructor === LavaWall) { wall.endRotation() } }, scope: this, params: [rotTween] } } if (wall.__proto__.constructor === LavaWall) { wall.startRotation(Math.PI / 2, new Phaser.Math.Vector2(this.bouncy.x, this.bouncy.y)) } }, this); var mainWall = this.maze.children.entries[0]; if (this.game.device.os.desktop) var scale = Math.min(this.cameras.main.width / Math.abs((mainWall.width + 80) * Math.cos(mainWall.rotation + Math.PI / 2) + (mainWall.height + 80) * Math.sin(mainWall.rotation + Math.PI / 2)), this.cameras.main.height / Math.abs((mainWall.width + 80) * Math.sin(mainWall.rotation + Math.PI / 2) + (mainWall.height + 80) * Math.cos(mainWall.rotation + Math.PI / 2))); else var scale = Math.min(this.cameras.main.width / Math.abs((mainWall.width + 120) * Math.cos(mainWall.rotation + Math.PI / 2) + (mainWall.height + this.buttonsFrame.displayHeight + 40) * Math.sin(mainWall.rotation + Math.PI / 2)), this.cameras.main.height / Math.abs((mainWall.width + 120) * Math.sin(mainWall.rotation + Math.PI / 2) + (mainWall.height + this.buttonsFrame.displayHeight + 40) * Math.cos(mainWall.rotation + Math.PI / 2))); var zoomTween = this.tweens.add({ targets: this.cameras.main, props: { zoom: { value: scale, ease: "Linear" } }, duration: 900 }); this.time.delayedCall(1100, this.unfreezeAfterRotation, [], this); if (this.jetSound.isPlaying) this.jetSound.pause(); this.rotateSound.play(); this.stopBouncyThrust() } else { this.pendingAction = this.rotateMazeRightTween } } }, { key: "rotateMazeLeftTween", value: function rotateMazeLeftTween() { if (!this.freezed) { if (this.tutRotCCl && this.tutRotCCl.alpha > 0) { this.tutRotCCl.alpha = 0; this.tutRotCl.alpha = 1 } this.freezeForRotation(); this.maze.children.each(function(wall) { var rotTween = this.tweens.add({ targets: wall, props: { rotation: { value: wall.rotation - Math.PI / 2, ease: "Linear" } }, duration: 900 }); var prevRotation = wall.rotation; rotTween.callbacks.onUpdate = { func: function func() { var rotDelta = wall.rotation - prevRotation, newCenter = new Phaser.Math.Vector2(wall.x - this.bouncy.x, wall.y - this.bouncy.y), rotateMatrix = new Phaser.Math.Matrix3; rotateMatrix.fromArray([Math.cos(rotDelta), Math.sin(rotDelta), 0, -Math.sin(rotDelta), Math.cos(rotDelta), 0, 0, 0]); newCenter.transformMat3(rotateMatrix); newCenter.add(new Phaser.Math.Vector2(this.bouncy.x, this.bouncy.y)); prevRotation = wall.rotation; wall.x = newCenter.x; wall.y = newCenter.y }, scope: this, params: [rotTween] }; if (wall.collider) { rotTween.callbacks.onComplete = { func: function func() { PlainCollider.rotateCollider(wall, -Math.PI / 2, new Phaser.Math.Vector2(this.bouncy.x, this.bouncy.y)); if (wall.__proto__.constructor === LavaWall) { wall.endRotation() } }, scope: this, params: [rotTween] } } if (wall.__proto__.constructor === LavaWall) { wall.startRotation(-Math.PI / 2, new Phaser.Math.Vector2(this.bouncy.x, this.bouncy.y)) } }, this); var mainWall = this.maze.children.entries[0]; if (this.game.device.os.desktop) var scale = Math.min(this.cameras.main.width / Math.abs((mainWall.width + 80) * Math.cos(mainWall.rotation + Math.PI / 2) + (mainWall.height + 80) * Math.sin(mainWall.rotation + Math.PI / 2)), this.cameras.main.height / Math.abs((mainWall.width + 80) * Math.sin(mainWall.rotation + Math.PI / 2) + (mainWall.height + 80) * Math.cos(mainWall.rotation + Math.PI / 2))); else var scale = Math.min(this.cameras.main.width / Math.abs((mainWall.width + 120) * Math.cos(mainWall.rotation + Math.PI / 2) + (mainWall.height + this.buttonsFrame.displayHeight + 40) * Math.sin(mainWall.rotation + Math.PI / 2)), this.cameras.main.height / Math.abs((mainWall.width + 120) * Math.sin(mainWall.rotation + Math.PI / 2) + (mainWall.height + this.buttonsFrame.displayHeight + 40) * Math.cos(mainWall.rotation + Math.PI / 2))); var zoomTween = this.tweens.add({ targets: this.cameras.main, props: { zoom: { value: scale, ease: "Linear" } }, duration: 900 }); this.time.delayedCall(1100, this.unfreezeAfterRotation, [], this); if (this.jetSound.isPlaying) this.jetSound.pause(); this.rotateSound.play(); this.stopBouncyThrust() } else { this.pendingAction = this.rotateMazeLeftTween } } }, { key: "freezeForRotation", value: function freezeForRotation() { this.freezed = true } }, { key: "unfreezeAfterRotation", value: function unfreezeAfterRotation() { this.freezed = false; this.bouncy.vel = new Phaser.Math.Vector2; this.maze.children.each(function(entity) { entity.vel = new Phaser.Math.Vector2; if (entity.__proto__.constructor === FuelCan) { entity.rotation = 0 } }, this); if (this.pendingAction) { this.pendingAction.call(this); this.pendingAction = false } } }, { key: "restartScene", value: function restartScene() { this.anims.remove("idle"); this.anims.remove("fly"); this.anims.remove("shock"); this.anims.remove("rocketLaunch"); this.anims.remove("dustSplash"); this.anims.remove("flashMain"); this.anims.remove("main"); if (this.game.levelNumber > this.game.lastAvailLevel) { this.game.lastAvailLevel = this.game.levelNumber; localStorage.setItem("rocketateLevelNumber", this.game.lastAvailLevel) } wallGenerator.clearTextures(); this.scene.restart() } }, { key: "switchContinuousThrust", value: function switchContinuousThrust() { this.continuousThrust = !this.continuousThrust } }, { key: "thrustBouncy", value: function thrustBouncy() { if (this.tutThrust && this.tutThrust.alpha > 0) { this.tutThrust.alpha = 0 } if (this.bouncy.currentFuel > 0) { if (this.bouncy.fromGroundLaunch) { this.bouncy.vel.y -= 3; this.rocketLaunch.setPosition(this.bouncy.x - this.bouncy.displayWidth * .3, this.bouncy.y + this.bouncy.displayHeight * .5); this.rocketLaunch.rotation = 0; this.rocketLaunch.alpha = 1; this.rocketLaunch.play("rocketLaunch") } else { this.bouncy.vel.y -= .6 } if (this.bouncy.thrustSprite) { if (this.bouncy.thrustAnimation.paused) { this.bouncy.thrustSprite.play("main"); this.bouncy.thrustAnimation.resume() } } else { if (!this.bouncy.engineEmitter.on) { this.bouncy.engineEmitter.setPosition(this.bouncy.x - this.bouncy.displayWidth * .25, this.bouncy.y + this.bouncy.displayHeight * .5); this.bouncy.engineEmitter.start() } } this.bouncy.currentFuel = Math.max(0, this.bouncy.currentFuel - .5); var fuelBarHeight = this.bouncy.currentFuel / this.bouncy.fuelCapacity * 80; this.fuelLevel.setCrop(0, 80 - fuelBarHeight, 80, fuelBarHeight); if (!this.jetSound.isPlaying) { this.jetSound.play() } } if (this.bouncy.currentFuel <= 50 && !this.fuelSpawned) { this.spawnFuel(); this.fuelSpawned = true } if (this.bouncy.flyAnimation.paused) { this.bouncy.idleAnimation.pause(); this.bouncy.play("fly"); this.bouncy.flyAnimation.resume() } } }, { key: "hideLaunch", value: function hideLaunch() { this.rocketLaunch.alpha = 0 } }, { key: "tankUpBouncy", value: function tankUpBouncy() { var fuelBarHeight = this.bouncy.currentFuel / this.bouncy.fuelCapacity * 80; this.fuelLevel.setCrop(0, 80 - fuelBarHeight, 80, fuelBarHeight); this.fuelSpawned = false; this.fuelSound.play() } }, { key: "spawnFuel", value: function spawnFuel() { var bouncyPos = new Phaser.Math.Vector2(this.bouncy.x, this.bouncy.y); var spawnSpot = this.respawnFuelSpots.reduce(function(curr, acc, arr) { if (bouncyPos.distance(curr) > bouncyPos.distance(acc)) return curr; return acc }, this.respawnFuelSpots[0]); var fuelCan = new FuelCan(this, spawnSpot.x, spawnSpot.y); PlainCollider.addObject(fuelCan, fuelCan.vertices); PlainCollider.assignCollGroup(fuelCan, "fuelCanCollGroup"); fuelCan.collWith = [this.bouncyCollGroup]; this.maze.add(fuelCan); PlainCollider.injectObjectInPairs(fuelCan) } }, { key: "stopBouncyThrust", value: function stopBouncyThrust() { if (!this.game.device.os.desktop && (this.bouncy.thrustSprite ? this.bouncy.thustSprite === 1 : this.bouncy.engineEmitter.on) && this.bouncy.vel.y > -.1) { this.freezed = true; this.time.delayedCall(500, function() { this.freezed = false; if (this.pendingAction) { this.pendingAction.call(this); this.pendingAction = false } }, [], this) } if (this.bouncy.thrustSprite) { if (!this.bouncy.thrustAnimation.paused) { this.bouncy.thrustSprite.alpha = 0; this.bouncy.thrustAnimation.pause() } } else { if (this.bouncy.engineEmitter.on) { this.bouncy.engineEmitter.stop() } } if (this.bouncy.flyAnimation && !this.bouncy.flyAnimation.paused) { this.bouncy.flyAnimation.pause(); this.bouncy.play("idle"); this.bouncy.idleAnimation.resume(); if (this.jetSound.isPlaying) { this.jetSound.pause() } } } }, { key: "makeButton", value: function makeButton(imageKey, text, posX, posY, callback) { var button = this.add.image(posX, posY, imageKey, "out").setInteractive(); button.setDepth(101); button.on("pointerdown", function() { this.buttonSound.play(); button.setFrame("down"); callback.call(this) }, this); button.on("pointerup", function() { button.setFrame("out") }, this); var buttonLabel = this.add.bitmapText(button.x, button.y, "basicFont", text, 16); buttonLabel.setDepth(102); return button } }, { key: "makePressButton", value: function makePressButton(imageKey, text, posX, posY, callback) { var button = this.add.image(posX, posY, imageKey, "out").setInteractive(); button.setDepth(101); button.on("pointerdown", function() { this.buttonSound.play(); button.setFrame("down"); callback.call(this) }, this); button.on("pointerup", function() { if (this.continuousThrust) { button.setFrame("out"); callback.call(this) } }, this); var buttonLabel = this.add.bitmapText(button.x, button.y, "basicFont", text, 16); buttonLabel.setDepth(102); return button } }, { key: "makeMuteButton", value: function makeMuteButton(imageKey, text, posX, posY) { if (this.sound.mute) { var startFrame = "muteOffOut" } else { var startFrame = "muteOnOut" } var button = this.add.image(posX, posY, imageKey, startFrame).setInteractive(); button.setDepth(101); button.on("pointerdown", function() { if (this.sound.mute) { button.setFrame("muteOffDown") } else { button.setFrame("muteOnDown") } this.buttonSound.play() }, this); button.on("pointerup", function() { if (this.sound.mute) { this.sound.mute = false; button.setFrame("muteOnOut") } else { this.sound.mute = true; button.setFrame("muteOffOut") } }, this); var buttonLabel = this.add.bitmapText(button.x, button.y, "basicFont", text, 16); buttonLabel.setDepth(102); return button } }, { key: "showMoreGames", value: function showMoreGames() { window.open("Enter here more games link", "_blank") } }, { key: "showWinPopup", value: function showWinPopup() { if (this.winPopup.alpha === 0) { GameAnalytics("addProgressionEvent", "Complete", "level" + this.game.levelNumber); this.winSound.play(); this.winPopup.alpha = 1; this.nextLevelButton.setInteractive(); this.replayButton.setInteractive(); this.moreGamesButton.setInteractive(); this.freezed = true; this.pauseButton.disableInteractive() } } }, { key: "showLosePopup", value: function showLosePopup(animation, frame) { if (animation.key === "shock" && this.losePopup.alpha === 0) { GameAnalytics("addProgressionEvent", "Fail", "level" + this.game.levelNumber); this.loseSound.play(); this.losePopup.alpha = 1; this.loseReplayButton.setInteractive(); this.freezed = true; this.pauseButton.disableInteractive() } } }, { key: "launchNextLevel", value: function launchNextLevel() { this.winPopup.alpha = 0; this.nextLevelButton.disableInteractive(); this.replayButton.disableInteractive(); this.moreGamesButton.disableInteractive(); this.game.levelNumber++; this.restartScene() } }, { key: "replayLevel", value: function replayLevel() { this.winPopup.alpha = 0; this.losePopup.alpha = 0; this.pausePopup.alpha = 0; this.nextLevelButton.disableInteractive(); this.replayButton.disableInteractive(); this.moreGamesButton.disableInteractive(); this.loseReplayButton.disableInteractive(); this.pauseReplayButton.disableInteractive(); this.pauseContinueButton.disableInteractive(); this.pauseMuteButton.disableInteractive(); this.restartScene() } }, { key: "pauseGame", value: function pauseGame() { this.pausePopup.alpha = 1; this.pauseButton.disableInteractive(); this.pauseReplayButton.setInteractive(); this.pauseContinueButton.setInteractive(); this.pauseMuteButton.setInteractive(); this.freezed = true } }, { key: "continueGame", value: function continueGame() { this.pausePopup.alpha = 0; this.pauseButton.setInteractive(); this.pauseReplayButton.disableInteractive(); this.pauseContinueButton.disableInteractive(); this.pauseMuteButton.disableInteractive(); this.freezed = false } }, { key: "respondLandscape", value: function respondLandscape() { this.playPortrait.alpha = 1 } }, { key: "respondPortrait", value: function respondPortrait() { this.playPortrait.alpha = 0 } }, { key: "goLevelChoice", value: function goLevelChoice() { this.anims.remove("idle"); this.anims.remove("fly"); this.anims.remove("shock"); this.anims.remove("rocketLaunch"); this.anims.remove("dustSplash"); this.anims.remove("flashMain"); this.anims.remove("main"); wallGenerator.clearTextures(); this.time.delayedCall(200, function() { this.scene.start("LevelChoiceScene") }, [], this) } }, { key: "update", value: function update(time, delta) { if (this.playing) { if (!this.freezed) { PlainCollider.checkCollisions(); PlainCollider.moveAll(); if (this.leftKey.isDown) { this.rotateMazeRightTween() } else if (this.rightKey.isDown) { this.rotateMazeLeftTween() } else if (this.upKey.isDown && this.game.device.os.desktop) { this.thrustBouncy() } if (this.bouncy.thrustSprite) { if (!this.bouncy.thrustAnimation.paused) { if (this.bouncy.thrustSprite.alpha === 0) this.bouncy.thrustSprite.alpha = 1; this.bouncy.thrustSprite.setPosition(this.bouncy.x - this.bouncy.displayWidth * .25, this.bouncy.y + this.bouncy.displayHeight * .5) } } else { if (this.bouncy.engineEmitter.on) { this.bouncy.engineEmitter.setPosition(this.bouncy.x - this.bouncy.displayWidth * .25, this.bouncy.y + this.bouncy.displayHeight * .5) } } if (!this.game.device.os.desktop) { if (this.continuousThrust) { this.thrustBouncy(delta); var pointerPos = this.input.activePointer.positionToCamera(this.HUDCamera); if (!this.thrustButton.getBounds().contains(pointerPos.x, pointerPos.y)) { this.continuousThrust = false; this.thrustButton.setFrame("out") } } else { this.stopBouncyThrust() } } if (!this.upKey.isDown && this.game.device.os.desktop) { this.stopBouncyThrust() } this.bouncy.update(); this.maze.children.each(function(entity) { if (entity.__proto__.constructor != Floor) { entity.update() } }, this); var toFinishVec = new Phaser.Math.Vector2(this.bouncy.x - this.finish.x, this.bouncy.y - this.finish.y); if (this.bouncy.inLava) { this.bouncy.inLava = false; if (!this.bouncy.inShock) { this.bouncy.play("shock"); this.shockSound.play(); this.bouncy.inShock = true } } if (toFinishVec.length() < 40 && !this.bouncy.inShock) { if (this.game.levelNumber < this.game.totalLevels && this.game.levelNumber > 0) { this.showWinPopup() } else if (this.game.levelNumber === this.game.totalLevels) { this.showFinalPopup() } } PlainCollider.updateObjectsIds() } if (this.rKey.isDown) { if (this.losePopup.alpha == 1 || this.winPopup.alpha == 1 || this.pausePopup.alpha == 1) { this.replayLevel() } } if (this.nKey.isDown) { if (this.winPopup.alpha == 1) { this.launchNextLevel() } } this.floor.update() } } }]); return PlayScene }(Phaser.Scene); if (Array.prototype.equals) console.warn("Overriding existing Array.prototype.equals. Possible causes: New API defines the method, there's a framework conflict or you've got double inclusions in your code."); Array.prototype.equals = function(array) { if (!array) return false; if (this.length != array.length) return false; for (var i = 0, l = this.length; i < l; i++) { if (this[i] instanceof Array && array[i] instanceof Array) { if (!this[i].equals(array[i])) return false } else if (typeof this[i] === "number" && typeof array[i] === "number") { if (Math.abs(this[i] - array[i]) > .01) { return false } } else if (this[i] != array[i]) { return false } } return true }; Object.defineProperty(Array.prototype, "equals", { enumerable: false }) }, 1160: function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor) } } return function(Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor } }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function") } } var SAT = __webpack_require__(1161); var Pair = exports.Pair = function() { function Pair(object1, object2, plainCollider) { _classCallCheck(this, Pair); this.object1 = object1; this.object2 = object2; this.object1.on("destroy", this.remove, this); this.object2.on("destroy", this.remove, this); this.plainCollider = plainCollider; this.collisionChecked = false; this.previouslyCollided = false; this.nowCollided = false; this.checksInIteration = 0 } _createClass(Pair, [{ key: "checkPairCollision", value: function checkPairCollision() { this.collisionChecked = true; this.checksInIteration++; if (this.object1.collWith.indexOf(this.object2.collGroup) >= 0 && this.object2.collWith.indexOf(this.object1.collGroup) >= 0) { for (var b1 = 0; b1 < this.object1.collider.length; b1++) { for (var b2 = 0; b2 < this.object2.collider.length; b2++) { var collision = { collided: false }; var body1 = this.object1.collider[b1], body2 = this.object2.collider[b2]; var bounds1 = this.getBoundsOfBody(body1), bounds2 = this.getBoundsOfBody(body2); bounds1.x += this.object1.vel.x + this.object1.lastCorrection.x; bounds2.x += this.object2.vel.x + this.object2.lastCorrection.x; bounds1.y += this.object1.vel.y + this.object1.lastCorrection.y; bounds2.y += this.object2.vel.y + this.object2.lastCorrection.y; if (Phaser.Geom.Rectangle.Overlaps(bounds1, bounds2)) { var intentCollider1 = body1.map(function(segment) { return { point: segment.point.clone(), direction: segment.direction.clone(), normal: segment.normal.clone() } }, this); intentCollider1.forEach(function(segment) { segment.point.add(this.object1.vel); segment.point.add(this.object1.lastCorrection) }, this); var intentCollider2 = body2.map(function(segment) { return { point: segment.point.clone(), direction: segment.direction.clone(), normal: segment.normal.clone() } }, this); intentCollider2.forEach(function(segment) { segment.point.add(this.object2.vel); segment.point.add(this.object2.lastCorrection) }, this); collision = SAT.findIntersection(intentCollider1, intentCollider2) } if (collision.collided && this.checksInIteration < 10) { if (collision.point1.length === 2 && collision.point2.length === 2) { this.nowCollided = true; var length1 = collision.point1[0].distance(collision.point1[1]), length2 = collision.point2[0].distance(collision.point2[1]); if (length1 < length2) { var colPoint1 = collision.point1[0], colPoint2 = collision.point1[1] } else { var colPoint1 = collision.point2[0], colPoint2 = collision.point2[1] } var spreadVec1 = colPoint1.clone().subtract(colPoint2).normalize(), spreadVec2 = colPoint2.clone().subtract(colPoint1).normalize() } if (this.object1.movability > this.object2.movability) { if (this.reporting) { console.log("case 1") } var correctionVec = collision.pushOutVec; var resCorrection = this.object1.velCorrection(correctionVec, collision.point1, collision.normal, this.object2, this); if (resCorrection.vector.length() > 0) { resCorrection.vector.scale(-1); this.object2.velCorrection(resCorrection.vector, collision.point2, collision.normal.clone().scale(-1), this.object1, this, resCorrection.ultimate) } } else if (this.object1.movability < this.object2.movability) { if (this.reporting) { console.log("case 2") } var correctionVec = collision.pushOutVec.scale(-1); var resCorrection = this.object2.velCorrection(correctionVec, collision.point2, collision.normal, this.object1, this); if (resCorrection.vector.length() > 0) { resCorrection.vector.scale(-1); this.object1.velCorrection(resCorrection.vector, collision.point1, collision.normal, this.object2, this, resCorrection.ultimate) } if (this.reporting) { console.log("collision object"); console.log(collision); console.log(intentCollider1); console.log(intentCollider2) } } else { if (this.reporting) { console.log("########equal movability###########") } if (this.object1.lastCorrPriority > this.object2.lastCorrPriority) { var correctionVec = collision.pushOutVec; var resCorrection = this.object1.velCorrection(correctionVec, collision.point1, collision.normal, this.object2, this); if (resCorrection.vector.length() > 0) { resCorrection.vector.scale(-1); this.object2.velCorrection(resCorrection.vector, collision.point2, collision.normal, this.object1, this, resCorrection.ultimate) } if (this.reporting) { console.log("object 1"); console.log(this.object1.vel); console.log(this.object1.lastCorrection); console.log("object 2"); console.log(this.object2.vel); console.log(this.object2.lastCorrection) } } else { var correctionVec = collision.pushOutVec.scale(-1); var resCorrection = this.object2.velCorrection(correctionVec, collision.point2, collision.normal, this.object1, this); if (resCorrection.vector.length() > 0) { resCorrection.vector.scale(-1); this.object1.velCorrection(resCorrection.vector, collision.point1, collision.normal, this.object2, this, resCorrection.ultimate) } if (this.reporting) { console.log("_________start from pair"); console.log("no corr prioroty"); console.log(correctionVec); console.log(resCorrection); console.log("object 1"); console.log(this.object1.vel); console.log(this.object1.lastCorrection); console.log(this.object1.constraints); console.log("object 2"); console.log(this.object2.vel); console.log(this.object2.lastCorrection); console.log(this.object1.constraints); console.log("_________end from pair") } } } return true } else if (this.checksInIteration >= 10) { this.object1.vel = new Phaser.Math.Vector2; this.object2.vel = new Phaser.Math.Vector2 } } } } return false } }, { key: "remove", value: function remove(destroyedObject) { this.plainCollider.removeObject(destroyedObject); this.object1 = undefined; this.object2 = undefined } }, { key: "updateCollisionStatus", value: function updateCollisionStatus() { this.previouslyCollided = this.nowCollided; this.nowCollided = false; this.collisionChecked = false; this.checksInIteration = 0 } }, { key: "getBoundsOfBody", value: function getBoundsOfBody(body) { var leftMostX = body.reduce(function(acc, curr, arr) { if (acc > curr.point.x) { return curr.point.x } return acc }, body[0].point.x), rightMostX = body.reduce(function(acc, curr, arr) { if (acc < curr.point.x) { return curr.point.x } return acc }, body[0].point.x), topMostY = body.reduce(function(acc, curr, arr) { if (acc > curr.point.y) { return curr.point.y } return acc }, body[0].point.y), bottomMostY = body.reduce(function(acc, curr, arr) { if (acc < curr.point.y) { return curr.point.y } return acc }, body[0].point.y); return new Phaser.Geom.Rectangle(leftMostX, topMostY, rightMostX - leftMostX, bottomMostY - topMostY) } }]); return Pair }(); module.exports = Pair }, 1161: function(module, exports, __webpack_require__) { "use strict"; var SAT = { findIntersection: function(collider1, collider2, report) { var collision = { collided: false, point1: undefined, point2: undefined, pushOutVec: undefined, normal: undefined }; var overlapByAxes = this.findMinOverlap(collider1, collider2); if (overlapByAxes.magnitude < 1e-4) return collision; else { collision.collided = true; collision.point1 = overlapByAxes.pushPoint1.slice(); collision.point2 = overlapByAxes.pushPoint2.slice(); collision.pushOutVec = overlapByAxes.pushOutVec; collision.normal = overlapByAxes.axis } return collision }, findMinOverlapOld: function(colliderAxes, collider, axes) { var minOverlap = { magnitude: this.projectOnAxis(colliderAxes, axes[0]).magnitude, axis: axes[0], pushOutVec: new Phaser.Math.Vector2, pushPoint1: new Phaser.Math.Vector2, pushPoint2: new Phaser.Math.Vector2 }; for (var a = 0; a < axes.length; a++) { var projectionOfColliderAxes = this.projectOnAxis(colliderAxes, axes[a]), projectionOfCollider = this.projectOnAxis(collider, axes[a]); var currentOverlap = this.findOverlap(projectionOfColliderAxes, projectionOfCollider); if (currentOverlap === 0) { return { magnitude: 0, axis: axes[a], penetrationPoint: undefined } } else { if (currentOverlap < minOverlap.magnitude) { var pushOut = this.findPushOutVec(projectionOfColliderAxes, projectionOfCollider, axes[a]), minOverlap = { magnitude: currentOverlap, axis: axes[a], pushOutVec: pushOut.pushOutVec, pushPoint1: pushOut.point1, pushPoint2: pushOut.point2 } } } } return minOverlap }, findMinOverlap: function(collider1, collider2) { var axes = [new Phaser.Math.Vector2(1, 0), new Phaser.Math.Vector2(0, 1)], southEast = false, northEast = false; for (var s = 0; s < collider1.length; s++) { var dir = collider1[s].direction.clone(); if (dir.x != 0 && dir.y != 0) { if (dir.x * dir.y > 0 && !northEast) { axes.push(new Phaser.Math.Vector2(1 / Math.sqrt(2), -1 / Math.sqrt(2))); northEast = true } else if (!southEast) { axes.push(new Phaser.Math.Vector2(1 / Math.sqrt(2), 1 / Math.sqrt(2))); southEast = true } } } if (!northEast || !southEast) { for (var s = 0; s < collider2.length; s++) { var dir = collider2[s].direction.clone(); if (dir.x != 0 && dir.y != 0) { if (dir.x * dir.y > 0 && !northEast) { axes.push(new Phaser.Math.Vector2(1 / Math.sqrt(2), -1 / Math.sqrt(2))); northEast = true } else if (!southEast) { axes.push(new Phaser.Math.Vector2(1 / Math.sqrt(2), 1 / Math.sqrt(2))); southEast = true } } } } var minOverlap = { magnitude: this.projectOnAxis(collider1, axes[0]).magnitude, axis: axes[0], pushOutVec: new Phaser.Math.Vector2, pushPoint1: [], pushPoint2: [] }; for (var a = 0; a < axes.length; a++) { var projectionOfCollider1 = this.projectOnAxis(collider1, axes[a]), projectionOfCollider2 = this.projectOnAxis(collider2, axes[a]); var currentOverlap = this.findOverlap(projectionOfCollider1, projectionOfCollider2); if (currentOverlap === 0) { return { magnitude: 0, axis: axes[a], penetrationPoint: undefined } } else { var pushOut = this.findPushOutVec(projectionOfCollider1, projectionOfCollider2, axes[a]); if (currentOverlap < minOverlap.magnitude) { minOverlap.magnitude = currentOverlap; minOverlap.axis = axes[a]; minOverlap.pushPoint1 = pushOut.point1; minOverlap.pushPoint2 = pushOut.point2 } if (axes[a].y === 0) { minOverlap.pushOutVec.x = pushOut.pushOutVec.x } else if (axes[a].x === 0) { minOverlap.pushOutVec.y = pushOut.pushOutVec.y } } } return minOverlap }, projectOnAxis: function(collider, axis) { var minProj = collider[0].point.dot(axis), maxProj = collider[0].point.dot(axis), minPoint = [collider[0].point], maxPoint = [collider[0].point]; for (var s = 1; s < collider.length; s++) { var currentProj = collider[s].point.dot(axis); if (currentProj > maxProj) { maxProj = currentProj; maxPoint[0] = collider[s].point } else if (Math.abs(currentProj - maxProj) < 1) { maxPoint[1] = collider[s].point } if (currentProj < minProj) { minProj = currentProj; minPoint[0] = collider[s].point } else if (Math.abs(currentProj - minProj) < 1) { minPoint[1] = collider[s].point } } return { min: minProj, max: maxProj, minPoint: minPoint, maxPoint: maxPoint, magnitude: maxProj - minProj } }, findPushOutVec: function(proj1, proj2, axis) { var pushOutVec = axis.clone(); if (proj1.max > proj2.max) { if (proj1.min > proj2.min) { pushOutVec.scale(proj2.max - proj1.min); return { pushOutVec: pushOutVec, point1: proj1.minPoint, point2: proj2.maxPoint } } else { pushOutVec.scale(proj2.min - proj1.max); return { pushOutVec: pushOutVec, point1: proj1.maxPoint, point2: proj2.minPoint } } } else { if (proj1.min > proj2.min) { pushOutVec.scale(proj2.max - proj1.min); return { pushOutVec: pushOutVec, point1: proj1.minPoint, point2: proj2.maxPoint } } else { pushOutVec.scale(proj2.min - proj1.max); return { pushOutVec: pushOutVec, point1: proj1.maxPoint, point2: proj2.minPoint } } } }, findOverlap: function(projection1, projection2) { if (projection1.min <= projection2.max && projection1.max > projection2.min) { return Math.min(projection2.max - projection1.min, projection1.max - projection2.min, projection1.max - projection1.min, projection2.max - projection1.min) } else { return 0 } } }; module.exports = SAT }, 1162: function(module, exports, __webpack_require__) { "use strict"; var defineOuterVertices = function defineOuterVertices(wallEdges) { var outerSegments = defineOuterSegments(wallEdges); var vertexArray = [], idleRun = 0; vertexArray = vertexArray.concat([outerSegments[0][0], outerSegments[0][1]]); outerSegments.splice(0, 1); while (outerSegments.length > 0 && idleRun < 3) { var lastVertex = vertexArray[vertexArray.length - 1], nextSegment = [], nextSegmentIndex = -1, nextVertexIndex = -1; outerSegments.forEach(function(segment, index, arr) { if (lastVertex.equals(segment[0])) { nextSegment = segment; nextSegmentIndex = index; nextVertexIndex = 1 } else if (lastVertex.equals(segment[1])) { nextSegment = segment; nextSegmentIndex = index; nextVertexIndex = 0 } }, this); if (nextSegmentIndex >= 0) { vertexArray.push(nextSegment[nextVertexIndex]); outerSegments.splice(nextSegmentIndex, 1) } else { idleRun++ } } return vertexArray }; var defineOuterSegments = function defineOuterSegments(edges) { var segments = []; for (var e in edges) { for (var v in edges[e]) { if (Number(v) < 4) { var nextV = Number(v) < 3 ? Number(v) + 1 : 0; segments.push([edges[e][v], edges[e][nextV]]) } } } var innerSegments = []; segments.forEach(function(seg1, index1, segArr1) { segArr1.forEach(function(seg2, index2, segArr2) { if (index2 > index1) { if (seg1[0].equals(seg2[0]) && seg1[1].equals(seg2[1]) || seg1[0].equals(seg2[1]) && seg1[1].equals(seg2[0])) { innerSegments.push(seg1) } } }, this) }, this); var candidateOuterSegments = segments.filter(function(segment) { var inner = false; innerSegments.forEach(function(innerSegment) { if (!inner) { if (innerSegment[0].equals(segment[0]) && innerSegment[1].equals(segment[1]) || innerSegment[1].equals(segment[0]) && innerSegment[0].equals(segment[1])) { inner = true } } }, this); return !inner }, this); var points = []; candidateOuterSegments.forEach(function(segment) { points = points.concat(segment) }, this); var points4T = []; points.forEach(function(point1, index1, pointsArr1) { var occurance = 0; pointsArr1.forEach(function(point2, index2, pointsArr2) { if (index2 >= index1) { if (point1.equals(point2)) occurance++ } }, this); if (occurance >= 4) points4T.push(point1) }, this); var innerSegments = []; points4T.forEach(function(point) { candidateOuterSegments.forEach(function(segment) { if (segment[0].equals(point)) { points4T.forEach(function(otherPoint) { if (segment[1].equals(otherPoint) && Math.sqrt(Math.pow(segment[1][0] - segment[0][0], 2) + Math.pow(segment[1][1] - segment[0][1], 2)) < 32) { innerSegments.push(segment) } }, this) } }, this) }, this); var outerSegmentsArray = candidateOuterSegments.filter(function(segment) { for (var iSeg in innerSegments) { if (innerSegments[iSeg].equals(segment)) return false } return true }, this); return outerSegmentsArray }; module.exports = defineOuterVertices }, 1163: function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor) } } return function(Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor } }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function") } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called") } return call && (typeof call === "object" || typeof call === "function") ? call : self } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass) } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass } var GWall = __webpack_require__(470); var wallGenerator = __webpack_require__(73); var FreeDoor = exports.FreeDoor = function(_GWall) { _inherits(FreeDoor, _GWall); function FreeDoor() { _classCallCheck(this, FreeDoor); return _possibleConstructorReturn(this, (FreeDoor.__proto__ || Object.getPrototypeOf(FreeDoor)).apply(this, arguments)) } _createClass(FreeDoor, [{ key: "drawTexture", value: function drawTexture(scene, edgeVertices, wallWidth, wallHeight) { return wallGenerator.generateFreeDoor(scene, edgeVertices, wallWidth, wallHeight) } }]); return FreeDoor }(GWall); module.exports = FreeDoor }, 1164: function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor) } } return function(Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor } }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function") } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called") } return call && (typeof call === "object" || typeof call === "function") ? call : self } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass) } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass } var WoodBox = __webpack_require__(471); var wallGenerator = __webpack_require__(73); var MetalBox = exports.MetalBox = function(_WoodBox) { _inherits(MetalBox, _WoodBox); function MetalBox(scene, edges, wallNumber) { _classCallCheck(this, MetalBox); var _this = _possibleConstructorReturn(this, (MetalBox.__proto__ || Object.getPrototypeOf(MetalBox)).call(this, scene, edges, wallNumber)); _this.movability = 1; _this.lastCorrPriority = _this.movability; return _this } _createClass(MetalBox, [{ key: "prepareTexture", value: function prepareTexture() { return "metalBox" } }]); return MetalBox }(WoodBox); module.exports = MetalBox }, 1165: function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function") } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called") } return call && (typeof call === "object" || typeof call === "function") ? call : self } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass) } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass } var Finish = exports.Finish = function(_Phaser$GameObjects$S) { _inherits(Finish, _Phaser$GameObjects$S); function Finish(scene, posX, posY) { _classCallCheck(this, Finish); var _this = _possibleConstructorReturn(this, (Finish.__proto__ || Object.getPrototypeOf(Finish)).call(this, scene, posX, posY, "finish")); scene.add.existing(_this); _this.setDepth(9); return _this } return Finish }(Phaser.GameObjects.Sprite); module.exports = Finish }, 1166: function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor) } } return function(Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor } }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function") } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called") } return call && (typeof call === "object" || typeof call === "function") ? call : self } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass) } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass } var Floor = exports.Floor = function(_Phaser$GameObjects$I) { _inherits(Floor, _Phaser$GameObjects$I); function Floor(scene, vertices, wallNumber) { _classCallCheck(this, Floor); var tint = 15132128; var leftBorder = vertices.reduce(function(acc, currentVer) { if (acc > currentVer[0]) { return currentVer[0] } return acc }, vertices[0][0]), rightBorder = vertices.reduce(function(acc, currentVer) { if (acc < currentVer[0]) { return currentVer[0] } return acc }, vertices[0][0]), topBorder = vertices.reduce(function(acc, currentVer) { if (acc > currentVer[1]) { return currentVer[1] } return acc }, vertices[0][1]), bottomBorder = vertices.reduce(function(acc, currentVer) { if (acc < currentVer[1]) { return currentVer[1] } return acc }, vertices[0][1]), floorWidth = rightBorder - leftBorder, floorHeight = bottomBorder - topBorder; if (scene.game.renderer.type === 1) { var floorGraphics = scene.make.graphics({ fillStyle: { color: 9275053 } }); var alignedVertices = vertices.map(function(vertex) { return [vertex[0] - leftBorder, vertex[1] - topBorder] }); floorGraphics.clear(); floorGraphics.save(); floorGraphics.beginPath(); floorGraphics.moveTo(alignedVertices[0][0], alignedVertices[0][1]); for (var v = 1; v < alignedVertices.length; v++) { floorGraphics.lineTo(alignedVertices[v][0], alignedVertices[v][1]) } floorGraphics.closePath(); floorGraphics.fillPath(); floorGraphics.restore(); if (scene.textures.exists("floorGraphics")) { scene.textures.remove("floorGraphics") } floorGraphics.generateTexture("floorGraphics", floorWidth, floorHeight); var _this = _possibleConstructorReturn(this, (Floor.__proto__ || Object.getPrototypeOf(Floor)).call(this, scene, leftBorder, topBorder, "floorGraphics")); scene.add.existing(_this) } else { var _this = _possibleConstructorReturn(this, (Floor.__proto__ || Object.getPrototypeOf(Floor)).call(this, scene, leftBorder, topBorder, "levelFloor")); _this.floorGraphics = scene.make.graphics({ fillStyle: { color: 9275053 } }); var alignedVertices = vertices.map(function(vertex) { return [vertex[0] - leftBorder, vertex[1] - topBorder] }); _this.floorGraphics.clear(); _this.floorGraphics.save(); _this.floorGraphics.beginPath(); _this.floorGraphics.moveTo(alignedVertices[0][0], alignedVertices[0][1]); for (var v = 1; v < alignedVertices.length; v++) { _this.floorGraphics.lineTo(alignedVertices[v][0], alignedVertices[v][1]) } _this.floorGraphics.closePath(); _this.floorGraphics.fillPath(); _this.floorGraphics.restore(); _this.mask = new Phaser.Display.Masks.GeometryMask(scene, _this.floorGraphics); scene.add.existing(_this) } _this.setOrigin(0); _this.setDepth(0); return _this } _createClass(Floor, [{ key: "update", value: function update() { if (this.floorGraphics) { this.floorGraphics.x = this.x; this.floorGraphics.y = this.y; this.floorGraphics.rotation = this.rotation } } }, { key: "drawMask", value: function drawMask() { this.floorGraphics.clear(); this.floorGraphics.save(); this.floorGraphics.beginPath(); this.floorGraphics.moveTo(this.alignedVertices[0][0], this.alignedVertices[0][1]); for (var v = 1; v < this.alignedVertices.length; v++) { this.floorGraphics.lineTo(this.alignedVertices[v][0], this.alignedVertices[v][1]) } this.floorGraphics.closePath(); this.floorGraphics.fillPath(); this.floorGraphics.restore() } }, { key: "rotateVertices", value: function rotateVertices(pointX, pointY, angle) { this.vertices.forEach(function(vertex) { var oldX = vertex[0] - pointX, oldY = vertex[1] - pointY; var newX = oldX * Math.cos(angle) - oldY * Math.sin(angle) + pointX, newY = oldX * Math.sin(angle) + oldY * Math.cos(angle) + pointY; vertex = [newX, newY] }, this) } }, { key: "rotateMask", value: function rotateMask(pointX, pointY, angle) { this.rotateVertices(pointX, pointY, angle); this.drawMask() } }]); return Floor }(Phaser.GameObjects.Image); module.exports = Floor }, 1167: function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor) } } return function(Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor } }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function") } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called") } return call && (typeof call === "object" || typeof call === "function") ? call : self } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass) } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass } var Bouncy = __webpack_require__(472); var FuelCan = exports.FuelCan = function(_Phaser$GameObjects$S) { _inherits(FuelCan, _Phaser$GameObjects$S); function FuelCan(scene, xPos, yPos) { _classCallCheck(this, FuelCan); var _this = _possibleConstructorReturn(this, (FuelCan.__proto__ || Object.getPrototypeOf(FuelCan)).call(this, scene, xPos, yPos, "fuelCan")); scene.add.existing(_this); var topLeft = _this.getTopLeft(), bottomRight = _this.getBottomRight(); _this.vertices = [ [ [topLeft.x, topLeft.y], [bottomRight.x, topLeft.y], [bottomRight.x, bottomRight.y], [topLeft.x, bottomRight.y] ] ]; _this.vel = new Phaser.Math.Vector2; _this.movability = 2; _this.velCorrected = false; _this.lastCorrection = new Phaser.Math.Vector2; _this.lastCorrPriority = _this.movability; _this.resolvedPairs = []; _this.unresolvedPairs = []; _this.inLava = false; _this.setDepth(10); _this.capacity = 50; _this.toDestroy = false; return _this } _createClass(FuelCan, [{ key: "velCorrection", value: function velCorrection(correction, point, normal, otherObject, pair) { var ultimatePushBack = { x: false, y: false }; if (otherObject.__proto__.constructor === Bouncy) { otherObject.tankUp(this.capacity); this.toDestroy = true } this.lastCorrection = correction; return { vector: new Phaser.Math.Vector2, ultimate: ultimatePushBack } } }, { key: "updateVel", value: function updateVel() { this.vel.add(this.lastCorrection) } }, { key: "update", value: function update() { if (this.toDestroy) this.destroy() } }]); return FuelCan }(Phaser.GameObjects.Sprite); module.exports = FuelCan }, 1168: function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor) } } return function(Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor } }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function") } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called") } return call && (typeof call === "object" || typeof call === "function") ? call : self } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass) } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass } var PreloaderScene = exports.PreloaderScene = function(_Phaser$Scene) { _inherits(PreloaderScene, _Phaser$Scene); function PreloaderScene() { _classCallCheck(this, PreloaderScene); return _possibleConstructorReturn(this, (PreloaderScene.__proto__ || Object.getPrototypeOf(PreloaderScene)).call(this, "PreloaderScene")) } _createClass(PreloaderScene, [{ key: "preload", value: function preload() { var gameWidth = this.game.config.width, gameHeight = this.game.config.height; this.add.image(150, 480, "preloaderBack").setOrigin(0, .5); this.playPortrait = this.add.image(gameWidth * .5, gameHeight * .5, "playPortrait"); this.playPortrait.setDepth(200); this.playPortrait.alpha = 0; this.preloaderBar = this.add.image(155, 480, "preloaderBar").setOrigin(0, .5); this.preloaderBar.setCrop(0, 0, 0, 39); this.splashScreen = this.add.image(gameWidth * .5, gameHeight * .5, "splashScreen"); this.splashScreen.setScale(.8); this.splashTween = this.tweens.add({ targets: this.splashScreen, props: { scaleX: { value: 1, ease: "Linear" }, scaleY: { value: 1, ease: "Linear" } }, duration: 1500 }); this.splashTween.setCallback("onComplete", function() { var alphaTween = this.tweens.add({ targets: this.splashScreen, props: { alpha: { value: .2, ease: "Linear" } }, duration: 400 }) }, [], this); this.cameras.main.setBackgroundColor("#2a3343"); this.time.delayedCall(2e3, function() { this.splashScreen.alpha = 0; this.cameras.main.setBackgroundColor("#3d3752") }, [], this); this.load.on("progress", function(value) { this.preloaderBar.setCrop(0, 0, 287 * value, 39) }, this); this.load.atlas("bouncy", "assets/bouncy.png", "assets/bouncy.json"); this.load.atlas("dustSplash", "assets/dustSplash.png", "assets/dustSplash.json"); this.load.atlas("startButton", "assets/startButton.png", "assets/startButton.json"); this.load.atlas("levelButton", "assets/levelButton.png", "assets/levelButton.json"); this.load.atlas("flash", "assets/flash.png", "assets/flash.json"); this.load.atlas("replayButton", "assets/replayButton.png", "assets/replayButton.json"); this.load.atlas("nextLevelButton", "assets/nextLevelButton.png", "assets/nextLevelButton.json"); this.load.atlas("pauseButton", "assets/pauseButton.png", "assets/pauseButton.json"); this.load.atlas("launch", "assets/launch.png", "assets/launch.json"); this.load.atlas("rotateCClButton", "assets/rotateCClButton.png", "assets/rotateCClButton.json"); this.load.atlas("rotateClButton", "assets/rotateClButton.png", "assets/rotateClButton.json"); this.load.atlas("thrustButton", "assets/thrustButton.png", "assets/thrustButton.json"); this.load.atlas("creditsButton", "assets/creditsButton.png", "assets/creditsButton.json"); this.load.atlas("muteButton", "assets/muteButton.png", "assets/muteButton.json"); this.load.atlas("goLevelChoiceButton", "assets/goLevelChoiceButton.png", "assets/goLevelChoiceButton.json"); this.load.atlas("thrustAnim", "assets/thrustAnim.png", "assets/thrustAnim.json"); this.load.atlas("moreGamesButton", "assets/moreGamesButton.png", "assets/moreGamesButton.json"); this.load.image("woodBox", "assets/woodBox.png"); this.load.image("finish", "assets/finish.png"); this.load.image("levelFloor", "assets/levelFloor.png"); this.load.image("mainMenuBack", "assets/mainMenuBack.png"); this.load.image("lockImage", "assets/lock.png"); this.load.image("winPopupBack", "assets/winPopupBack.png"); this.load.image("winPopupImage", "assets/winPopupImage.png"); this.load.image("losePopupBack", "assets/losePopupBack.png"); this.load.image("losePopupImage", "assets/losePopupImage.png"); this.load.image("fuelIndicatorBack", "assets/fuelIndicatorBack.png"); this.load.image("fuelIndicatorLevel", "assets/fuelIndicatorLevel.png"); this.load.image("fuelIndicatorLogo", "assets/fuelIndicatorLogo.png"); this.load.image("mainMenuImage", "assets/mainMenuImage.png"); this.load.image("mainMenuLabel", "assets/mainMenuLabel.png"); this.load.image("pausePopupBack", "assets/pausePopupBack.png"); this.load.image("pausePopupImage", "assets/pausePopupImage.png"); this.load.image("finalPopupImage", "assets/finalPopupImage.png"); this.load.image("levelLabelBack", "assets/levelLabelBack.png"); this.load.image("credits", "assets/credits.png"); this.load.image("tutRotCCl", "assets/tutRotCCl.png"); this.load.image("tutRotCl", "assets/tutRotCl.png"); this.load.image("tutThrust", "assets/tutThrust.png"); this.load.image("mobTutRotCCl", "assets/mobTutRotCCl.png"); this.load.image("mobTutRotCl", "assets/mobTutRotCl.png"); this.load.image("mobTutThrust", "assets/mobTutThrust.png"); this.load.image("engineParticle", "assets/engineTrail.png"); this.load.image("fuelCan", "assets/fuelCan.png"); this.load.image("pressR", "assets/pressR.png"); this.load.image("pressN", "assets/pressN.png"); this.load.bitmapFont("basicFont", "assets/fonts/font.png", "assets/fonts/font.fnt"); this.load.bitmapFont("peachFont", "assets/fonts/fontPeach.png", "assets/fonts/fontPeach.fnt"); this.load.audio("backgroundMusic", "assets/music/background.mp3"); this.load.audio("bumpSound", "assets/music/bump.mp3"); this.load.audio("buttonSound", "assets/music/button.mp3"); this.load.audio("jetSound", "assets/music/jet.mp3"); this.load.audio("loseSound", "assets/music/lose.mp3"); this.load.audio("winSound", "assets/music/win.mp3"); this.load.audio("fuelSound", "assets/music/fuel.mp3"); this.load.audio("rotateSound", ["assets/music/rotate.wav", "assets/music/rotate.mp3"]); this.load.audio("shockSound", "assets/music/shock.mp3"); for (var i = 1; i <= 34; i++) { var levelName = "level" + i, fileName = "assets/levels/rbLevel" + i + ".json"; this.load.json(levelName, fileName) } } }, { key: "respondLandscape", value: function respondLandscape() { this.playPortrait.alpha = 1 } }, { key: "respondPortrait", value: function respondPortrait() { var gameWidth = this.game.config.width, gameHeight = this.game.config.height; this.playPortrait.alpha = 0; this.splashScreen.setPosition(gameWidth * .5, gameHeight * .5) } }, { key: "update", value: function create() { if (this.splashScreen.alpha === 0) this.scene.start("MainMenuScene") } }]); return PreloaderScene }(Phaser.Scene) }, 1169: function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor) } } return function(Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor } }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function") } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called") } return call && (typeof call === "object" || typeof call === "function") ? call : self } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass) } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass } var MainMenuScene = exports.MainMenuScene = function(_Phaser$Scene) { _inherits(MainMenuScene, _Phaser$Scene); function MainMenuScene() { _classCallCheck(this, MainMenuScene); return _possibleConstructorReturn(this, (MainMenuScene.__proto__ || Object.getPrototypeOf(MainMenuScene)).call(this, "MainMenuScene")) } _createClass(MainMenuScene, [{ key: "create", value: function create() { var gameWidth = this.game.config.width, gameHeight = this.game.config.height; this.backgroundImage = this.add.tileSprite(0, 0, gameWidth, gameHeight, "mainMenuBack"); this.backgroundImage.setOrigin(0); this.startButton = this.makeButton("startButton", "", gameWidth * .5, gameHeight * .67, this.startGame); this.titleLabel = this.add.image(gameWidth * .5, gameHeight * .45, "mainMenuLabel"); this.titleImage = this.add.sprite(gameWidth * .5, gameHeight * .25, "mainMenuImage"); this.creditsButton = this.makeButton("creditsButton", "", gameWidth * .13, gameHeight * .9, this.showCredits); this.credits = this.add.image(gameWidth * .5, gameHeight * .45, "credits"); this.credits.alpha = 0; this.credits.setDepth(110); this.muteButton = this.makeMuteButton("muteButton", "", gameWidth * .87, gameHeight * .9); this.playPortrait = this.add.image(gameWidth * .5, gameHeight * .5, "playPortrait"); this.playPortrait.setDepth(200); this.playPortrait.alpha = 0; if (isNaN(localStorage.getItem("rocketateLevelNumber")) || localStorage.getItem("rocketateLevelNumber") === null) { this.game.lastAvailLevel = 1; localStorage.setItem("rocketateLevelNumber", this.game.lastAvailLevel) } else { this.game.lastAvailLevel = Number(localStorage.getItem("rocketateLevelNumber")) } this.buttonSound = this.sound.add("buttonSound"); this.game.backgroundMusic = this.sound.add("backgroundMusic"); this.game.backgroundMusic.play("", { loop: true }); this.input.on("pointerup", function(pointer, gameObjects) { if (gameObjects.length > 0) { for (var i = 0; i < gameObjects.length; i++) { if (gameObjects[i].texture.key === "credits") { this.credits.alpha = 0; this.credits.disableInteractive(); this.startButton.setInteractive(); this.creditsButton.setInteractive() } } } else { this.credits.alpha = 0; this.credits.disableInteractive(); this.startButton.setInteractive(); this.creditsButton.setInteractive() } }, this) } }, { key: "makeButton", value: function makeButton(imageKey, text, posX, posY, callback) { var button = this.add.image(posX, posY, imageKey, "out").setInteractive().setScrollFactor(0); button.setDepth(101); button.on("pointerdown", function() { button.setFrame("down"); this.buttonSound.play() }, this); button.on("pointerup", function() { callback.call(this); button.setFrame("out") }, this); var buttonLabel = this.add.bitmapText(button.x, button.y, "basicFont", text, 16).setScrollFactor(0); buttonLabel.setDepth(102); return button } }, { key: "makeMuteButton", value: function makeMuteButton(imageKey, text, posX, posY) { if (this.sound.mute) { var startFrame = "muteOffOut" } else { var startFrame = "muteOnOut" } var button = this.add.image(posX, posY, imageKey, startFrame).setInteractive().setScrollFactor(0); button.setDepth(101); button.on("pointerdown", function() { if (this.sound.mute) { button.setFrame("muteOffDown") } else { button.setFrame("muteOnDown") } this.buttonSound.play() }, this); button.on("pointerup", function() { if (this.sound.mute) { this.sound.mute = false; button.setFrame("muteOnOut") } else { this.sound.mute = true; button.setFrame("muteOffOut") } }, this); var buttonLabel = this.add.bitmapText(button.x, button.y, "basicFont", text, 16).setScrollFactor(0); buttonLabel.setDepth(102); return button } }, { key: "showCredits", value: function showCredits() { if (this.credits.alpha === 0) { this.credits.alpha = 1; this.credits.setInteractive(); this.startButton.disableInteractive(); this.creditsButton.disableInteractive() } } }, { key: "respondLandscape", value: function respondLandscape() { this.playPortrait.alpha = 1 } }, { key: "respondPortrait", value: function respondPortrait() { var gameWidth = this.game.config.width, gameHeight = this.game.config.height; this.playPortrait.alpha = 0; this.backgroundImage.setPosition(0, 0); this.startButton.setPosition(gameWidth * .5, gameHeight * .67); this.titleLabel.setPosition(gameWidth * .5, gameHeight * .45); this.titleImage.setPosition(gameWidth * .5, gameHeight * .25); this.creditsButton.setPosition(gameWidth * .13, gameHeight * .9); this.credits.setPosition(gameWidth * .5, gameHeight * .45); this.muteButton.setPosition(gameWidth * .87, gameHeight * .9); this.playPortrait.setPosition(gameWidth * .5, gameHeight * .5) } }, { key: "startGame", value: function startGame() { this.scene.start("LevelChoiceScene") } }]); return MainMenuScene }(Phaser.Scene) }, 1170: function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor) } } return function(Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor } }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function") } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called") } return call && (typeof call === "object" || typeof call === "function") ? call : self } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass) } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass } var LevelChoiceScene = exports.LevelChoiceScene = function(_Phaser$Scene) { _inherits(LevelChoiceScene, _Phaser$Scene); function LevelChoiceScene() { _classCallCheck(this, LevelChoiceScene); return _possibleConstructorReturn(this, (LevelChoiceScene.__proto__ || Object.getPrototypeOf(LevelChoiceScene)).call(this, "LevelChoiceScene")) } _createClass(LevelChoiceScene, [{ key: "create", value: function create() { var gameWidth = this.game.config.width, gameHeight = this.game.config.height; this.backgroundImage = this.add.tileSprite(0, 0, gameWidth, gameHeight, "mainMenuBack"); this.backgroundImage.setOrigin(0); this.playPortrait = this.add.image(gameWidth * .5, gameHeight * .5, "playPortrait"); this.playPortrait.setDepth(200); this.playPortrait.alpha = 0; this.game.totalLevels = 34; this.buttonsGroup = this.add.group(); var numOfButtonsInRow = 4, betweenButtonsDistanceH = this.game.config.width / (numOfButtonsInRow + .5), betweenButtonsDistanceV = gameHeight * .1; for (var i = 1; i <= this.game.totalLevels; i++) { var posX = ((i - 1) % 4 + .75) * betweenButtonsDistanceH, posY = (Math.floor((i - 1) / 4) + .5) * betweenButtonsDistanceV; var button = this.makeButton("levelButton", i, posX, posY, this.launchLevel); if (betweenButtonsDistanceV < button.height * 1.1) { button.setScale(betweenButtonsDistanceV / (button.height * 1.1)) } if (i > this.game.lastAvailLevel) { button.disableInteractive(); var lockImage = this.add.image(posX, posY, "lockImage"); lockImage.setDepth(103); if (betweenButtonsDistanceV < button.height * 1.1) { lockImage.setScale(betweenButtonsDistanceV / (button.height * 1.1)) } } this.buttonsGroup.add(button) } this.downKey = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.DOWN); this.upKey = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.UP); this.buttonSound = this.sound.add("buttonSound") } }, { key: "makeButton", value: function makeButton(imageKey, text, posX, posY, callback) { var button = this.add.image(posX, posY, imageKey, "out").setInteractive().setScrollFactor(0); button.setDepth(101); button.levelNumber = text; button.on("pointerdown", function() { button.setFrame("down"); this.buttonSound.play() }, this); button.on("pointerup", function() { button.setFrame("out"); callback.call(this, button.levelNumber) }, this); button.buttonLabel = this.add.bitmapText(button.x, button.y, "basicFont", "" + text, 32).setScrollFactor(0); button.buttonLabel.setDepth(102); button.buttonLabel.setOrigin(.5, .5); button.buttonLabel.tint = 16116959; return button } }, { key: "launchLevel", value: function launchLevel(levelNumber) { this.game.levelNumber = levelNumber; this.scene.start("PlayScene") } }, { key: "respondLandscape", value: function respondLandscape() { this.playPortrait.alpha = 1 } }, { key: "respondPortrait", value: function respondPortrait() { this.playPortrait.alpha = 0 } }]); return LevelChoiceScene }(Phaser.Scene) }, 1171: function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor) } } return function(Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor } }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function") } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called") } return call && (typeof call === "object" || typeof call === "function") ? call : self } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass) } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass } var BootScene = exports.BootScene = function(_Phaser$Scene) { _inherits(BootScene, _Phaser$Scene); function BootScene() { _classCallCheck(this, BootScene); return _possibleConstructorReturn(this, (BootScene.__proto__ || Object.getPrototypeOf(BootScene)).call(this, "BootScene")) } _createClass(BootScene, [{ key: "preload", value: function preload() { this.load.image("preloaderBack", "assets/preloaderBack.png"); this.load.image("preloaderBar", "assets/preloaderBar.png"); this.load.image("playPortrait", "assets/playInPortrait.png"); this.load.image("splashScreen", "assets/splash.png") } }, { key: "create", value: function create() { var gameWidth = this.game.config.width, gameHeight = this.game.config.height; this.playPortrait = this.add.image(gameWidth * .5, gameHeight * .5, "playPortrait"); this.playPortrait.setDepth(200); if (document.documentElement.clientWidth < document.documentElement.clientHeight || this.game.device.os.desktop) this.playPortrait.alpha = 0 } }, { key: "respondLandscape", value: function respondLandscape() { this.playPortrait.alpha = 1 } }, { key: "respondPortrait", value: function respondPortrait() { this.playPortrait.alpha = 0 } }, { key: "update", value: function update() { if (this.playPortrait.alpha === 0) { this.scene.start("PreloaderScene") } } }]); return BootScene }(Phaser.Scene) }, 141: function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor) } } return function(Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor } }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function") } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called") } return call && (typeof call === "object" || typeof call === "function") ? call : self } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass) } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass } var PlainCollider = __webpack_require__(223); var defineOuterVertices = __webpack_require__(1162); var wallGenerator = __webpack_require__(73); var Wall = exports.Wall = function(_Phaser$GameObjects$S) { _inherits(Wall, _Phaser$GameObjects$S); function Wall(scene, edges, wallNumber) { _classCallCheck(this, Wall); var _this = _possibleConstructorReturn(this, (Wall.__proto__ || Object.getPrototypeOf(Wall)).call(this, scene)); _this.definePosition(edges); _this.setPosition(_this.leftPointWall + _this.wallWidth / 2, _this.topPointWall + _this.wallHeight / 2); var textureName = _this.prepareTexture(edges); _this.setTexture(textureName); scene.add.existing(_this); _this.vel = new Phaser.Math.Vector2; _this.movability = 0; _this.velCorrected = false; _this.lastCorrection = new Phaser.Math.Vector2; _this.correctionDirection = new Phaser.Math.Vector2; _this.lastCorrPriority = _this.movability; _this.constraints = { x: { 1: _this.movability, "-1": _this.movability }, y: { 1: _this.movability, "-1": _this.movability } }; _this.wallNumber = wallNumber; _this.reporting = false; _this.setDepth(10); _this.vertices = edges; return _this } _createClass(Wall, [{ key: "definePosition", value: function definePosition(edges) { this.leftPointWall = edges.reduce(function(leftWall, currEdge) { var currEdgeLeft = currEdge.reduce(function(leftEdge, currVer) { if (leftEdge > currVer[0]) { return currVer[0] } return leftEdge }, currEdge[0][0]); if (leftWall > currEdgeLeft) { return currEdgeLeft } return leftWall }, edges[0][0][0]); this.topPointWall = edges.reduce(function(topWall, currEdge) { var currEdgeTop = currEdge.reduce(function(topEdge, currVer) { if (topEdge > currVer[1]) { return currVer[1] } return topEdge }, currEdge[0][1]); if (topWall > currEdgeTop) { return currEdgeTop } return topWall }, edges[0][0][1]); this.rightPointWall = edges.reduce(function(rightWall, currEdge) { var currEdgeRight = currEdge.reduce(function(rightEdge, currVer) { if (rightEdge < currVer[0]) { return currVer[0] } return rightEdge }, currEdge[0][0]); if (rightWall < currEdgeRight) { return currEdgeRight } return rightWall }, edges[0][0][0]); this.bottomPointWall = edges.reduce(function(bottomWall, currEdge) { var currEdgeBottom = currEdge.reduce(function(bottomEdge, currVer) { if (bottomEdge < currVer[1]) { return currVer[1] } return bottomEdge }, currEdge[0][1]); if (bottomWall < currEdgeBottom) { return currEdgeBottom } return bottomWall }, edges[0][0][1]); this.wallWidth = this.rightPointWall - this.leftPointWall, this.wallHeight = this.bottomPointWall - this.topPointWall } }, { key: "prepareTexture", value: function prepareTexture(edges) { var leftOffset = this.leftPointWall, topOffset = this.topPointWall; var alignedEdges = edges.map(function(edge) { return edge.map(function(vertex) { return [vertex[0] - leftOffset, vertex[1] - topOffset] }) }); var edgeVertices = defineOuterVertices(alignedEdges); return this.drawTexture(this.scene, edgeVertices, this.wallWidth, this.wallHeight) } }, { key: "drawTexture", value: function drawTexture(scene, edgeVertices, wallWidth, wallHeight) { return wallGenerator.generateWall(scene, edgeVertices, wallWidth, wallHeight) } }, { key: "velCorrection", value: function velCorrection(origCorrection, point, normal, otherObject, pair, ultimate) { if (!ultimate) var ultimate = { x: false, y: false }; var priority = otherObject.constraints, pushBack = new Phaser.Math.Vector2, ultimatePushBack = { x: false, y: false }; if (!this.velCorrected) this.velCorrected = true; var correction = origCorrection.clone(); correction.multiply(normal); for (var axis in this.constraints) { if (correction[axis] != 0) { var corrSign = correction[axis] / Math.abs(correction[axis]), cSign = -corrSign; if (this.constraints[axis][cSign] != 0 || this.constraints[axis][corrSign] != 0) { if (this.constraints[axis][cSign] > priority[axis][corrSign] || ultimate[axis]) { this.lastCorrection[axis] += correction[axis] } else if (this.constraints[axis][cSign] < priority[axis][corrSign]) { pushBack[axis] = correction[axis] } else if (this.constraints[axis][cSign] == priority[axis][corrSign]) { if (Math.abs(otherObject.vel[axis] + otherObject.lastCorrection[axis]) + Math.abs(this.vel[axis] + this.lastCorrection[axis]) > 0) { var objectShare = Math.abs(this.vel[axis] + this.lastCorrection[axis]) / (Math.abs(otherObject.vel[axis] + otherObject.lastCorrection[axis]) + Math.abs(this.vel[axis] + this.lastCorrection[axis])); this.lastCorrection[axis] += correction[axis] * objectShare; pushBack[axis] = correction[axis] * (1 - objectShare); ultimatePushBack[axis] = true } else { this.lastCorrection[axis] += correction[axis] } } } else { var currentVel = new Phaser.Math.Vector2; currentVel.add(this.vel); currentVel.add(this.lastCorrection); if (Math.abs(currentVel.dot(correction)) < .001 && currentVel.length() > .001) { var altNormal = new Phaser.Math.Vector2(1, 1); altNormal.subtract(normal); this.velCorrection(origCorrection, point, altNormal, otherObject, pair, ultimate) } else { pushBack[axis] = correction[axis] } } this.constraints[axis][corrSign] = Math.min(priority[axis][corrSign], this.constraints[axis][corrSign]) } } return { vector: pushBack, ultimate: ultimatePushBack } } }, { key: "updateVel", value: function updateVel() { this.vel.add(this.lastCorrection) } }, { key: "update", value: function update(time, delta) { this.vel = new Phaser.Math.Vector2; this.velCorrected = false; this.lastCorrection = new Phaser.Math.Vector2; this.lastCorrPriority = this.movability; this.constraints = { x: { 1: this.movability, "-1": this.movability }, y: { 1: this.movability, "-1": this.movability } }; this.resolvedPairs = []; this.unresolvedPairs = [] } }]); return Wall }(Phaser.GameObjects.Sprite); module.exports = Wall }, 223: function(module, exports, __webpack_require__) { "use strict"; var Pair = __webpack_require__(1160); var PlainCollider = { initiate: function(scene) { this.objects = []; this.currentCollGroupId = 0; this.collGroups = {}; this.pairs = []; this.bouncyIndex = undefined; this.reporting = false; this.objectRemoved = false; this.scene = scene }, addObject: function(object, vertices) { object.collider = []; vertices.forEach(function(body) { var clockWiseVertices = this.arrangeVerticesClockwise(body), segments = clockWiseVertices.map(function(vertex, index, vertArray) { var point = new Phaser.Math.Vector2(vertex[0], vertex[1]), nextIndex = index < vertArray.length - 1 ? index + 1 : 0, dirV = new Phaser.Math.Vector2(vertArray[nextIndex][0] - vertex[0], vertArray[nextIndex][1] - vertex[1]), normalVec = dirV.clone(); normalVec.normalizeRightHand(); normalVec.normalize(); normalVec.scale(-1); return { point: point, direction: dirV, normal: normalVec } }, this); object.collider.push(segments) }, this); object.colliderId = this.objects.length; this.objects.push(object); object.on("destroy", function(obj) { var objIndex = this.objects.indexOf(obj); this.objects.splice(objIndex, 1) }, this) }, updateCollider: function(object, vertices) { object.collider = []; vertices.forEach(function(body) { var clockWiseVertices = this.arrangeVerticesClockwise(body), segments = clockWiseVertices.map(function(vertex, index, vertArray) { var point = new Phaser.Math.Vector2(vertex[0], vertex[1]), nextIndex = index < vertArray.length - 1 ? index + 1 : 0, dirV = new Phaser.Math.Vector2(vertArray[nextIndex][0] - vertex[0], vertArray[nextIndex][1] - vertex[1]), normalVec = dirV.clone(); normalVec.normalizeRightHand(); normalVec.normalize(); normalVec.scale(-1); return { point: point, direction: dirV, normal: normalVec } }, this); object.collider.push(segments) }, this) }, refreshPairs: function() { this.findAllPairs() }, sortPairsByPriority: function() { this.pairs.sort(function(a, b) { var aCorrectionIndex = a.object1.lastCorrPriority * a.object2.lastCorrPriority, bCorrectionIndex = b.object1.lastCorrPriority * b.object2.lastCorrPriority; if (aCorrectionIndex < bCorrectionIndex) return -1; return 1 }) }, findAllPairs: function() { this.objects.sort(function(a, b) { if (a.movability > b.movability) return 1; return -1 }); this.pairs = []; for (var r = 0; r < this.objects.length; r++) { this.pairs[r] = []; for (var c = 0; c < this.objects.length; c++) { if (c > r) { if (this.objects[r].collWith.indexOf(this.objects[c].collGroup) >= 0 && this.objects[c].collWith.indexOf(this.objects[r].collGroup) >= 0) this.pairs[r][c] = new Pair(this.objects[r], this.objects[c], this); else this.pairs[r][c] = false } else if (c === r) { this.pairs[r][c] = false } else { this.pairs[r][c] = this.pairs[c][r] } } } }, injectObjectInPairs: function(newObject) { this.pairs[this.objects.length - 1] = []; for (var c = 0; c < this.objects.length - 1; c++) { this.pairs[c][this.objects.length - 1] = new Pair(this.objects[c], newObject, this); this.pairs[this.objects.length - 1][c] = this.pairs[c][this.objects.length - 1] } this.pairs[this.objects.length - 1][this.objects.length - 1] = false }, removeObject: function(obj) { if (!this.objectRemoved) { this.pairs.splice(obj.colliderId, 1); this.pairs.forEach(function(pairRow) { pairRow.splice(obj.colliderId, 1) }, this); this.objectRemoved = true } }, arrangeVerticesClockwise: function(vertices) { if (vertices.length > 3) { var innerPoint = new Phaser.Math.Vector2((vertices[0][0] + vertices[2][0]) * .5, (vertices[0][1] + vertices[2][1]) * .5) } else { var innerPoint = new Phaser.Math.Vector2((vertices[0][0] + vertices[1][0]) * .5, (vertices[0][1] + vertices[1][1]) * .5) } var vertCopy = vertices.slice(); vertCopy.sort(function(a, b) { var aVec = new Phaser.Math.Vector2(a[0] - innerPoint.x, a[1] - innerPoint.y), bVec = new Phaser.Math.Vector2(b[0] - innerPoint.x, b[1] - innerPoint.y); if (aVec.angle() > bVec.angle()) { return 1 } return -1 }, this); return vertCopy }, rotateCollider: function(object, angle, rotPoint) { var rotateMatrix = new Phaser.Math.Matrix3; rotateMatrix.fromArray([Math.cos(angle), Math.sin(angle), 0, -Math.sin(angle), Math.cos(angle), 0, 0, 0]); object.collider.forEach(function(body) { body.forEach(function(segment) { segment.normal.add(segment.point); segment.normal.subtract(rotPoint); segment.normal.transformMat3(rotateMatrix); segment.normal.add(rotPoint); segment.direction.add(segment.point); segment.direction.subtract(rotPoint); segment.direction.transformMat3(rotateMatrix); segment.direction.add(rotPoint); segment.point.subtract(rotPoint); segment.point.transformMat3(rotateMatrix); segment.point.add(rotPoint); segment.direction.subtract(segment.point); segment.normal.subtract(segment.point) }, this) }, this) }, registerNewCollGroup: function(name) { this.collGroups[name] = this.currentCollGroupId; this.currentCollGroupId++; return this.collGroups[name] }, assignCollGroup: function(object, name) { object.collGroup = this.collGroups[name] }, getPairsWithObject: function(object) { var pairsWithObject = this.pairs.filter(function(pair) { if (pair.object1.colliderId === object.colliderId || pair.object2.colliderId === object.colliderId) { return true } return false }, this); return pairsWithObject }, checkCollisionsWithObject: function(object) { var pairs = this.getPairsWithObject(object); pairs.forEach(function(pair) { pair.checkPairCollision(false) }, this) }, checkCollisions: function(objArray) { if (this.objectRemoved) {} var currentPairCell = [0, 1], queueStop = 0, rowsToCheck = [], totalCalledRows = [], iterationCounter = 0; while (queueStop < this.objects.length && iterationCounter < 1e3) { var pair = this.pairs[currentPairCell[0]][currentPairCell[1]]; if (pair) { var pairCollided = pair.checkPairCollision(); if (pairCollided) { totalCalledRows.push(currentPairCell); if (rowsToCheck.indexOf(currentPairCell[1]) < 0) { rowsToCheck.push(currentPairCell[1]) } } } else {} if (currentPairCell[1] === this.objects.length - 1) { if (rowsToCheck.length === 0) { queueStop++; currentPairCell = [queueStop, 0] } else { currentPairCell = [rowsToCheck.shift(), 0] } } else { currentPairCell = [currentPairCell[0], currentPairCell[1] + 1] } if (pair) iterationCounter++ } for (var i = 0; i < this.objects.length; i++) { for (var j = 0; j < i; j++) { var pair = this.pairs[j][i]; if (pair) { if (pair.nowCollided && !pair.previouslyCollided) {} pair.updateCollisionStatus() } } } }, updateObjectsIds: function() { if (this.objectRemoved) { this.objects.forEach(function(entity, index) { entity.colliderId = Number(index) }, this); this.objectRemoved = false } }, drawColliders: function(graphics) { graphics.clear(); this.objects.forEach(function(object) { graphics.beginPath(); object.collider.forEach(function(body) { body.forEach(function(segment, index, arr) { if (index === 0) { graphics.moveTo(segment.point.x, segment.point.y) } else { graphics.lineTo(segment.point.x, segment.point.y); if (index === arr.length - 1) { graphics.closePath(); graphics.strokePath() } } }, this) }, this) }, this) }, moveAll: function(delta) { this.objects.forEach(function(object) { object.updateVel(delta); object.x += object.vel.x; object.y += object.vel.y; object.collider.forEach(function(body) { body.forEach(function(segment) { segment.point.x += object.vel.x; segment.point.y += object.vel.y }, this) }, this) }, this) } }; module.exports = PlainCollider }, 470: function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor) } } return function(Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor } }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function") } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called") } return call && (typeof call === "object" || typeof call === "function") ? call : self } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass) } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass } var Wall = __webpack_require__(141); var wallGenerator = __webpack_require__(73); var GWall = exports.GWall = function(_Wall) { _inherits(GWall, _Wall); function GWall(scene, edges, wallNumber) { _classCallCheck(this, GWall); var _this = _possibleConstructorReturn(this, (GWall.__proto__ || Object.getPrototypeOf(GWall)).call(this, scene, edges, wallNumber)); _this.movability = 3; _this.lastCorrPriority = _this.movability; _this.constraints = { x: { 1: _this.movability, "-1": _this.movability }, y: { 1: _this.movability, "-1": _this.movability } }; return _this } _createClass(GWall, [{ key: "drawTexture", value: function drawTexture(scene, edgeVertices, wallWidth, wallHeight) { return wallGenerator.generateGWall(scene, edgeVertices, wallWidth, wallHeight) } }, { key: "update", value: function update(time, delta) { this.vel.x = 0; this.vel.y = Math.min(5, this.vel.y + .5); this.velCorrected = false; this.lastCorrection = new Phaser.Math.Vector2; this.lastCorrPriority = this.movability; this.constraints = { x: { 1: this.movability, "-1": this.movability }, y: { 1: this.movability, "-1": this.movability } }; this.resolvedPairs = []; this.unresolvedPairs = [] } }]); return GWall }(Wall); module.exports = GWall }, 471: function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor) } } return function(Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor } }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function") } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called") } return call && (typeof call === "object" || typeof call === "function") ? call : self } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass) } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass } var GWall = __webpack_require__(470); var wallGenerator = __webpack_require__(73); var WoodBox = exports.WoodBox = function(_GWall) { _inherits(WoodBox, _GWall); function WoodBox(scene, edges, wallNumber) { _classCallCheck(this, WoodBox); var _this = _possibleConstructorReturn(this, (WoodBox.__proto__ || Object.getPrototypeOf(WoodBox)).call(this, scene, edges, wallNumber)); var topLeft = _this.getTopLeft(), bottomRight = _this.getBottomRight(); _this.vertices = [ [ [topLeft.x, topLeft.y], [bottomRight.x, topLeft.y], [bottomRight.x, bottomRight.y], [topLeft.x, bottomRight.y] ] ]; return _this } _createClass(WoodBox, [{ key: "definePosition", value: function definePosition(edges) { this.wallWidth = 70; this.wallHeight = 70; this.leftPointWall = edges[0][0] - this.wallWidth / 2; this.topPointWall = edges[0][1] - this.wallHeight / 2 } }, { key: "prepareTexture", value: function prepareTexture() { return "woodBox" } }]); return WoodBox }(GWall); module.exports = WoodBox }, 472: function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor) } } return function(Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor } }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function") } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called") } return call && (typeof call === "object" || typeof call === "function") ? call : self } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass) } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass } var PlainCollider = __webpack_require__(223); var Wall = __webpack_require__(141); var LavaWall = __webpack_require__(473); var Bouncy = exports.Bouncy = function(_Phaser$GameObjects$S) { _inherits(Bouncy, _Phaser$GameObjects$S); function Bouncy(scene, xPos, yPos) { _classCallCheck(this, Bouncy); var _this = _possibleConstructorReturn(this, (Bouncy.__proto__ || Object.getPrototypeOf(Bouncy)).call(this, scene, xPos, yPos, "bouncy", "idle0")); scene.add.existing(_this); var frameNamesIdle = [{ key: "bouncy", frame: "idle0" }, { key: "bouncy", frame: "idle1" }, { key: "bouncy", frame: "idle2" }, { key: "bouncy", frame: "idle1" }]; var frameNamesFly = [{ key: "bouncy", frame: "fly0" }, { key: "bouncy", frame: "fly1" }]; var frameNamesShock = scene.anims.generateFrameNames("bouncy", { prefix: "shock", start: 0, end: 3 }); _this.idleAnimation = scene.anims.create({ key: "idle", frames: frameNamesIdle, repeat: -1, frameRate: 4 }); _this.flyAnimation = scene.anims.create({ key: "fly", frames: frameNamesFly, repeat: -1, frameRate: 6 }); _this.shockAnimation = scene.anims.create({ key: "shock", frames: frameNamesShock, repeat: 1, frameRate: 12 }); _this.play("idle"); var topLeft = _this.getTopLeft(), bottomRight = _this.getBottomRight(); _this.vertices = [ [ [topLeft.x, topLeft.y], [bottomRight.x, topLeft.y], [bottomRight.x, bottomRight.y], [topLeft.x, bottomRight.y] ] ]; _this.vel = new Phaser.Math.Vector2; _this.movability = 2; _this.velCorrected = false; _this.lastCorrection = new Phaser.Math.Vector2; _this.correctionDirection = new Phaser.Math.Vector2; _this.lastCorrPriority = _this.movability; _this.inLava = false; _this.constraints = { x: { 1: _this.movability, "-1": _this.movability }, y: { 1: _this.movability, "-1": _this.movability } }; _this.setDepth(10); if (scene.game.renderer.gl) { _this.engineParticles = scene.add.particles("engineParticle"); _this.engineParticles.setDepth(10); _this.engineEmitter = _this.engineParticles.createEmitter({ x: _this.x, y: _this.y, lifespan: 300, frequency: 30, speed: 10, angle: 90, scale: { start: .5, end: .2 }, alpha: { start: .6, end: 0 } }); _this.engineEmitter.stop() } else { _this.thrustSprite = scene.add.sprite(_this.x, _this.y, "thrustAnim"); var thrustAnimationNames = scene.anims.generateFrameNames("thrustAnim", { start: 1, end: 3 }); _this.thrustAnimation = scene.anims.create({ key: "main", frames: thrustAnimationNames, repeat: -1, frameRate: 12 }); _this.thrustSprite.alpha = 0; _this.thrustSprite.setOrigin(.5, 0); _this.thrustSprite.setDepth(10) } _this.fuelCapacity = 100; _this.currentFuel = 100; _this.fromGroundLaunch = false; _this.dustSplashRight = scene.add.sprite(bottomRight.x, bottomRight.y, "dustSplash"); _this.dustSplashRight.alpha = 0; _this.dustSplashRight.setOrigin(0, 1); _this.dustSplashRight.setDepth(10); _this.dustSplashLeft = scene.add.sprite(topLeft.x, bottomRight.y, "dustSplash"); _this.dustSplashLeft.alpha = 0; _this.dustSplashLeft.setOrigin(1, 1); _this.dustSplashLeft.setDepth(10); _this.dustSplashLeft.setFlipX(true); var dustFrames = [{ key: "dustSplash", frame: "1" }, { key: "dustSplash", frame: "2" }, { key: "dustSplash", frame: "3" }, { key: "dustSplash", frame: "4" }, { key: "dustSplash", frame: "5" }, { key: "dustSplash", frame: "6" }, { key: "dustSplash", frame: "7" }, { key: "dustSplash", frame: "8" }, { key: "dustSplash", frame: "9" }, { key: "dustSplash", frame: "10" }, { key: "dustSplash", frame: "11" }, { key: "dustSplash", frame: "12" }, { key: "dustSplash", frame: "13" }, { key: "dustSplash", frame: "14" }, { key: "dustSplash", frame: "15" }, { key: "dustSplash", frame: "16" }]; _this.dustSplashAnimation = scene.anims.create({ key: "dustSplash", frames: dustFrames, repeat: 0, frameRate: 32 }); _this.dustSplashRight.on("animationcomplete", _this.hideDust, _this); _this.inGroundContact = false; _this.inShock = false; _this.bumpSound = scene.sound.add("bumpSound"); return _this } _createClass(Bouncy, [{ key: "velCorrection", value: function velCorrection(origCorrection, point, normal, otherObject, pair, ultimate) { if (!ultimate) var ultimate = { x: false, y: false }; var priority = otherObject.constraints, pushBack = new Phaser.Math.Vector2, ultimatePushBack = { x: false, y: false }; if (!this.velCorrected) this.velCorrected = true; var correction = origCorrection.clone(); correction.multiply(normal); for (var axis in this.constraints) { if (correction[axis] != 0) { var corrSign = correction[axis] / Math.abs(correction[axis]), cSign = -corrSign; if (this.constraints[axis][cSign] != 0 || this.constraints[axis][corrSign] != 0) { if (this.constraints[axis][cSign] > priority[axis][corrSign] || ultimate[axis]) { this.lastCorrection[axis] += correction[axis] } else if (this.constraints[axis][cSign] < priority[axis][corrSign]) { pushBack[axis] = correction[axis] } else if (this.constraints[axis][cSign] == priority[axis][corrSign]) { if (Math.abs(otherObject.vel[axis] + otherObject.lastCorrection[axis]) + Math.abs(this.vel[axis] + this.lastCorrection[axis]) > 0) { var objectShare = Math.abs(this.vel[axis] + this.lastCorrection[axis]) / (Math.abs(otherObject.vel[axis] + otherObject.lastCorrection[axis]) + Math.abs(this.vel[axis] + this.lastCorrection[axis])); this.lastCorrection[axis] += correction[axis] * objectShare; pushBack[axis] = correction[axis] * (1 - objectShare); ultimatePushBack[axis] = true } else { this.lastCorrection[axis] += correction[axis] } } } else { var currentVel = new Phaser.Math.Vector2; currentVel.add(this.vel); currentVel.add(this.lastCorrection); if (Math.abs(currentVel.dot(correction)) < .001 && currentVel.length() > .001) { var altNormal = new Phaser.Math.Vector2(1, 1); altNormal.subtract(normal); this.velCorrection(origCorrection, point, altNormal, otherObject, pair, ultimate) } else { pushBack[axis] = correction[axis] } } this.constraints[axis][corrSign] = Math.min(priority[axis][corrSign], this.constraints[axis][corrSign]) } } if (otherObject.__proto__.constructor === LavaWall && !this.inLava) { this.inLava = true } if (!this.fromGroundLaunch && Math.abs(normal.y) - 1 < .1 && point[0].y > this.y) { this.fromGroundLaunch = true } return { vector: pushBack, ultimate: ultimatePushBack } } }, { key: "updateVel", value: function updateVel() { this.vel.add(this.lastCorrection) } }, { key: "update", value: function update(time, delta) { this.vel.x = 0; this.vel.y = Math.min(5, this.vel.y + .5); this.velCorrected = false; this.lastCorrection = new Phaser.Math.Vector2; this.lastCorrPriority = this.movability; this.constraints = { x: { 1: this.movability, "-1": this.movability }, y: { 1: this.movability, "-1": this.movability } }; this.resolvedPairs = []; this.unresolvedPairs = []; if (this.fromGroundLaunch && !this.inGroundContact) { this.launchDust(); this.inGroundContact = true } else if (!this.fromGroundLaunch) { this.inGroundContact = false } this.fromGroundLaunch = false } }, { key: "tankUp", value: function tankUp(fuelAmount) { this.currentFuel = Math.min(this.fuelCapacity, this.currentFuel + fuelAmount); this.emit("tankUp") } }, { key: "launchDust", value: function launchDust() { var bottomRight = this.getBottomRight(), topLeft = this.getTopLeft(); this.dustSplashRight.x = bottomRight.x; this.dustSplashRight.y = bottomRight.y; this.dustSplashLeft.x = topLeft.x; this.dustSplashLeft.y = bottomRight.y; this.dustSplashRight.alpha = 1; this.dustSplashLeft.alpha = 1; this.dustSplashAnimation.resume(); this.dustSplashRight.play("dustSplash"); this.dustSplashLeft.play("dustSplash"); this.bumpSound.play() } }, { key: "hideDust", value: function hideDust() { this.dustSplashRight.alpha = 0; this.dustSplashLeft.alpha = 0 } }]); return Bouncy }(Phaser.GameObjects.Sprite); module.exports = Bouncy }, 473: function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor) } } return function(Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor } }(); var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined } else { return get(parent, property, receiver) } } else if ("value" in desc) { return desc.value } else { var getter = desc.get; if (getter === undefined) { return undefined } return getter.call(receiver) } }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function") } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called") } return call && (typeof call === "object" || typeof call === "function") ? call : self } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass) } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass } var Wall = __webpack_require__(141); var wallGenerator = __webpack_require__(73); var LavaWall = exports.LavaWall = function(_Wall) { _inherits(LavaWall, _Wall); function LavaWall() { _classCallCheck(this, LavaWall); return _possibleConstructorReturn(this, (LavaWall.__proto__ || Object.getPrototypeOf(LavaWall)).apply(this, arguments)) } _createClass(LavaWall, [{ key: "drawTexture", value: function drawTexture(scene, edgeVertices, wallWidth, wallHeight) { var wallTextureData = wallGenerator.generateLavaWall(scene, edgeVertices, wallWidth, wallHeight), alignedFramePoints = wallTextureData.framePoints; this.framePoints = alignedFramePoints.map(function(point) { return new Phaser.Math.Vector2(point.x + this.leftPointWall, point.y + this.topPointWall) }, this); this.scene = scene; this.updatePaths(); this.follower = { t: 0, vec: new Phaser.Math.Vector2, angleVec: new Phaser.Math.Vector2 }; this.flashTween = scene.tweens.add({ targets: this.follower, t: 1, ease: "Linear", duration: this.distance * 3, yoyo: true, repeat: -1 }); this.flashSprite = scene.add.sprite(this.framePoints[0].x, this.framePoints[0].y, "flash"); this.flashSprite.setDepth(11); this.flashSprite.setScale(.7); if (!scene.anims.get("flashMain")) { this.mainAnim = scene.anims.create({ key: "flashMain", frames: scene.anims.generateFrameNames("flash", { start: 1, end: 8 }), repeat: -1, frameRate: 12 }) } else { this.mainAnim = scene.anims.get("flashMain") } this.flashSprite.play("flashMain"); this.inRotation = false; this.alphaEvent = scene.time.delayedCall(100 + 400 * Math.random(), this.changeDischargeAlpha, [], this); return wallTextureData.textureName } }, { key: "updatePaths", value: function updatePaths() { var currentDistance = 0; if (this.flashPath) { this.flashPath.destroy() } this.flashPath = this.scene.add.path(); if (this.anglePath) { this.anglePath.destroy() } this.anglePath = this.scene.add.path(); for (var p = 0; p < this.framePoints.length - 1; p++) { var line = new Phaser.Curves.Line([this.framePoints[p].x, this.framePoints[p].y, this.framePoints[p + 1].x, this.framePoints[p + 1].y]); this.flashPath.add(line); var toNextVec = new Phaser.Math.Vector2(this.framePoints[p + 1].x - this.framePoints[p].x, this.framePoints[p + 1].y - this.framePoints[p].y), toNextAngle = toNextVec.angle(), toNextDistance = toNextVec.length(); var angleLine = new Phaser.Curves.Line([currentDistance, toNextAngle, currentDistance + toNextDistance, toNextAngle]); this.anglePath.add(angleLine); currentDistance += toNextDistance } this.distance = currentDistance } }, { key: "rotateFramePoints", value: function rotateFramePoints(angle, center) { this.framePoints.forEach(function(point) { var newPoint = new Phaser.Math.Vector2(point.x - center.x, point.y - center.y), rotateMatrix = new Phaser.Math.Matrix3; rotateMatrix.fromArray([Math.cos(angle), Math.sin(angle), 0, -Math.sin(angle), Math.cos(angle), 0, 0, 0]); newPoint.transformMat3(rotateMatrix); newPoint.add(new Phaser.Math.Vector2(center.x, center.y)); point.copy(newPoint) }, this) } }, { key: "rotateFlash", value: function rotateFlash(angle, center) { this.flashSprite.setRotation(this.flashSprite.rotation + angle); var newPoint = new Phaser.Math.Vector2(this.flashSprite.x - center.x, this.flashSprite.y - center.y), rotateMatrix = new Phaser.Math.Matrix3; rotateMatrix.fromArray([Math.cos(angle), Math.sin(angle), 0, -Math.sin(angle), Math.cos(angle), 0, 0, 0]); newPoint.transformMat3(rotateMatrix); newPoint.add(new Phaser.Math.Vector2(center.x, center.y)); this.flashSprite.setPosition(newPoint.x, newPoint.y) } }, { key: "startRotation", value: function startRotation(angle, center) { this.flashSprite.alpha = 0; this.rotateFramePoints(angle, center); this.rotateFlash(angle, center); this.flashTween.pause(); this.inRotation = true; this.alphaEvent.destroy() } }, { key: "endRotation", value: function endRotation() { this.flashSprite.alpha = 1; this.flashTween.resume(); this.updatePaths(); this.inRotation = false; this.alphaEvent = this.scene.time.delayedCall(100 + 400 * Math.random(), this.changeDischargeAlpha, [], this) } }, { key: "changeDischargeAlpha", value: function changeDischargeAlpha() { if (this) { if (this.flashSprite.alpha === 0) { this.flashSprite.alpha = 1 } else { this.flashSprite.alpha = 0 } this.alphaEvent = this.scene.time.delayedCall(100 + 200 * Math.random(), this.changeDischargeAlpha, [], this) } } }, { key: "update", value: function update(time, delta) { _get(LavaWall.prototype.__proto__ || Object.getPrototypeOf(LavaWall.prototype), "update", this).call(this, time, delta); if (!this.inRotation) { this.flashPath.getPoint(this.follower.t, this.follower.vec); this.flashSprite.setPosition(this.follower.vec.x, this.follower.vec.y); this.anglePath.getPoint(this.follower.t, this.follower.angleVec); this.flashSprite.setRotation(this.follower.angleVec.y) } } }]); return LavaWall }(Wall); module.exports = LavaWall }, 474: function(module, exports, __webpack_require__) { "use strict"; __webpack_require__(224); __webpack_require__(222); var _PlayScene = __webpack_require__(1159); var _PreloaderScene = __webpack_require__(1168); var _MainMenuScene = __webpack_require__(1169); var _LevelChoiceScene = __webpack_require__(1170); var _BootScene = __webpack_require__(1171); var defaultWidth = 600; var defaultHeight = 600; var ua = window.navigator.userAgent; var iOS = !!ua.match(/iPad/i) || !!ua.match(/iPhone/i); var webkit = !!ua.match(/WebKit/i); var iOSSafari = iOS && webkit && !ua.match(/CriOS/i); var config = { type: iOSSafari ? Phaser.CANVAS : Phaser.AUTO, width: defaultWidth, height: defaultHeight, backgroundColor: "#3d3752", parent: "gameContainer", scene: [_BootScene.BootScene, _PreloaderScene.PreloaderScene, _MainMenuScene.MainMenuScene, _LevelChoiceScene.LevelChoiceScene, _PlayScene.PlayScene] }; var game = new Phaser.Game(config); window.addEventListener("resize", windowResized); window.onload = function() { windowResized() }; function windowResized() { if (game.device.os.desktop) { var w = window.innerWidth, h = window.innerHeight; var scaleW = Math.min(w / defaultWidth, 1), scaleH = Math.min(h / defaultHeight, 1), scale = Math.min(scaleW, scaleH); game.canvas.setAttribute("style", " -ms-transform: scale(" + scale + "); -webkit-transform: scale3d(" + scale + ", 1);" + " -moz-transform: scale(" + scale + "); -o-transform: scale(" + scale + "); transform: scale(" + scale + ");" + " transform-origin: center center;"); if (scale < 1) { if (scaleH < 1) { var gameHeight = h / scaleH } else { var gameHeight = defaultHeight } if (scaleW < 1) { var gameWidth = w / scaleW } else { var gameWidth = defaultWidth } game.resize(gameWidth, gameHeight) } } else { if (document.documentElement.clientWidth < document.documentElement.clientHeight) { var w = document.documentElement.clientWidth, h = document.documentElement.clientHeight; var scaleW = w / defaultWidth, scaleH = h / defaultHeight, scale = Math.min(scaleW, scaleH); var gameWidth = w, gameHeight = h; game.resize(gameWidth, gameHeight); game.scene.scenes.forEach(function(scene) { if (scene.cameras.main) scene.cameras.main.setViewport(0, 0, gameWidth, gameHeight); if (scene.playPortrait && scene.sys.isActive()) { scene.respondPortrait() } }, this) } else { game.scene.scenes.forEach(function(scene) { if (scene.playPortrait && scene.sys.isActive()) { scene.respondLandscape() } }, this) } } } }, 73: function(module, exports, __webpack_require__) { "use strict"; var paper = __webpack_require__(222); var wallGenerator = { textureNameArray: [], textureArray: [], texturesBin: [], generateWall: function generateWall(state, vertices, width, height) { this.state = state; var maxOffset = 10; var textureCanvas = document.createElement("canvas"); textureCanvas.width = (width + 2 * maxOffset) / window.devicePixelRatio; textureCanvas.height = (height + 2 * maxOffset) / window.devicePixelRatio; var textureName = "wallTexture" + this.textureNameArray.length; paper.setup(textureCanvas); var segments = vertices.map(function(vertex) { return new paper.Point(vertex[0] + maxOffset, vertex[1] + maxOffset) }, this); segments.pop(); var outerPath = new paper.Path(segments); outerPath.closed = true; outerPath.fillColor = "#563eb2"; outerPath.strokeColor = "black"; outerPath.strokeWidth = 2; var middlePath = outerPath.clone(); extrude(middlePath, 5); middlePath.fillColor = "#433475"; middlePath.strokeWidth = 0; placeEndSquares(outerPath, 16); putShines(outerPath); function drawShine(point, direction, width) { if (direction.equals(new paper.Point(1, 0))) { var aboveVec = direction.rotate(45).multiply(5 * Math.pow(2, .5)), middleVec = direction.rotate(45).multiply(6 * Math.pow(2, .5)), shiftVec = direction.rotate(90).multiply(width) } else if (direction.equals(new paper.Point(-1, 0))) { var aboveVec = direction.rotate(45).multiply(5 * Math.pow(2, .5)), middleVec = direction.rotate(45).multiply(6 * Math.pow(2, .5)), shiftVec = direction.rotate(-90).multiply(width) } else if (direction.equals(new paper.Point(-1, 0))) { var aboveVec = direction.rotate(-45).multiply(5 * Math.pow(2, .5)), middleVec = direction.rotate(-45).multiply(6 * Math.pow(2, .5)), shiftVec = direction.rotate(-90).multiply(width) } else { var aboveVec = direction.rotate(-45).multiply(5 * Math.pow(2, .5)), middleVec = direction.rotate(-45).multiply(6 * Math.pow(2, .5)), shiftVec = direction.rotate(90).multiply(width) } var point1 = point.add(aboveVec), point2 = point1.add(shiftVec.multiply(.4)), point3 = point2.add(middleVec), point4 = point3.add(shiftVec.multiply(-.4)), point5 = point4.add(aboveVec), point6 = point5.add(shiftVec), point7 = point6.add(aboveVec.multiply(-1)), point8 = point7.add(shiftVec.multiply(.4)), point9 = point8.add(middleVec.multiply(-1)), point10 = point9.add(shiftVec.multiply(-.4)), point11 = point10.add(aboveVec.multiply(-1)); var shinePath = new paper.Path([point, point1, point2, point3, point4, point5, point6, point7, point8, point9, point10, point11]); shinePath.closed = true; shinePath.fillColor = "white"; shinePath.opacity = .2 } function putShines(path) { var startRivets = false; path.segments.forEach(function(segment) { var toNextVec = segment.next.point.subtract(segment.point), currentDistance = 0; if (startRivets) { var distance = Math.round(Math.random() * 50) + 100; currentDistance += distance; while (currentDistance + 20 < toNextVec.length) { var localNormal = segment.curve.getNormalAt(currentDistance / toNextVec.length); var tangentPos = segment.point.add(toNextVec.multiply(currentDistance / toNextVec.length)); var shineWidth = Math.round(Math.random() * 20) + 10; drawShine(tangentPos, localNormal, shineWidth); distance = Math.round(Math.random() * 50) + 100; currentDistance += distance + shineWidth } } if (toNextVec.length <= 17) { startRivets = !startRivets } }, this) } function putRivets(path) { var startRivets = false, distance = 70; path.segments.forEach(function(segment) { var toNextVec = segment.next.point.subtract(segment.point); if (startRivets) { var numberOfRivets = Math.floor(toNextVec.length / distance); for (var r = 1; r < numberOfRivets; r++) { var localNormal = segment.curve.getNormalAt(r / numberOfRivets); var tangentPos = segment.point.add(toNextVec.multiply(r / numberOfRivets)), rivetPos = tangentPos.add(localNormal.multiply(8)); drawRivet(rivetPos) } } if (toNextVec.length <= 17) { startRivets = !startRivets } }, this) } function drawRivet(point) { var outerRivet = new paper.Path.Circle(point, 8); outerRivet.fillColor = "#3f706b"; var fromPoint = point.add(new paper.Point(0, -8)), toPoint = point.add(new paper.Point(-8, 0)), throughPoint = point.add(new paper.Point(-8 * Math.cos(Math.PI / 4)), new paper.Point(-8 * Math.sin(Math.PI / 4))), shine = new paper.Path.Arc(fromPoint, throughPoint, toPoint); shine.fillColor = "#ffffff"; shine.opacity = .7; var middleRivet = new paper.Path.Circle(point, 5); middleRivet.fillColor = "#273833" } function extrude(path, depth) { var bisecs = []; path.segments.forEach(function(segment) { var toNextVec = segment.next.point.subtract(segment.point), toPrevVec = segment.previous.point.subtract(segment.point); if (toNextVec.length <= 17) { var bisec = toNextVec.normalize(depth) } else if (toPrevVec.length <= 17) { var bisec = toPrevVec.normalize(depth) } else { toNextVec = toNextVec.normalize(depth); toPrevVec = toPrevVec.normalize(depth); var bisec = toNextVec.add(toPrevVec) } bisecs.push(bisec) }, this); for (var s in path.segments) { var newPoint = path.segments[s].point.add(bisecs[s]); if (path.contains(newPoint)) { path.segments[s].point = path.segments[s].point.add(bisecs[s]) } else { path.segments[s].point = path.segments[s].point.subtract(bisecs[s]) } } } function placeEndSquares(path, squareSide) { path.segments.forEach(function(segment) { var toNextVec = segment.next.point.subtract(segment.point), toPrevVec = segment.previous.point.subtract(segment.point); if (toNextVec.length <= 17) { toNextVec = toNextVec.normalize(squareSide); toPrevVec = toPrevVec.normalize(squareSide); var toVec = segment.point.add(toNextVec).add(toPrevVec); var squarePath = new paper.Path.Rectangle(segment.point, toVec); squarePath.fillColor = "#406ed0"; squarePath.strokeColor = "black"; squarePath.strokeWidth = 2; var smallSquarePath = new paper.Path.Rectangle(segment.point, toVec); smallSquarePath.scale(.8); smallSquarePath.fillColor = "#5e8cf0"; var trianglePath = new paper.Path([segment.point.add(toPrevVec), segment.point, segment.point.add(toNextVec)]); trianglePath.closed = true; trianglePath.fillColor = "#ffffff"; trianglePath.opacity = .3 } }, this) } paper.view.scale(1 / window.devicePixelRatio, new paper.Point(0, 0)); paper.view.draw(); this.state.textures.addCanvas(textureName, textureCanvas); this.textureArray.push(textureCanvas); this.textureNameArray.push(textureName); paper.project.remove(); return textureName }, generateLavaWall: function generateLavaWall(state, vertices, width, height) { this.state = state; var maxOffset = 10; var textureCanvas = document.createElement("canvas"); textureCanvas.width = (width + 2 * maxOffset) / window.devicePixelRatio; textureCanvas.height = (height + 2 * maxOffset) / window.devicePixelRatio; var textureName = "wallTexture" + this.textureNameArray.length; paper.setup(textureCanvas); var segments = vertices.map(function(vertex) { return new paper.Point(vertex[0] + maxOffset, vertex[1] + maxOffset) }, this); segments.pop(); var outerPath = new paper.Path(segments); outerPath.closed = true; outerPath.fillColor = "#5e8cf0"; var leftPath = outerPath.clone(); extrude(leftPath, 2, 9); leftPath.fillColor = "#b5dbf8"; var rightPath = outerPath.clone(); extrude(rightPath, 10, 2); rightPath.fillColor = "#b5dbf8"; outerPath.strokeColor = "black"; outerPath.strokeWidth = 2; placeEndBolts(outerPath, 16); function extrude(path, otherSideDepth, thisSideDepth) { var bisecs = [], otherSide = false; path.segments.forEach(function(segment) { var toNextVec = segment.next.point.subtract(segment.point), toPrevVec = segment.previous.point.subtract(segment.point); var localDepth = otherSide ? otherSideDepth : thisSideDepth; if (toNextVec.length <= 17) { var bisec = toNextVec.normalize(localDepth); otherSide = !otherSide } else if (toPrevVec.length <= 17) { var bisec = toPrevVec.normalize(localDepth) } else { toNextVec = toNextVec.normalize(localDepth); toPrevVec = toPrevVec.normalize(localDepth); var bisec = toNextVec.add(toPrevVec) } bisecs.push(bisec) }, this); for (var s in path.segments) { var newPoint = path.segments[s].point.add(bisecs[s]); if (path.contains(newPoint)) { path.segments[s].point = path.segments[s].point.add(bisecs[s]) } else { path.segments[s].point = path.segments[s].point.subtract(bisecs[s]) } } } function placeEndBolts(path, squareSide) { path.segments.forEach(function(segment) { var toNextVec = segment.next.point.subtract(segment.point), toPrevVec = segment.previous.point.subtract(segment.point); if (toNextVec.length <= 17) { toNextVec = toNextVec.normalize(squareSide); toPrevVec = toPrevVec.normalize(squareSide); var toVec = segment.point.add(toNextVec).add(toPrevVec); var squarePath = new paper.Path.Rectangle(segment.point, toVec); squarePath.fillColor = "#30487e"; squarePath.strokeColor = "black"; squarePath.strokeWidth = 2; drawFlash(squarePath.position, 14, 16) } }, this) } function drawFlash(center, width, height) { var point1 = new paper.Point(center.x - width / 3, center.y + height / 2), point2 = new paper.Point(center.x + width / 2, center.y - height / 6), point3 = new paper.Point(center.x + width / 12, center.y - height / 6), point4 = new paper.Point(center.x + width / 3, center.y - height / 2), point5 = new paper.Point(center.x - width / 6, center.y - height / 2), point6 = new paper.Point(center.x - width / 2, center.y + height / 12), point7 = new paper.Point(center.x - width / 6, center.y + height / 12); var pointArray = [point1, point2, point3, point4, point5, point6, point7]; var flashPath = new paper.Path(pointArray); flashPath.closed = true; flashPath.fillColor = "#b5dbf8" } function findFramePoints(path) { var framePoints = [], bisecs = [], startIndex = undefined, endIndex = undefined, localDepth = 8; path.segments.forEach(function(segment, index) { var toNextVec = segment.next.point.subtract(segment.point), toPrevVec = segment.previous.point.subtract(segment.point); if (toNextVec.length <= 17) { var bisec = toNextVec.normalize(localDepth); if (!startIndex) { startIndex = index } else if (!endIndex) { endIndex = index } } else if (toPrevVec.length <= 17) { var bisec = toPrevVec.normalize(localDepth) } else { toNextVec = toNextVec.normalize(localDepth); toPrevVec = toPrevVec.normalize(localDepth); var bisec = toNextVec.add(toPrevVec) } bisecs.push(bisec) }, this); for (var s in path.segments) { var newPoint = path.segments[s].point.add(bisecs[s]); if (Number(s) >= startIndex && Number(s) <= endIndex) { if (path.contains(newPoint)) { framePoints.push(newPoint) } else { framePoints.push(path.segments[s].point.subtract(bisecs[s])) } } } return framePoints } var alignedFramePoints = findFramePoints(outerPath), noOffsetFramePoints = alignedFramePoints.map(function(point) { return point.add(new paper.Point(-maxOffset, -maxOffset)) }, this); paper.view.scale(1 / window.devicePixelRatio, new paper.Point(0, 0)); paper.view.draw(); this.state.textures.addCanvas(textureName, textureCanvas); this.textureArray.push(textureCanvas); this.textureNameArray.push(textureName); paper.project.remove(); return { textureName: textureName, framePoints: noOffsetFramePoints } }, generateGWall: function generateGWall(state, vertices, width, height) { this.state = state; var textureCanvas = document.createElement("canvas"); textureCanvas.width = width / window.devicePixelRatio; textureCanvas.height = height / window.devicePixelRatio; var textureName = "wallTexture" + this.textureNameArray.length; paper.setup(textureCanvas); var segments = vertices.map(function(vertex) { return new paper.Point(vertex[0], vertex[1]) }, this); segments.pop(); var outerPath = new paper.Path(segments); outerPath.closed = true; outerPath.fillColor = "red"; var middlePath = outerPath.clone(); extrude(middlePath, 5); middlePath.fillColor = "#97b4c3"; insetEnds(outerPath, 7); var subtractedPath = outerPath.subtract(middlePath); subtractedPath.fillColor = "#623e2a"; middlePath.opacity = .7; outerPath.opacity = 0; insetEnds(outerPath, 10); function insetEnds(path, depth) { var moves = []; path.segments.forEach(function(segment) { var toNextVec = segment.next.point.subtract(segment.point), toPrevVec = segment.previous.point.subtract(segment.point); if (toNextVec.length <= 17) { var move = toPrevVec.normalize(depth) } else if (toPrevVec.length <= 17) { var move = toNextVec.normalize(depth) } else { var move = new paper.Point(0, 0) } moves.push(move) }, this); for (var s in path.segments) { path.segments[s].point = path.segments[s].point.add(moves[s]) } } function extrude(path, depth) { var bisecs = []; path.segments.forEach(function(segment) { var toNextVec = segment.next.point.subtract(segment.point), toPrevVec = segment.previous.point.subtract(segment.point); if (toNextVec.length <= 17) { var bisec = toNextVec.normalize(depth) } else if (toPrevVec.length <= 17) { var bisec = toPrevVec.normalize(depth) } else { toNextVec = toNextVec.normalize(depth); toPrevVec = toPrevVec.normalize(depth); var bisec = toNextVec.add(toPrevVec) } bisecs.push(bisec) }, this); for (var s in path.segments) { var newPoint = path.segments[s].point.add(bisecs[s]); if (path.contains(newPoint)) { path.segments[s].point = path.segments[s].point.add(bisecs[s]) } else { path.segments[s].point = path.segments[s].point.subtract(bisecs[s]) } } } paper.view.draw(); paper.view.scale(1 / window.devicePixelRatio, new paper.Point(0, 0)); this.state.textures.addCanvas(textureName, textureCanvas); this.textureArray.push(textureCanvas); this.textureNameArray.push(textureName); paper.project.remove(); return textureName }, generateFreeDoor: function generateFreeDoor(state, vertices, width, height) { this.state = state; var textureCanvas = document.createElement("canvas"), offset = 5; textureCanvas.width = (width + 2 * offset) / window.devicePixelRatio; textureCanvas.height = (height + 2 * offset) / window.devicePixelRatio; var textureName = "wallTexture" + this.textureNameArray.length; paper.setup(textureCanvas); var segments = vertices.map(function(vertex) { return new paper.Point(vertex[0] + offset, vertex[1] + offset) }, this); segments.pop(); var outerPath = new paper.Path(segments); outerPath.closed = true; outerPath.fillColor = "#ffbd5c"; outerPath.strokeColor = "black"; outerPath.strokeWidth = 2; var middlePath = outerPath.clone(); extrude(middlePath, 5); middlePath.fillColor = "#cc8f5d"; middlePath.strokeWidth = 0; paper.view.scale(1 / window.devicePixelRatio, new paper.Point(0, 0)); paper.view.draw(); this.state.textures.addCanvas(textureName, textureCanvas); this.textureArray.push(textureCanvas); this.textureNameArray.push(textureName); paper.project.remove(); return textureName; function extrude(path, depth) { var bisecs = []; path.segments.forEach(function(segment) { var toNextVec = segment.next.point.subtract(segment.point), toPrevVec = segment.previous.point.subtract(segment.point); toNextVec = toNextVec.normalize(depth); toPrevVec = toPrevVec.normalize(depth); var bisec = toNextVec.add(toPrevVec); bisecs.push(bisec) }, this); for (var s in path.segments) { var newPoint = path.segments[s].point.add(bisecs[s]); if (path.contains(newPoint)) { path.segments[s].point = path.segments[s].point.add(bisecs[s]) } else { path.segments[s].point = path.segments[s].point.subtract(bisecs[s]) } } } }, generateButtonDoor: function generateButtonDoor(state, vertices, width, height) { this.state = state; var textureCanvas = document.createElement("canvas"); textureCanvas.width = width; textureCanvas.height = height; var textureName = "wallTexture" + this.textureNameArray.length; paper.setup(textureCanvas); var segments = vertices.map(function(vertex) { return new paper.Point(vertex[0], vertex[1]) }, this); segments.pop(); var outerPath = new paper.Path(segments); outerPath.closed = true; outerPath.fillColor = "red"; var middlePath = outerPath.clone(); extrude(middlePath, 5); middlePath.fillColor = "#97b4c3"; insetEnds(outerPath, 7); var subtractedPath = outerPath.subtract(middlePath); subtractedPath.fillColor = "#ff3163"; middlePath.opacity = .7; outerPath.opacity = 0; insetEnds(outerPath, 10); function insetEnds(path, depth) { var moves = []; path.segments.forEach(function(segment) { var toNextVec = segment.next.point.subtract(segment.point), toPrevVec = segment.previous.point.subtract(segment.point); if (toNextVec.length <= 17) { var move = toPrevVec.normalize(depth) } else if (toPrevVec.length <= 17) { var move = toNextVec.normalize(depth) } else { var move = new paper.Point(0, 0) } moves.push(move) }, this); for (var s in path.segments) { path.segments[s].point = path.segments[s].point.add(moves[s]) } } function extrude(path, depth) { var bisecs = []; path.segments.forEach(function(segment) { var toNextVec = segment.next.point.subtract(segment.point), toPrevVec = segment.previous.point.subtract(segment.point); if (toNextVec.length <= 17) { var bisec = toNextVec.normalize(depth) } else if (toPrevVec.length <= 17) { var bisec = toPrevVec.normalize(depth) } else { toNextVec = toNextVec.normalize(depth); toPrevVec = toPrevVec.normalize(depth); var bisec = toNextVec.add(toPrevVec) } bisecs.push(bisec) }, this); for (var s in path.segments) { var newPoint = path.segments[s].point.add(bisecs[s]); if (path.contains(newPoint)) { path.segments[s].point = path.segments[s].point.add(bisecs[s]) } else { path.segments[s].point = path.segments[s].point.subtract(bisecs[s]) } } } paper.view.scale(1 / window.devicePixelRatio, new paper.Point(0, 0)); paper.view.draw(); this.state.textures.addCanvas(textureName, textureCanvas); this.textureArray.push(textureCanvas); this.textureNameArray.push(textureName); paper.project.remove(); return textureName }, clearTextures: function clearTextures() { this.texturesBin = this.textureNameArray.slice(); this.textureArray = []; this.textureNameArray = [] }, clearBin: function clearBin() { this.texturesBin.forEach(function(textureName) { this.state.textures.remove(textureName) }, this); this.texturesBin = [] } }; module.exports = wallGenerator } }, [474]);
| ver. 1.4 |
Github
|
.
| PHP 8.2.29 | Генераци� �траницы: 0.08 |
proxy
|
phpinfo
|
�а�тройка