Skip to content

Instantly share code, notes, and snippets.

@eonarheim
Created July 19, 2021 19:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eonarheim/f0e42cb94851f4b18098bb0ce658aada to your computer and use it in GitHub Desktop.
Save eonarheim/f0e42cb94851f4b18098bb0ce658aada to your computer and use it in GitHub Desktop.
Collision Resolution Patch v0.24.5
This file has been truncated, but you can view the full file.
/*!
* excalibur - 0.24.5 - Collision Resolution Patch - 2020-9-8
* https://github.com/excaliburjs/Excalibur
* Copyright (c) 2020 Excalibur.js <https://github.com/excaliburjs/Excalibur/graphs/contributors>
* Licensed BSD-2-Clause
* @preserve
*/
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["ex"] = factory();
else
root["ex"] = factory();
})(window, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __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;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "./index.ts");
/******/ })
/************************************************************************/
/******/ ({
/***/ "../../node_modules/core-js/es/array/index.js":
/*!***************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/es/array/index.js ***!
\***************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(/*! ../../modules/es.string.iterator */ "../../node_modules/core-js/modules/es.string.iterator.js");
__webpack_require__(/*! ../../modules/es.array.from */ "../../node_modules/core-js/modules/es.array.from.js");
__webpack_require__(/*! ../../modules/es.array.is-array */ "../../node_modules/core-js/modules/es.array.is-array.js");
__webpack_require__(/*! ../../modules/es.array.of */ "../../node_modules/core-js/modules/es.array.of.js");
__webpack_require__(/*! ../../modules/es.array.concat */ "../../node_modules/core-js/modules/es.array.concat.js");
__webpack_require__(/*! ../../modules/es.array.copy-within */ "../../node_modules/core-js/modules/es.array.copy-within.js");
__webpack_require__(/*! ../../modules/es.array.every */ "../../node_modules/core-js/modules/es.array.every.js");
__webpack_require__(/*! ../../modules/es.array.fill */ "../../node_modules/core-js/modules/es.array.fill.js");
__webpack_require__(/*! ../../modules/es.array.filter */ "../../node_modules/core-js/modules/es.array.filter.js");
__webpack_require__(/*! ../../modules/es.array.find */ "../../node_modules/core-js/modules/es.array.find.js");
__webpack_require__(/*! ../../modules/es.array.find-index */ "../../node_modules/core-js/modules/es.array.find-index.js");
__webpack_require__(/*! ../../modules/es.array.flat */ "../../node_modules/core-js/modules/es.array.flat.js");
__webpack_require__(/*! ../../modules/es.array.flat-map */ "../../node_modules/core-js/modules/es.array.flat-map.js");
__webpack_require__(/*! ../../modules/es.array.for-each */ "../../node_modules/core-js/modules/es.array.for-each.js");
__webpack_require__(/*! ../../modules/es.array.includes */ "../../node_modules/core-js/modules/es.array.includes.js");
__webpack_require__(/*! ../../modules/es.array.index-of */ "../../node_modules/core-js/modules/es.array.index-of.js");
__webpack_require__(/*! ../../modules/es.array.iterator */ "../../node_modules/core-js/modules/es.array.iterator.js");
__webpack_require__(/*! ../../modules/es.array.join */ "../../node_modules/core-js/modules/es.array.join.js");
__webpack_require__(/*! ../../modules/es.array.last-index-of */ "../../node_modules/core-js/modules/es.array.last-index-of.js");
__webpack_require__(/*! ../../modules/es.array.map */ "../../node_modules/core-js/modules/es.array.map.js");
__webpack_require__(/*! ../../modules/es.array.reduce */ "../../node_modules/core-js/modules/es.array.reduce.js");
__webpack_require__(/*! ../../modules/es.array.reduce-right */ "../../node_modules/core-js/modules/es.array.reduce-right.js");
__webpack_require__(/*! ../../modules/es.array.reverse */ "../../node_modules/core-js/modules/es.array.reverse.js");
__webpack_require__(/*! ../../modules/es.array.slice */ "../../node_modules/core-js/modules/es.array.slice.js");
__webpack_require__(/*! ../../modules/es.array.some */ "../../node_modules/core-js/modules/es.array.some.js");
__webpack_require__(/*! ../../modules/es.array.sort */ "../../node_modules/core-js/modules/es.array.sort.js");
__webpack_require__(/*! ../../modules/es.array.species */ "../../node_modules/core-js/modules/es.array.species.js");
__webpack_require__(/*! ../../modules/es.array.splice */ "../../node_modules/core-js/modules/es.array.splice.js");
__webpack_require__(/*! ../../modules/es.array.unscopables.flat */ "../../node_modules/core-js/modules/es.array.unscopables.flat.js");
__webpack_require__(/*! ../../modules/es.array.unscopables.flat-map */ "../../node_modules/core-js/modules/es.array.unscopables.flat-map.js");
var path = __webpack_require__(/*! ../../internals/path */ "../../node_modules/core-js/internals/path.js");
module.exports = path.Array;
/***/ }),
/***/ "../../node_modules/core-js/es/function/index.js":
/*!******************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/es/function/index.js ***!
\******************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(/*! ../../modules/es.function.bind */ "../../node_modules/core-js/modules/es.function.bind.js");
__webpack_require__(/*! ../../modules/es.function.name */ "../../node_modules/core-js/modules/es.function.name.js");
__webpack_require__(/*! ../../modules/es.function.has-instance */ "../../node_modules/core-js/modules/es.function.has-instance.js");
var path = __webpack_require__(/*! ../../internals/path */ "../../node_modules/core-js/internals/path.js");
module.exports = path.Function;
/***/ }),
/***/ "../../node_modules/core-js/internals/a-function.js":
/*!*********************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/a-function.js ***!
\*********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = function (it) {
if (typeof it != 'function') {
throw TypeError(String(it) + ' is not a function');
} return it;
};
/***/ }),
/***/ "../../node_modules/core-js/internals/a-possible-prototype.js":
/*!*******************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/a-possible-prototype.js ***!
\*******************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(/*! ../internals/is-object */ "../../node_modules/core-js/internals/is-object.js");
module.exports = function (it) {
if (!isObject(it) && it !== null) {
throw TypeError("Can't set " + String(it) + ' as a prototype');
} return it;
};
/***/ }),
/***/ "../../node_modules/core-js/internals/add-to-unscopables.js":
/*!*****************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/add-to-unscopables.js ***!
\*****************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var wellKnownSymbol = __webpack_require__(/*! ../internals/well-known-symbol */ "../../node_modules/core-js/internals/well-known-symbol.js");
var create = __webpack_require__(/*! ../internals/object-create */ "../../node_modules/core-js/internals/object-create.js");
var definePropertyModule = __webpack_require__(/*! ../internals/object-define-property */ "../../node_modules/core-js/internals/object-define-property.js");
var UNSCOPABLES = wellKnownSymbol('unscopables');
var ArrayPrototype = Array.prototype;
// Array.prototype[@@unscopables]
// https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables
if (ArrayPrototype[UNSCOPABLES] == undefined) {
definePropertyModule.f(ArrayPrototype, UNSCOPABLES, {
configurable: true,
value: create(null)
});
}
// add a key to Array.prototype[@@unscopables]
module.exports = function (key) {
ArrayPrototype[UNSCOPABLES][key] = true;
};
/***/ }),
/***/ "../../node_modules/core-js/internals/an-object.js":
/*!********************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/an-object.js ***!
\********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(/*! ../internals/is-object */ "../../node_modules/core-js/internals/is-object.js");
module.exports = function (it) {
if (!isObject(it)) {
throw TypeError(String(it) + ' is not an object');
} return it;
};
/***/ }),
/***/ "../../node_modules/core-js/internals/array-copy-within.js":
/*!****************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/array-copy-within.js ***!
\****************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var toObject = __webpack_require__(/*! ../internals/to-object */ "../../node_modules/core-js/internals/to-object.js");
var toAbsoluteIndex = __webpack_require__(/*! ../internals/to-absolute-index */ "../../node_modules/core-js/internals/to-absolute-index.js");
var toLength = __webpack_require__(/*! ../internals/to-length */ "../../node_modules/core-js/internals/to-length.js");
var min = Math.min;
// `Array.prototype.copyWithin` method implementation
// https://tc39.github.io/ecma262/#sec-array.prototype.copywithin
module.exports = [].copyWithin || function copyWithin(target /* = 0 */, start /* = 0, end = @length */) {
var O = toObject(this);
var len = toLength(O.length);
var to = toAbsoluteIndex(target, len);
var from = toAbsoluteIndex(start, len);
var end = arguments.length > 2 ? arguments[2] : undefined;
var count = min((end === undefined ? len : toAbsoluteIndex(end, len)) - from, len - to);
var inc = 1;
if (from < to && to < from + count) {
inc = -1;
from += count - 1;
to += count - 1;
}
while (count-- > 0) {
if (from in O) O[to] = O[from];
else delete O[to];
to += inc;
from += inc;
} return O;
};
/***/ }),
/***/ "../../node_modules/core-js/internals/array-fill.js":
/*!*********************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/array-fill.js ***!
\*********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var toObject = __webpack_require__(/*! ../internals/to-object */ "../../node_modules/core-js/internals/to-object.js");
var toAbsoluteIndex = __webpack_require__(/*! ../internals/to-absolute-index */ "../../node_modules/core-js/internals/to-absolute-index.js");
var toLength = __webpack_require__(/*! ../internals/to-length */ "../../node_modules/core-js/internals/to-length.js");
// `Array.prototype.fill` method implementation
// https://tc39.github.io/ecma262/#sec-array.prototype.fill
module.exports = function fill(value /* , start = 0, end = @length */) {
var O = toObject(this);
var length = toLength(O.length);
var argumentsLength = arguments.length;
var index = toAbsoluteIndex(argumentsLength > 1 ? arguments[1] : undefined, length);
var end = argumentsLength > 2 ? arguments[2] : undefined;
var endPos = end === undefined ? length : toAbsoluteIndex(end, length);
while (endPos > index) O[index++] = value;
return O;
};
/***/ }),
/***/ "../../node_modules/core-js/internals/array-for-each.js":
/*!*************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/array-for-each.js ***!
\*************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $forEach = __webpack_require__(/*! ../internals/array-iteration */ "../../node_modules/core-js/internals/array-iteration.js").forEach;
var arrayMethodIsStrict = __webpack_require__(/*! ../internals/array-method-is-strict */ "../../node_modules/core-js/internals/array-method-is-strict.js");
var arrayMethodUsesToLength = __webpack_require__(/*! ../internals/array-method-uses-to-length */ "../../node_modules/core-js/internals/array-method-uses-to-length.js");
var STRICT_METHOD = arrayMethodIsStrict('forEach');
var USES_TO_LENGTH = arrayMethodUsesToLength('forEach');
// `Array.prototype.forEach` method implementation
// https://tc39.github.io/ecma262/#sec-array.prototype.foreach
module.exports = (!STRICT_METHOD || !USES_TO_LENGTH) ? function forEach(callbackfn /* , thisArg */) {
return $forEach(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
} : [].forEach;
/***/ }),
/***/ "../../node_modules/core-js/internals/array-from.js":
/*!*********************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/array-from.js ***!
\*********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var bind = __webpack_require__(/*! ../internals/function-bind-context */ "../../node_modules/core-js/internals/function-bind-context.js");
var toObject = __webpack_require__(/*! ../internals/to-object */ "../../node_modules/core-js/internals/to-object.js");
var callWithSafeIterationClosing = __webpack_require__(/*! ../internals/call-with-safe-iteration-closing */ "../../node_modules/core-js/internals/call-with-safe-iteration-closing.js");
var isArrayIteratorMethod = __webpack_require__(/*! ../internals/is-array-iterator-method */ "../../node_modules/core-js/internals/is-array-iterator-method.js");
var toLength = __webpack_require__(/*! ../internals/to-length */ "../../node_modules/core-js/internals/to-length.js");
var createProperty = __webpack_require__(/*! ../internals/create-property */ "../../node_modules/core-js/internals/create-property.js");
var getIteratorMethod = __webpack_require__(/*! ../internals/get-iterator-method */ "../../node_modules/core-js/internals/get-iterator-method.js");
// `Array.from` method implementation
// https://tc39.github.io/ecma262/#sec-array.from
module.exports = function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) {
var O = toObject(arrayLike);
var C = typeof this == 'function' ? this : Array;
var argumentsLength = arguments.length;
var mapfn = argumentsLength > 1 ? arguments[1] : undefined;
var mapping = mapfn !== undefined;
var iteratorMethod = getIteratorMethod(O);
var index = 0;
var length, result, step, iterator, next, value;
if (mapping) mapfn = bind(mapfn, argumentsLength > 2 ? arguments[2] : undefined, 2);
// if the target is not iterable or it's an array with the default iterator - use a simple case
if (iteratorMethod != undefined && !(C == Array && isArrayIteratorMethod(iteratorMethod))) {
iterator = iteratorMethod.call(O);
next = iterator.next;
result = new C();
for (;!(step = next.call(iterator)).done; index++) {
value = mapping ? callWithSafeIterationClosing(iterator, mapfn, [step.value, index], true) : step.value;
createProperty(result, index, value);
}
} else {
length = toLength(O.length);
result = new C(length);
for (;length > index; index++) {
value = mapping ? mapfn(O[index], index) : O[index];
createProperty(result, index, value);
}
}
result.length = index;
return result;
};
/***/ }),
/***/ "../../node_modules/core-js/internals/array-includes.js":
/*!*************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/array-includes.js ***!
\*************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var toIndexedObject = __webpack_require__(/*! ../internals/to-indexed-object */ "../../node_modules/core-js/internals/to-indexed-object.js");
var toLength = __webpack_require__(/*! ../internals/to-length */ "../../node_modules/core-js/internals/to-length.js");
var toAbsoluteIndex = __webpack_require__(/*! ../internals/to-absolute-index */ "../../node_modules/core-js/internals/to-absolute-index.js");
// `Array.prototype.{ indexOf, includes }` methods implementation
var createMethod = function (IS_INCLUDES) {
return function ($this, el, fromIndex) {
var O = toIndexedObject($this);
var length = toLength(O.length);
var index = toAbsoluteIndex(fromIndex, length);
var value;
// Array#includes uses SameValueZero equality algorithm
// eslint-disable-next-line no-self-compare
if (IS_INCLUDES && el != el) while (length > index) {
value = O[index++];
// eslint-disable-next-line no-self-compare
if (value != value) return true;
// Array#indexOf ignores holes, Array#includes - not
} else for (;length > index; index++) {
if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0;
} return !IS_INCLUDES && -1;
};
};
module.exports = {
// `Array.prototype.includes` method
// https://tc39.github.io/ecma262/#sec-array.prototype.includes
includes: createMethod(true),
// `Array.prototype.indexOf` method
// https://tc39.github.io/ecma262/#sec-array.prototype.indexof
indexOf: createMethod(false)
};
/***/ }),
/***/ "../../node_modules/core-js/internals/array-iteration.js":
/*!**************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/array-iteration.js ***!
\**************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var bind = __webpack_require__(/*! ../internals/function-bind-context */ "../../node_modules/core-js/internals/function-bind-context.js");
var IndexedObject = __webpack_require__(/*! ../internals/indexed-object */ "../../node_modules/core-js/internals/indexed-object.js");
var toObject = __webpack_require__(/*! ../internals/to-object */ "../../node_modules/core-js/internals/to-object.js");
var toLength = __webpack_require__(/*! ../internals/to-length */ "../../node_modules/core-js/internals/to-length.js");
var arraySpeciesCreate = __webpack_require__(/*! ../internals/array-species-create */ "../../node_modules/core-js/internals/array-species-create.js");
var push = [].push;
// `Array.prototype.{ forEach, map, filter, some, every, find, findIndex }` methods implementation
var createMethod = function (TYPE) {
var IS_MAP = TYPE == 1;
var IS_FILTER = TYPE == 2;
var IS_SOME = TYPE == 3;
var IS_EVERY = TYPE == 4;
var IS_FIND_INDEX = TYPE == 6;
var NO_HOLES = TYPE == 5 || IS_FIND_INDEX;
return function ($this, callbackfn, that, specificCreate) {
var O = toObject($this);
var self = IndexedObject(O);
var boundFunction = bind(callbackfn, that, 3);
var length = toLength(self.length);
var index = 0;
var create = specificCreate || arraySpeciesCreate;
var target = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined;
var value, result;
for (;length > index; index++) if (NO_HOLES || index in self) {
value = self[index];
result = boundFunction(value, index, O);
if (TYPE) {
if (IS_MAP) target[index] = result; // map
else if (result) switch (TYPE) {
case 3: return true; // some
case 5: return value; // find
case 6: return index; // findIndex
case 2: push.call(target, value); // filter
} else if (IS_EVERY) return false; // every
}
}
return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : target;
};
};
module.exports = {
// `Array.prototype.forEach` method
// https://tc39.github.io/ecma262/#sec-array.prototype.foreach
forEach: createMethod(0),
// `Array.prototype.map` method
// https://tc39.github.io/ecma262/#sec-array.prototype.map
map: createMethod(1),
// `Array.prototype.filter` method
// https://tc39.github.io/ecma262/#sec-array.prototype.filter
filter: createMethod(2),
// `Array.prototype.some` method
// https://tc39.github.io/ecma262/#sec-array.prototype.some
some: createMethod(3),
// `Array.prototype.every` method
// https://tc39.github.io/ecma262/#sec-array.prototype.every
every: createMethod(4),
// `Array.prototype.find` method
// https://tc39.github.io/ecma262/#sec-array.prototype.find
find: createMethod(5),
// `Array.prototype.findIndex` method
// https://tc39.github.io/ecma262/#sec-array.prototype.findIndex
findIndex: createMethod(6)
};
/***/ }),
/***/ "../../node_modules/core-js/internals/array-last-index-of.js":
/*!******************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/array-last-index-of.js ***!
\******************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var toIndexedObject = __webpack_require__(/*! ../internals/to-indexed-object */ "../../node_modules/core-js/internals/to-indexed-object.js");
var toInteger = __webpack_require__(/*! ../internals/to-integer */ "../../node_modules/core-js/internals/to-integer.js");
var toLength = __webpack_require__(/*! ../internals/to-length */ "../../node_modules/core-js/internals/to-length.js");
var arrayMethodIsStrict = __webpack_require__(/*! ../internals/array-method-is-strict */ "../../node_modules/core-js/internals/array-method-is-strict.js");
var arrayMethodUsesToLength = __webpack_require__(/*! ../internals/array-method-uses-to-length */ "../../node_modules/core-js/internals/array-method-uses-to-length.js");
var min = Math.min;
var nativeLastIndexOf = [].lastIndexOf;
var NEGATIVE_ZERO = !!nativeLastIndexOf && 1 / [1].lastIndexOf(1, -0) < 0;
var STRICT_METHOD = arrayMethodIsStrict('lastIndexOf');
// For preventing possible almost infinite loop in non-standard implementations, test the forward version of the method
var USES_TO_LENGTH = arrayMethodUsesToLength('indexOf', { ACCESSORS: true, 1: 0 });
var FORCED = NEGATIVE_ZERO || !STRICT_METHOD || !USES_TO_LENGTH;
// `Array.prototype.lastIndexOf` method implementation
// https://tc39.github.io/ecma262/#sec-array.prototype.lastindexof
module.exports = FORCED ? function lastIndexOf(searchElement /* , fromIndex = @[*-1] */) {
// convert -0 to +0
if (NEGATIVE_ZERO) return nativeLastIndexOf.apply(this, arguments) || 0;
var O = toIndexedObject(this);
var length = toLength(O.length);
var index = length - 1;
if (arguments.length > 1) index = min(index, toInteger(arguments[1]));
if (index < 0) index = length + index;
for (;index >= 0; index--) if (index in O && O[index] === searchElement) return index || 0;
return -1;
} : nativeLastIndexOf;
/***/ }),
/***/ "../../node_modules/core-js/internals/array-method-has-species-support.js":
/*!*******************************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/array-method-has-species-support.js ***!
\*******************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var fails = __webpack_require__(/*! ../internals/fails */ "../../node_modules/core-js/internals/fails.js");
var wellKnownSymbol = __webpack_require__(/*! ../internals/well-known-symbol */ "../../node_modules/core-js/internals/well-known-symbol.js");
var V8_VERSION = __webpack_require__(/*! ../internals/engine-v8-version */ "../../node_modules/core-js/internals/engine-v8-version.js");
var SPECIES = wellKnownSymbol('species');
module.exports = function (METHOD_NAME) {
// We can't use this feature detection in V8 since it causes
// deoptimization and serious performance degradation
// https://github.com/zloirock/core-js/issues/677
return V8_VERSION >= 51 || !fails(function () {
var array = [];
var constructor = array.constructor = {};
constructor[SPECIES] = function () {
return { foo: 1 };
};
return array[METHOD_NAME](Boolean).foo !== 1;
});
};
/***/ }),
/***/ "../../node_modules/core-js/internals/array-method-is-strict.js":
/*!*********************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/array-method-is-strict.js ***!
\*********************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var fails = __webpack_require__(/*! ../internals/fails */ "../../node_modules/core-js/internals/fails.js");
module.exports = function (METHOD_NAME, argument) {
var method = [][METHOD_NAME];
return !!method && fails(function () {
// eslint-disable-next-line no-useless-call,no-throw-literal
method.call(null, argument || function () { throw 1; }, 1);
});
};
/***/ }),
/***/ "../../node_modules/core-js/internals/array-method-uses-to-length.js":
/*!**************************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/array-method-uses-to-length.js ***!
\**************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var DESCRIPTORS = __webpack_require__(/*! ../internals/descriptors */ "../../node_modules/core-js/internals/descriptors.js");
var fails = __webpack_require__(/*! ../internals/fails */ "../../node_modules/core-js/internals/fails.js");
var has = __webpack_require__(/*! ../internals/has */ "../../node_modules/core-js/internals/has.js");
var defineProperty = Object.defineProperty;
var cache = {};
var thrower = function (it) { throw it; };
module.exports = function (METHOD_NAME, options) {
if (has(cache, METHOD_NAME)) return cache[METHOD_NAME];
if (!options) options = {};
var method = [][METHOD_NAME];
var ACCESSORS = has(options, 'ACCESSORS') ? options.ACCESSORS : false;
var argument0 = has(options, 0) ? options[0] : thrower;
var argument1 = has(options, 1) ? options[1] : undefined;
return cache[METHOD_NAME] = !!method && !fails(function () {
if (ACCESSORS && !DESCRIPTORS) return true;
var O = { length: -1 };
if (ACCESSORS) defineProperty(O, 1, { enumerable: true, get: thrower });
else O[1] = 1;
method.call(O, argument0, argument1);
});
};
/***/ }),
/***/ "../../node_modules/core-js/internals/array-reduce.js":
/*!***********************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/array-reduce.js ***!
\***********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var aFunction = __webpack_require__(/*! ../internals/a-function */ "../../node_modules/core-js/internals/a-function.js");
var toObject = __webpack_require__(/*! ../internals/to-object */ "../../node_modules/core-js/internals/to-object.js");
var IndexedObject = __webpack_require__(/*! ../internals/indexed-object */ "../../node_modules/core-js/internals/indexed-object.js");
var toLength = __webpack_require__(/*! ../internals/to-length */ "../../node_modules/core-js/internals/to-length.js");
// `Array.prototype.{ reduce, reduceRight }` methods implementation
var createMethod = function (IS_RIGHT) {
return function (that, callbackfn, argumentsLength, memo) {
aFunction(callbackfn);
var O = toObject(that);
var self = IndexedObject(O);
var length = toLength(O.length);
var index = IS_RIGHT ? length - 1 : 0;
var i = IS_RIGHT ? -1 : 1;
if (argumentsLength < 2) while (true) {
if (index in self) {
memo = self[index];
index += i;
break;
}
index += i;
if (IS_RIGHT ? index < 0 : length <= index) {
throw TypeError('Reduce of empty array with no initial value');
}
}
for (;IS_RIGHT ? index >= 0 : length > index; index += i) if (index in self) {
memo = callbackfn(memo, self[index], index, O);
}
return memo;
};
};
module.exports = {
// `Array.prototype.reduce` method
// https://tc39.github.io/ecma262/#sec-array.prototype.reduce
left: createMethod(false),
// `Array.prototype.reduceRight` method
// https://tc39.github.io/ecma262/#sec-array.prototype.reduceright
right: createMethod(true)
};
/***/ }),
/***/ "../../node_modules/core-js/internals/array-species-create.js":
/*!*******************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/array-species-create.js ***!
\*******************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(/*! ../internals/is-object */ "../../node_modules/core-js/internals/is-object.js");
var isArray = __webpack_require__(/*! ../internals/is-array */ "../../node_modules/core-js/internals/is-array.js");
var wellKnownSymbol = __webpack_require__(/*! ../internals/well-known-symbol */ "../../node_modules/core-js/internals/well-known-symbol.js");
var SPECIES = wellKnownSymbol('species');
// `ArraySpeciesCreate` abstract operation
// https://tc39.github.io/ecma262/#sec-arrayspeciescreate
module.exports = function (originalArray, length) {
var C;
if (isArray(originalArray)) {
C = originalArray.constructor;
// cross-realm fallback
if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined;
else if (isObject(C)) {
C = C[SPECIES];
if (C === null) C = undefined;
}
} return new (C === undefined ? Array : C)(length === 0 ? 0 : length);
};
/***/ }),
/***/ "../../node_modules/core-js/internals/call-with-safe-iteration-closing.js":
/*!*******************************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/call-with-safe-iteration-closing.js ***!
\*******************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var anObject = __webpack_require__(/*! ../internals/an-object */ "../../node_modules/core-js/internals/an-object.js");
// call something on iterator step with safe closing on error
module.exports = function (iterator, fn, value, ENTRIES) {
try {
return ENTRIES ? fn(anObject(value)[0], value[1]) : fn(value);
// 7.4.6 IteratorClose(iterator, completion)
} catch (error) {
var returnMethod = iterator['return'];
if (returnMethod !== undefined) anObject(returnMethod.call(iterator));
throw error;
}
};
/***/ }),
/***/ "../../node_modules/core-js/internals/check-correctness-of-iteration.js":
/*!*****************************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/check-correctness-of-iteration.js ***!
\*****************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var wellKnownSymbol = __webpack_require__(/*! ../internals/well-known-symbol */ "../../node_modules/core-js/internals/well-known-symbol.js");
var ITERATOR = wellKnownSymbol('iterator');
var SAFE_CLOSING = false;
try {
var called = 0;
var iteratorWithReturn = {
next: function () {
return { done: !!called++ };
},
'return': function () {
SAFE_CLOSING = true;
}
};
iteratorWithReturn[ITERATOR] = function () {
return this;
};
// eslint-disable-next-line no-throw-literal
Array.from(iteratorWithReturn, function () { throw 2; });
} catch (error) { /* empty */ }
module.exports = function (exec, SKIP_CLOSING) {
if (!SKIP_CLOSING && !SAFE_CLOSING) return false;
var ITERATION_SUPPORT = false;
try {
var object = {};
object[ITERATOR] = function () {
return {
next: function () {
return { done: ITERATION_SUPPORT = true };
}
};
};
exec(object);
} catch (error) { /* empty */ }
return ITERATION_SUPPORT;
};
/***/ }),
/***/ "../../node_modules/core-js/internals/classof-raw.js":
/*!**********************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/classof-raw.js ***!
\**********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
var toString = {}.toString;
module.exports = function (it) {
return toString.call(it).slice(8, -1);
};
/***/ }),
/***/ "../../node_modules/core-js/internals/classof.js":
/*!******************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/classof.js ***!
\******************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var TO_STRING_TAG_SUPPORT = __webpack_require__(/*! ../internals/to-string-tag-support */ "../../node_modules/core-js/internals/to-string-tag-support.js");
var classofRaw = __webpack_require__(/*! ../internals/classof-raw */ "../../node_modules/core-js/internals/classof-raw.js");
var wellKnownSymbol = __webpack_require__(/*! ../internals/well-known-symbol */ "../../node_modules/core-js/internals/well-known-symbol.js");
var TO_STRING_TAG = wellKnownSymbol('toStringTag');
// ES3 wrong here
var CORRECT_ARGUMENTS = classofRaw(function () { return arguments; }()) == 'Arguments';
// fallback for IE11 Script Access Denied error
var tryGet = function (it, key) {
try {
return it[key];
} catch (error) { /* empty */ }
};
// getting tag from ES6+ `Object.prototype.toString`
module.exports = TO_STRING_TAG_SUPPORT ? classofRaw : function (it) {
var O, tag, result;
return it === undefined ? 'Undefined' : it === null ? 'Null'
// @@toStringTag case
: typeof (tag = tryGet(O = Object(it), TO_STRING_TAG)) == 'string' ? tag
// builtinTag case
: CORRECT_ARGUMENTS ? classofRaw(O)
// ES3 arguments fallback
: (result = classofRaw(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : result;
};
/***/ }),
/***/ "../../node_modules/core-js/internals/copy-constructor-properties.js":
/*!**************************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/copy-constructor-properties.js ***!
\**************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var has = __webpack_require__(/*! ../internals/has */ "../../node_modules/core-js/internals/has.js");
var ownKeys = __webpack_require__(/*! ../internals/own-keys */ "../../node_modules/core-js/internals/own-keys.js");
var getOwnPropertyDescriptorModule = __webpack_require__(/*! ../internals/object-get-own-property-descriptor */ "../../node_modules/core-js/internals/object-get-own-property-descriptor.js");
var definePropertyModule = __webpack_require__(/*! ../internals/object-define-property */ "../../node_modules/core-js/internals/object-define-property.js");
module.exports = function (target, source) {
var keys = ownKeys(source);
var defineProperty = definePropertyModule.f;
var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (!has(target, key)) defineProperty(target, key, getOwnPropertyDescriptor(source, key));
}
};
/***/ }),
/***/ "../../node_modules/core-js/internals/correct-prototype-getter.js":
/*!***********************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/correct-prototype-getter.js ***!
\***********************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var fails = __webpack_require__(/*! ../internals/fails */ "../../node_modules/core-js/internals/fails.js");
module.exports = !fails(function () {
function F() { /* empty */ }
F.prototype.constructor = null;
return Object.getPrototypeOf(new F()) !== F.prototype;
});
/***/ }),
/***/ "../../node_modules/core-js/internals/create-iterator-constructor.js":
/*!**************************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/create-iterator-constructor.js ***!
\**************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var IteratorPrototype = __webpack_require__(/*! ../internals/iterators-core */ "../../node_modules/core-js/internals/iterators-core.js").IteratorPrototype;
var create = __webpack_require__(/*! ../internals/object-create */ "../../node_modules/core-js/internals/object-create.js");
var createPropertyDescriptor = __webpack_require__(/*! ../internals/create-property-descriptor */ "../../node_modules/core-js/internals/create-property-descriptor.js");
var setToStringTag = __webpack_require__(/*! ../internals/set-to-string-tag */ "../../node_modules/core-js/internals/set-to-string-tag.js");
var Iterators = __webpack_require__(/*! ../internals/iterators */ "../../node_modules/core-js/internals/iterators.js");
var returnThis = function () { return this; };
module.exports = function (IteratorConstructor, NAME, next) {
var TO_STRING_TAG = NAME + ' Iterator';
IteratorConstructor.prototype = create(IteratorPrototype, { next: createPropertyDescriptor(1, next) });
setToStringTag(IteratorConstructor, TO_STRING_TAG, false, true);
Iterators[TO_STRING_TAG] = returnThis;
return IteratorConstructor;
};
/***/ }),
/***/ "../../node_modules/core-js/internals/create-non-enumerable-property.js":
/*!*****************************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/create-non-enumerable-property.js ***!
\*****************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var DESCRIPTORS = __webpack_require__(/*! ../internals/descriptors */ "../../node_modules/core-js/internals/descriptors.js");
var definePropertyModule = __webpack_require__(/*! ../internals/object-define-property */ "../../node_modules/core-js/internals/object-define-property.js");
var createPropertyDescriptor = __webpack_require__(/*! ../internals/create-property-descriptor */ "../../node_modules/core-js/internals/create-property-descriptor.js");
module.exports = DESCRIPTORS ? function (object, key, value) {
return definePropertyModule.f(object, key, createPropertyDescriptor(1, value));
} : function (object, key, value) {
object[key] = value;
return object;
};
/***/ }),
/***/ "../../node_modules/core-js/internals/create-property-descriptor.js":
/*!*************************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/create-property-descriptor.js ***!
\*************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = function (bitmap, value) {
return {
enumerable: !(bitmap & 1),
configurable: !(bitmap & 2),
writable: !(bitmap & 4),
value: value
};
};
/***/ }),
/***/ "../../node_modules/core-js/internals/create-property.js":
/*!**************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/create-property.js ***!
\**************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var toPrimitive = __webpack_require__(/*! ../internals/to-primitive */ "../../node_modules/core-js/internals/to-primitive.js");
var definePropertyModule = __webpack_require__(/*! ../internals/object-define-property */ "../../node_modules/core-js/internals/object-define-property.js");
var createPropertyDescriptor = __webpack_require__(/*! ../internals/create-property-descriptor */ "../../node_modules/core-js/internals/create-property-descriptor.js");
module.exports = function (object, key, value) {
var propertyKey = toPrimitive(key);
if (propertyKey in object) definePropertyModule.f(object, propertyKey, createPropertyDescriptor(0, value));
else object[propertyKey] = value;
};
/***/ }),
/***/ "../../node_modules/core-js/internals/define-iterator.js":
/*!**************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/define-iterator.js ***!
\**************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $ = __webpack_require__(/*! ../internals/export */ "../../node_modules/core-js/internals/export.js");
var createIteratorConstructor = __webpack_require__(/*! ../internals/create-iterator-constructor */ "../../node_modules/core-js/internals/create-iterator-constructor.js");
var getPrototypeOf = __webpack_require__(/*! ../internals/object-get-prototype-of */ "../../node_modules/core-js/internals/object-get-prototype-of.js");
var setPrototypeOf = __webpack_require__(/*! ../internals/object-set-prototype-of */ "../../node_modules/core-js/internals/object-set-prototype-of.js");
var setToStringTag = __webpack_require__(/*! ../internals/set-to-string-tag */ "../../node_modules/core-js/internals/set-to-string-tag.js");
var createNonEnumerableProperty = __webpack_require__(/*! ../internals/create-non-enumerable-property */ "../../node_modules/core-js/internals/create-non-enumerable-property.js");
var redefine = __webpack_require__(/*! ../internals/redefine */ "../../node_modules/core-js/internals/redefine.js");
var wellKnownSymbol = __webpack_require__(/*! ../internals/well-known-symbol */ "../../node_modules/core-js/internals/well-known-symbol.js");
var IS_PURE = __webpack_require__(/*! ../internals/is-pure */ "../../node_modules/core-js/internals/is-pure.js");
var Iterators = __webpack_require__(/*! ../internals/iterators */ "../../node_modules/core-js/internals/iterators.js");
var IteratorsCore = __webpack_require__(/*! ../internals/iterators-core */ "../../node_modules/core-js/internals/iterators-core.js");
var IteratorPrototype = IteratorsCore.IteratorPrototype;
var BUGGY_SAFARI_ITERATORS = IteratorsCore.BUGGY_SAFARI_ITERATORS;
var ITERATOR = wellKnownSymbol('iterator');
var KEYS = 'keys';
var VALUES = 'values';
var ENTRIES = 'entries';
var returnThis = function () { return this; };
module.exports = function (Iterable, NAME, IteratorConstructor, next, DEFAULT, IS_SET, FORCED) {
createIteratorConstructor(IteratorConstructor, NAME, next);
var getIterationMethod = function (KIND) {
if (KIND === DEFAULT && defaultIterator) return defaultIterator;
if (!BUGGY_SAFARI_ITERATORS && KIND in IterablePrototype) return IterablePrototype[KIND];
switch (KIND) {
case KEYS: return function keys() { return new IteratorConstructor(this, KIND); };
case VALUES: return function values() { return new IteratorConstructor(this, KIND); };
case ENTRIES: return function entries() { return new IteratorConstructor(this, KIND); };
} return function () { return new IteratorConstructor(this); };
};
var TO_STRING_TAG = NAME + ' Iterator';
var INCORRECT_VALUES_NAME = false;
var IterablePrototype = Iterable.prototype;
var nativeIterator = IterablePrototype[ITERATOR]
|| IterablePrototype['@@iterator']
|| DEFAULT && IterablePrototype[DEFAULT];
var defaultIterator = !BUGGY_SAFARI_ITERATORS && nativeIterator || getIterationMethod(DEFAULT);
var anyNativeIterator = NAME == 'Array' ? IterablePrototype.entries || nativeIterator : nativeIterator;
var CurrentIteratorPrototype, methods, KEY;
// fix native
if (anyNativeIterator) {
CurrentIteratorPrototype = getPrototypeOf(anyNativeIterator.call(new Iterable()));
if (IteratorPrototype !== Object.prototype && CurrentIteratorPrototype.next) {
if (!IS_PURE && getPrototypeOf(CurrentIteratorPrototype) !== IteratorPrototype) {
if (setPrototypeOf) {
setPrototypeOf(CurrentIteratorPrototype, IteratorPrototype);
} else if (typeof CurrentIteratorPrototype[ITERATOR] != 'function') {
createNonEnumerableProperty(CurrentIteratorPrototype, ITERATOR, returnThis);
}
}
// Set @@toStringTag to native iterators
setToStringTag(CurrentIteratorPrototype, TO_STRING_TAG, true, true);
if (IS_PURE) Iterators[TO_STRING_TAG] = returnThis;
}
}
// fix Array#{values, @@iterator}.name in V8 / FF
if (DEFAULT == VALUES && nativeIterator && nativeIterator.name !== VALUES) {
INCORRECT_VALUES_NAME = true;
defaultIterator = function values() { return nativeIterator.call(this); };
}
// define iterator
if ((!IS_PURE || FORCED) && IterablePrototype[ITERATOR] !== defaultIterator) {
createNonEnumerableProperty(IterablePrototype, ITERATOR, defaultIterator);
}
Iterators[NAME] = defaultIterator;
// export additional methods
if (DEFAULT) {
methods = {
values: getIterationMethod(VALUES),
keys: IS_SET ? defaultIterator : getIterationMethod(KEYS),
entries: getIterationMethod(ENTRIES)
};
if (FORCED) for (KEY in methods) {
if (BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME || !(KEY in IterablePrototype)) {
redefine(IterablePrototype, KEY, methods[KEY]);
}
} else $({ target: NAME, proto: true, forced: BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME }, methods);
}
return methods;
};
/***/ }),
/***/ "../../node_modules/core-js/internals/descriptors.js":
/*!**********************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/descriptors.js ***!
\**********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var fails = __webpack_require__(/*! ../internals/fails */ "../../node_modules/core-js/internals/fails.js");
// Thank's IE8 for his funny defineProperty
module.exports = !fails(function () {
return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] != 7;
});
/***/ }),
/***/ "../../node_modules/core-js/internals/document-create-element.js":
/*!**********************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/document-create-element.js ***!
\**********************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(/*! ../internals/global */ "../../node_modules/core-js/internals/global.js");
var isObject = __webpack_require__(/*! ../internals/is-object */ "../../node_modules/core-js/internals/is-object.js");
var document = global.document;
// typeof document.createElement is 'object' in old IE
var EXISTS = isObject(document) && isObject(document.createElement);
module.exports = function (it) {
return EXISTS ? document.createElement(it) : {};
};
/***/ }),
/***/ "../../node_modules/core-js/internals/engine-user-agent.js":
/*!****************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/engine-user-agent.js ***!
\****************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var getBuiltIn = __webpack_require__(/*! ../internals/get-built-in */ "../../node_modules/core-js/internals/get-built-in.js");
module.exports = getBuiltIn('navigator', 'userAgent') || '';
/***/ }),
/***/ "../../node_modules/core-js/internals/engine-v8-version.js":
/*!****************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/engine-v8-version.js ***!
\****************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(/*! ../internals/global */ "../../node_modules/core-js/internals/global.js");
var userAgent = __webpack_require__(/*! ../internals/engine-user-agent */ "../../node_modules/core-js/internals/engine-user-agent.js");
var process = global.process;
var versions = process && process.versions;
var v8 = versions && versions.v8;
var match, version;
if (v8) {
match = v8.split('.');
version = match[0] + match[1];
} else if (userAgent) {
match = userAgent.match(/Edge\/(\d+)/);
if (!match || match[1] >= 74) {
match = userAgent.match(/Chrome\/(\d+)/);
if (match) version = match[1];
}
}
module.exports = version && +version;
/***/ }),
/***/ "../../node_modules/core-js/internals/enum-bug-keys.js":
/*!************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/enum-bug-keys.js ***!
\************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
// IE8- don't enum bug keys
module.exports = [
'constructor',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'toLocaleString',
'toString',
'valueOf'
];
/***/ }),
/***/ "../../node_modules/core-js/internals/export.js":
/*!*****************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/export.js ***!
\*****************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(/*! ../internals/global */ "../../node_modules/core-js/internals/global.js");
var getOwnPropertyDescriptor = __webpack_require__(/*! ../internals/object-get-own-property-descriptor */ "../../node_modules/core-js/internals/object-get-own-property-descriptor.js").f;
var createNonEnumerableProperty = __webpack_require__(/*! ../internals/create-non-enumerable-property */ "../../node_modules/core-js/internals/create-non-enumerable-property.js");
var redefine = __webpack_require__(/*! ../internals/redefine */ "../../node_modules/core-js/internals/redefine.js");
var setGlobal = __webpack_require__(/*! ../internals/set-global */ "../../node_modules/core-js/internals/set-global.js");
var copyConstructorProperties = __webpack_require__(/*! ../internals/copy-constructor-properties */ "../../node_modules/core-js/internals/copy-constructor-properties.js");
var isForced = __webpack_require__(/*! ../internals/is-forced */ "../../node_modules/core-js/internals/is-forced.js");
/*
options.target - name of the target object
options.global - target is the global object
options.stat - export as static methods of target
options.proto - export as prototype methods of target
options.real - real prototype method for the `pure` version
options.forced - export even if the native feature is available
options.bind - bind methods to the target, required for the `pure` version
options.wrap - wrap constructors to preventing global pollution, required for the `pure` version
options.unsafe - use the simple assignment of property instead of delete + defineProperty
options.sham - add a flag to not completely full polyfills
options.enumerable - export as enumerable property
options.noTargetGet - prevent calling a getter on target
*/
module.exports = function (options, source) {
var TARGET = options.target;
var GLOBAL = options.global;
var STATIC = options.stat;
var FORCED, target, key, targetProperty, sourceProperty, descriptor;
if (GLOBAL) {
target = global;
} else if (STATIC) {
target = global[TARGET] || setGlobal(TARGET, {});
} else {
target = (global[TARGET] || {}).prototype;
}
if (target) for (key in source) {
sourceProperty = source[key];
if (options.noTargetGet) {
descriptor = getOwnPropertyDescriptor(target, key);
targetProperty = descriptor && descriptor.value;
} else targetProperty = target[key];
FORCED = isForced(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced);
// contained in target
if (!FORCED && targetProperty !== undefined) {
if (typeof sourceProperty === typeof targetProperty) continue;
copyConstructorProperties(sourceProperty, targetProperty);
}
// add a flag to not completely full polyfills
if (options.sham || (targetProperty && targetProperty.sham)) {
createNonEnumerableProperty(sourceProperty, 'sham', true);
}
// extend global
redefine(target, key, sourceProperty, options);
}
};
/***/ }),
/***/ "../../node_modules/core-js/internals/fails.js":
/*!****************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/fails.js ***!
\****************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = function (exec) {
try {
return !!exec();
} catch (error) {
return true;
}
};
/***/ }),
/***/ "../../node_modules/core-js/internals/flatten-into-array.js":
/*!*****************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/flatten-into-array.js ***!
\*****************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var isArray = __webpack_require__(/*! ../internals/is-array */ "../../node_modules/core-js/internals/is-array.js");
var toLength = __webpack_require__(/*! ../internals/to-length */ "../../node_modules/core-js/internals/to-length.js");
var bind = __webpack_require__(/*! ../internals/function-bind-context */ "../../node_modules/core-js/internals/function-bind-context.js");
// `FlattenIntoArray` abstract operation
// https://tc39.github.io/proposal-flatMap/#sec-FlattenIntoArray
var flattenIntoArray = function (target, original, source, sourceLen, start, depth, mapper, thisArg) {
var targetIndex = start;
var sourceIndex = 0;
var mapFn = mapper ? bind(mapper, thisArg, 3) : false;
var element;
while (sourceIndex < sourceLen) {
if (sourceIndex in source) {
element = mapFn ? mapFn(source[sourceIndex], sourceIndex, original) : source[sourceIndex];
if (depth > 0 && isArray(element)) {
targetIndex = flattenIntoArray(target, original, element, toLength(element.length), targetIndex, depth - 1) - 1;
} else {
if (targetIndex >= 0x1FFFFFFFFFFFFF) throw TypeError('Exceed the acceptable array length');
target[targetIndex] = element;
}
targetIndex++;
}
sourceIndex++;
}
return targetIndex;
};
module.exports = flattenIntoArray;
/***/ }),
/***/ "../../node_modules/core-js/internals/function-bind-context.js":
/*!********************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/function-bind-context.js ***!
\********************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var aFunction = __webpack_require__(/*! ../internals/a-function */ "../../node_modules/core-js/internals/a-function.js");
// optional / simple context binding
module.exports = function (fn, that, length) {
aFunction(fn);
if (that === undefined) return fn;
switch (length) {
case 0: return function () {
return fn.call(that);
};
case 1: return function (a) {
return fn.call(that, a);
};
case 2: return function (a, b) {
return fn.call(that, a, b);
};
case 3: return function (a, b, c) {
return fn.call(that, a, b, c);
};
}
return function (/* ...args */) {
return fn.apply(that, arguments);
};
};
/***/ }),
/***/ "../../node_modules/core-js/internals/function-bind.js":
/*!************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/function-bind.js ***!
\************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var aFunction = __webpack_require__(/*! ../internals/a-function */ "../../node_modules/core-js/internals/a-function.js");
var isObject = __webpack_require__(/*! ../internals/is-object */ "../../node_modules/core-js/internals/is-object.js");
var slice = [].slice;
var factories = {};
var construct = function (C, argsLength, args) {
if (!(argsLength in factories)) {
for (var list = [], i = 0; i < argsLength; i++) list[i] = 'a[' + i + ']';
// eslint-disable-next-line no-new-func
factories[argsLength] = Function('C,a', 'return new C(' + list.join(',') + ')');
} return factories[argsLength](C, args);
};
// `Function.prototype.bind` method implementation
// https://tc39.github.io/ecma262/#sec-function.prototype.bind
module.exports = Function.bind || function bind(that /* , ...args */) {
var fn = aFunction(this);
var partArgs = slice.call(arguments, 1);
var boundFunction = function bound(/* args... */) {
var args = partArgs.concat(slice.call(arguments));
return this instanceof boundFunction ? construct(fn, args.length, args) : fn.apply(that, args);
};
if (isObject(fn.prototype)) boundFunction.prototype = fn.prototype;
return boundFunction;
};
/***/ }),
/***/ "../../node_modules/core-js/internals/get-built-in.js":
/*!***********************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/get-built-in.js ***!
\***********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var path = __webpack_require__(/*! ../internals/path */ "../../node_modules/core-js/internals/path.js");
var global = __webpack_require__(/*! ../internals/global */ "../../node_modules/core-js/internals/global.js");
var aFunction = function (variable) {
return typeof variable == 'function' ? variable : undefined;
};
module.exports = function (namespace, method) {
return arguments.length < 2 ? aFunction(path[namespace]) || aFunction(global[namespace])
: path[namespace] && path[namespace][method] || global[namespace] && global[namespace][method];
};
/***/ }),
/***/ "../../node_modules/core-js/internals/get-iterator-method.js":
/*!******************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/get-iterator-method.js ***!
\******************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var classof = __webpack_require__(/*! ../internals/classof */ "../../node_modules/core-js/internals/classof.js");
var Iterators = __webpack_require__(/*! ../internals/iterators */ "../../node_modules/core-js/internals/iterators.js");
var wellKnownSymbol = __webpack_require__(/*! ../internals/well-known-symbol */ "../../node_modules/core-js/internals/well-known-symbol.js");
var ITERATOR = wellKnownSymbol('iterator');
module.exports = function (it) {
if (it != undefined) return it[ITERATOR]
|| it['@@iterator']
|| Iterators[classof(it)];
};
/***/ }),
/***/ "../../node_modules/core-js/internals/global.js":
/*!*****************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/global.js ***!
\*****************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {var check = function (it) {
return it && it.Math == Math && it;
};
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
module.exports =
// eslint-disable-next-line no-undef
check(typeof globalThis == 'object' && globalThis) ||
check(typeof window == 'object' && window) ||
check(typeof self == 'object' && self) ||
check(typeof global == 'object' && global) ||
// eslint-disable-next-line no-new-func
Function('return this')();
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../webpack/buildin/global.js */ "../../node_modules/webpack/buildin/global.js")))
/***/ }),
/***/ "../../node_modules/core-js/internals/has.js":
/*!**************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/has.js ***!
\**************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
var hasOwnProperty = {}.hasOwnProperty;
module.exports = function (it, key) {
return hasOwnProperty.call(it, key);
};
/***/ }),
/***/ "../../node_modules/core-js/internals/hidden-keys.js":
/*!**********************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/hidden-keys.js ***!
\**********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = {};
/***/ }),
/***/ "../../node_modules/core-js/internals/html.js":
/*!***************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/html.js ***!
\***************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var getBuiltIn = __webpack_require__(/*! ../internals/get-built-in */ "../../node_modules/core-js/internals/get-built-in.js");
module.exports = getBuiltIn('document', 'documentElement');
/***/ }),
/***/ "../../node_modules/core-js/internals/ie8-dom-define.js":
/*!*************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/ie8-dom-define.js ***!
\*************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var DESCRIPTORS = __webpack_require__(/*! ../internals/descriptors */ "../../node_modules/core-js/internals/descriptors.js");
var fails = __webpack_require__(/*! ../internals/fails */ "../../node_modules/core-js/internals/fails.js");
var createElement = __webpack_require__(/*! ../internals/document-create-element */ "../../node_modules/core-js/internals/document-create-element.js");
// Thank's IE8 for his funny defineProperty
module.exports = !DESCRIPTORS && !fails(function () {
return Object.defineProperty(createElement('div'), 'a', {
get: function () { return 7; }
}).a != 7;
});
/***/ }),
/***/ "../../node_modules/core-js/internals/indexed-object.js":
/*!*************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/indexed-object.js ***!
\*************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var fails = __webpack_require__(/*! ../internals/fails */ "../../node_modules/core-js/internals/fails.js");
var classof = __webpack_require__(/*! ../internals/classof-raw */ "../../node_modules/core-js/internals/classof-raw.js");
var split = ''.split;
// fallback for non-array-like ES3 and non-enumerable old V8 strings
module.exports = fails(function () {
// throws an error in rhino, see https://github.com/mozilla/rhino/issues/346
// eslint-disable-next-line no-prototype-builtins
return !Object('z').propertyIsEnumerable(0);
}) ? function (it) {
return classof(it) == 'String' ? split.call(it, '') : Object(it);
} : Object;
/***/ }),
/***/ "../../node_modules/core-js/internals/inspect-source.js":
/*!*************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/inspect-source.js ***!
\*************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var store = __webpack_require__(/*! ../internals/shared-store */ "../../node_modules/core-js/internals/shared-store.js");
var functionToString = Function.toString;
// this helper broken in `3.4.1-3.4.4`, so we can't use `shared` helper
if (typeof store.inspectSource != 'function') {
store.inspectSource = function (it) {
return functionToString.call(it);
};
}
module.exports = store.inspectSource;
/***/ }),
/***/ "../../node_modules/core-js/internals/internal-state.js":
/*!*************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/internal-state.js ***!
\*************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var NATIVE_WEAK_MAP = __webpack_require__(/*! ../internals/native-weak-map */ "../../node_modules/core-js/internals/native-weak-map.js");
var global = __webpack_require__(/*! ../internals/global */ "../../node_modules/core-js/internals/global.js");
var isObject = __webpack_require__(/*! ../internals/is-object */ "../../node_modules/core-js/internals/is-object.js");
var createNonEnumerableProperty = __webpack_require__(/*! ../internals/create-non-enumerable-property */ "../../node_modules/core-js/internals/create-non-enumerable-property.js");
var objectHas = __webpack_require__(/*! ../internals/has */ "../../node_modules/core-js/internals/has.js");
var sharedKey = __webpack_require__(/*! ../internals/shared-key */ "../../node_modules/core-js/internals/shared-key.js");
var hiddenKeys = __webpack_require__(/*! ../internals/hidden-keys */ "../../node_modules/core-js/internals/hidden-keys.js");
var WeakMap = global.WeakMap;
var set, get, has;
var enforce = function (it) {
return has(it) ? get(it) : set(it, {});
};
var getterFor = function (TYPE) {
return function (it) {
var state;
if (!isObject(it) || (state = get(it)).type !== TYPE) {
throw TypeError('Incompatible receiver, ' + TYPE + ' required');
} return state;
};
};
if (NATIVE_WEAK_MAP) {
var store = new WeakMap();
var wmget = store.get;
var wmhas = store.has;
var wmset = store.set;
set = function (it, metadata) {
wmset.call(store, it, metadata);
return metadata;
};
get = function (it) {
return wmget.call(store, it) || {};
};
has = function (it) {
return wmhas.call(store, it);
};
} else {
var STATE = sharedKey('state');
hiddenKeys[STATE] = true;
set = function (it, metadata) {
createNonEnumerableProperty(it, STATE, metadata);
return metadata;
};
get = function (it) {
return objectHas(it, STATE) ? it[STATE] : {};
};
has = function (it) {
return objectHas(it, STATE);
};
}
module.exports = {
set: set,
get: get,
has: has,
enforce: enforce,
getterFor: getterFor
};
/***/ }),
/***/ "../../node_modules/core-js/internals/is-array-iterator-method.js":
/*!***********************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/is-array-iterator-method.js ***!
\***********************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var wellKnownSymbol = __webpack_require__(/*! ../internals/well-known-symbol */ "../../node_modules/core-js/internals/well-known-symbol.js");
var Iterators = __webpack_require__(/*! ../internals/iterators */ "../../node_modules/core-js/internals/iterators.js");
var ITERATOR = wellKnownSymbol('iterator');
var ArrayPrototype = Array.prototype;
// check on default Array iterator
module.exports = function (it) {
return it !== undefined && (Iterators.Array === it || ArrayPrototype[ITERATOR] === it);
};
/***/ }),
/***/ "../../node_modules/core-js/internals/is-array.js":
/*!*******************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/is-array.js ***!
\*******************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var classof = __webpack_require__(/*! ../internals/classof-raw */ "../../node_modules/core-js/internals/classof-raw.js");
// `IsArray` abstract operation
// https://tc39.github.io/ecma262/#sec-isarray
module.exports = Array.isArray || function isArray(arg) {
return classof(arg) == 'Array';
};
/***/ }),
/***/ "../../node_modules/core-js/internals/is-forced.js":
/*!********************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/is-forced.js ***!
\********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var fails = __webpack_require__(/*! ../internals/fails */ "../../node_modules/core-js/internals/fails.js");
var replacement = /#|\.prototype\./;
var isForced = function (feature, detection) {
var value = data[normalize(feature)];
return value == POLYFILL ? true
: value == NATIVE ? false
: typeof detection == 'function' ? fails(detection)
: !!detection;
};
var normalize = isForced.normalize = function (string) {
return String(string).replace(replacement, '.').toLowerCase();
};
var data = isForced.data = {};
var NATIVE = isForced.NATIVE = 'N';
var POLYFILL = isForced.POLYFILL = 'P';
module.exports = isForced;
/***/ }),
/***/ "../../node_modules/core-js/internals/is-object.js":
/*!********************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/is-object.js ***!
\********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = function (it) {
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
/***/ }),
/***/ "../../node_modules/core-js/internals/is-pure.js":
/*!******************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/is-pure.js ***!
\******************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = false;
/***/ }),
/***/ "../../node_modules/core-js/internals/iterators-core.js":
/*!*************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/iterators-core.js ***!
\*************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var getPrototypeOf = __webpack_require__(/*! ../internals/object-get-prototype-of */ "../../node_modules/core-js/internals/object-get-prototype-of.js");
var createNonEnumerableProperty = __webpack_require__(/*! ../internals/create-non-enumerable-property */ "../../node_modules/core-js/internals/create-non-enumerable-property.js");
var has = __webpack_require__(/*! ../internals/has */ "../../node_modules/core-js/internals/has.js");
var wellKnownSymbol = __webpack_require__(/*! ../internals/well-known-symbol */ "../../node_modules/core-js/internals/well-known-symbol.js");
var IS_PURE = __webpack_require__(/*! ../internals/is-pure */ "../../node_modules/core-js/internals/is-pure.js");
var ITERATOR = wellKnownSymbol('iterator');
var BUGGY_SAFARI_ITERATORS = false;
var returnThis = function () { return this; };
// `%IteratorPrototype%` object
// https://tc39.github.io/ecma262/#sec-%iteratorprototype%-object
var IteratorPrototype, PrototypeOfArrayIteratorPrototype, arrayIterator;
if ([].keys) {
arrayIterator = [].keys();
// Safari 8 has buggy iterators w/o `next`
if (!('next' in arrayIterator)) BUGGY_SAFARI_ITERATORS = true;
else {
PrototypeOfArrayIteratorPrototype = getPrototypeOf(getPrototypeOf(arrayIterator));
if (PrototypeOfArrayIteratorPrototype !== Object.prototype) IteratorPrototype = PrototypeOfArrayIteratorPrototype;
}
}
if (IteratorPrototype == undefined) IteratorPrototype = {};
// 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
if (!IS_PURE && !has(IteratorPrototype, ITERATOR)) {
createNonEnumerableProperty(IteratorPrototype, ITERATOR, returnThis);
}
module.exports = {
IteratorPrototype: IteratorPrototype,
BUGGY_SAFARI_ITERATORS: BUGGY_SAFARI_ITERATORS
};
/***/ }),
/***/ "../../node_modules/core-js/internals/iterators.js":
/*!********************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/iterators.js ***!
\********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = {};
/***/ }),
/***/ "../../node_modules/core-js/internals/native-symbol.js":
/*!************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/native-symbol.js ***!
\************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var fails = __webpack_require__(/*! ../internals/fails */ "../../node_modules/core-js/internals/fails.js");
module.exports = !!Object.getOwnPropertySymbols && !fails(function () {
// Chrome 38 Symbol has incorrect toString conversion
// eslint-disable-next-line no-undef
return !String(Symbol());
});
/***/ }),
/***/ "../../node_modules/core-js/internals/native-weak-map.js":
/*!**************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/native-weak-map.js ***!
\**************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(/*! ../internals/global */ "../../node_modules/core-js/internals/global.js");
var inspectSource = __webpack_require__(/*! ../internals/inspect-source */ "../../node_modules/core-js/internals/inspect-source.js");
var WeakMap = global.WeakMap;
module.exports = typeof WeakMap === 'function' && /native code/.test(inspectSource(WeakMap));
/***/ }),
/***/ "../../node_modules/core-js/internals/object-create.js":
/*!************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/object-create.js ***!
\************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var anObject = __webpack_require__(/*! ../internals/an-object */ "../../node_modules/core-js/internals/an-object.js");
var defineProperties = __webpack_require__(/*! ../internals/object-define-properties */ "../../node_modules/core-js/internals/object-define-properties.js");
var enumBugKeys = __webpack_require__(/*! ../internals/enum-bug-keys */ "../../node_modules/core-js/internals/enum-bug-keys.js");
var hiddenKeys = __webpack_require__(/*! ../internals/hidden-keys */ "../../node_modules/core-js/internals/hidden-keys.js");
var html = __webpack_require__(/*! ../internals/html */ "../../node_modules/core-js/internals/html.js");
var documentCreateElement = __webpack_require__(/*! ../internals/document-create-element */ "../../node_modules/core-js/internals/document-create-element.js");
var sharedKey = __webpack_require__(/*! ../internals/shared-key */ "../../node_modules/core-js/internals/shared-key.js");
var GT = '>';
var LT = '<';
var PROTOTYPE = 'prototype';
var SCRIPT = 'script';
var IE_PROTO = sharedKey('IE_PROTO');
var EmptyConstructor = function () { /* empty */ };
var scriptTag = function (content) {
return LT + SCRIPT + GT + content + LT + '/' + SCRIPT + GT;
};
// Create object with fake `null` prototype: use ActiveX Object with cleared prototype
var NullProtoObjectViaActiveX = function (activeXDocument) {
activeXDocument.write(scriptTag(''));
activeXDocument.close();
var temp = activeXDocument.parentWindow.Object;
activeXDocument = null; // avoid memory leak
return temp;
};
// Create object with fake `null` prototype: use iframe Object with cleared prototype
var NullProtoObjectViaIFrame = function () {
// Thrash, waste and sodomy: IE GC bug
var iframe = documentCreateElement('iframe');
var JS = 'java' + SCRIPT + ':';
var iframeDocument;
iframe.style.display = 'none';
html.appendChild(iframe);
// https://github.com/zloirock/core-js/issues/475
iframe.src = String(JS);
iframeDocument = iframe.contentWindow.document;
iframeDocument.open();
iframeDocument.write(scriptTag('document.F=Object'));
iframeDocument.close();
return iframeDocument.F;
};
// Check for document.domain and active x support
// No need to use active x approach when document.domain is not set
// see https://github.com/es-shims/es5-shim/issues/150
// variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346
// avoid IE GC bug
var activeXDocument;
var NullProtoObject = function () {
try {
/* global ActiveXObject */
activeXDocument = document.domain && new ActiveXObject('htmlfile');
} catch (error) { /* ignore */ }
NullProtoObject = activeXDocument ? NullProtoObjectViaActiveX(activeXDocument) : NullProtoObjectViaIFrame();
var length = enumBugKeys.length;
while (length--) delete NullProtoObject[PROTOTYPE][enumBugKeys[length]];
return NullProtoObject();
};
hiddenKeys[IE_PROTO] = true;
// `Object.create` method
// https://tc39.github.io/ecma262/#sec-object.create
module.exports = Object.create || function create(O, Properties) {
var result;
if (O !== null) {
EmptyConstructor[PROTOTYPE] = anObject(O);
result = new EmptyConstructor();
EmptyConstructor[PROTOTYPE] = null;
// add "__proto__" for Object.getPrototypeOf polyfill
result[IE_PROTO] = O;
} else result = NullProtoObject();
return Properties === undefined ? result : defineProperties(result, Properties);
};
/***/ }),
/***/ "../../node_modules/core-js/internals/object-define-properties.js":
/*!***********************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/object-define-properties.js ***!
\***********************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var DESCRIPTORS = __webpack_require__(/*! ../internals/descriptors */ "../../node_modules/core-js/internals/descriptors.js");
var definePropertyModule = __webpack_require__(/*! ../internals/object-define-property */ "../../node_modules/core-js/internals/object-define-property.js");
var anObject = __webpack_require__(/*! ../internals/an-object */ "../../node_modules/core-js/internals/an-object.js");
var objectKeys = __webpack_require__(/*! ../internals/object-keys */ "../../node_modules/core-js/internals/object-keys.js");
// `Object.defineProperties` method
// https://tc39.github.io/ecma262/#sec-object.defineproperties
module.exports = DESCRIPTORS ? Object.defineProperties : function defineProperties(O, Properties) {
anObject(O);
var keys = objectKeys(Properties);
var length = keys.length;
var index = 0;
var key;
while (length > index) definePropertyModule.f(O, key = keys[index++], Properties[key]);
return O;
};
/***/ }),
/***/ "../../node_modules/core-js/internals/object-define-property.js":
/*!*********************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/object-define-property.js ***!
\*********************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var DESCRIPTORS = __webpack_require__(/*! ../internals/descriptors */ "../../node_modules/core-js/internals/descriptors.js");
var IE8_DOM_DEFINE = __webpack_require__(/*! ../internals/ie8-dom-define */ "../../node_modules/core-js/internals/ie8-dom-define.js");
var anObject = __webpack_require__(/*! ../internals/an-object */ "../../node_modules/core-js/internals/an-object.js");
var toPrimitive = __webpack_require__(/*! ../internals/to-primitive */ "../../node_modules/core-js/internals/to-primitive.js");
var nativeDefineProperty = Object.defineProperty;
// `Object.defineProperty` method
// https://tc39.github.io/ecma262/#sec-object.defineproperty
exports.f = DESCRIPTORS ? nativeDefineProperty : function defineProperty(O, P, Attributes) {
anObject(O);
P = toPrimitive(P, true);
anObject(Attributes);
if (IE8_DOM_DEFINE) try {
return nativeDefineProperty(O, P, Attributes);
} catch (error) { /* empty */ }
if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported');
if ('value' in Attributes) O[P] = Attributes.value;
return O;
};
/***/ }),
/***/ "../../node_modules/core-js/internals/object-get-own-property-descriptor.js":
/*!*********************************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/object-get-own-property-descriptor.js ***!
\*********************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var DESCRIPTORS = __webpack_require__(/*! ../internals/descriptors */ "../../node_modules/core-js/internals/descriptors.js");
var propertyIsEnumerableModule = __webpack_require__(/*! ../internals/object-property-is-enumerable */ "../../node_modules/core-js/internals/object-property-is-enumerable.js");
var createPropertyDescriptor = __webpack_require__(/*! ../internals/create-property-descriptor */ "../../node_modules/core-js/internals/create-property-descriptor.js");
var toIndexedObject = __webpack_require__(/*! ../internals/to-indexed-object */ "../../node_modules/core-js/internals/to-indexed-object.js");
var toPrimitive = __webpack_require__(/*! ../internals/to-primitive */ "../../node_modules/core-js/internals/to-primitive.js");
var has = __webpack_require__(/*! ../internals/has */ "../../node_modules/core-js/internals/has.js");
var IE8_DOM_DEFINE = __webpack_require__(/*! ../internals/ie8-dom-define */ "../../node_modules/core-js/internals/ie8-dom-define.js");
var nativeGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
// `Object.getOwnPropertyDescriptor` method
// https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptor
exports.f = DESCRIPTORS ? nativeGetOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) {
O = toIndexedObject(O);
P = toPrimitive(P, true);
if (IE8_DOM_DEFINE) try {
return nativeGetOwnPropertyDescriptor(O, P);
} catch (error) { /* empty */ }
if (has(O, P)) return createPropertyDescriptor(!propertyIsEnumerableModule.f.call(O, P), O[P]);
};
/***/ }),
/***/ "../../node_modules/core-js/internals/object-get-own-property-names.js":
/*!****************************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/object-get-own-property-names.js ***!
\****************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var internalObjectKeys = __webpack_require__(/*! ../internals/object-keys-internal */ "../../node_modules/core-js/internals/object-keys-internal.js");
var enumBugKeys = __webpack_require__(/*! ../internals/enum-bug-keys */ "../../node_modules/core-js/internals/enum-bug-keys.js");
var hiddenKeys = enumBugKeys.concat('length', 'prototype');
// `Object.getOwnPropertyNames` method
// https://tc39.github.io/ecma262/#sec-object.getownpropertynames
exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
return internalObjectKeys(O, hiddenKeys);
};
/***/ }),
/***/ "../../node_modules/core-js/internals/object-get-own-property-symbols.js":
/*!******************************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/object-get-own-property-symbols.js ***!
\******************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
exports.f = Object.getOwnPropertySymbols;
/***/ }),
/***/ "../../node_modules/core-js/internals/object-get-prototype-of.js":
/*!**********************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/object-get-prototype-of.js ***!
\**********************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var has = __webpack_require__(/*! ../internals/has */ "../../node_modules/core-js/internals/has.js");
var toObject = __webpack_require__(/*! ../internals/to-object */ "../../node_modules/core-js/internals/to-object.js");
var sharedKey = __webpack_require__(/*! ../internals/shared-key */ "../../node_modules/core-js/internals/shared-key.js");
var CORRECT_PROTOTYPE_GETTER = __webpack_require__(/*! ../internals/correct-prototype-getter */ "../../node_modules/core-js/internals/correct-prototype-getter.js");
var IE_PROTO = sharedKey('IE_PROTO');
var ObjectPrototype = Object.prototype;
// `Object.getPrototypeOf` method
// https://tc39.github.io/ecma262/#sec-object.getprototypeof
module.exports = CORRECT_PROTOTYPE_GETTER ? Object.getPrototypeOf : function (O) {
O = toObject(O);
if (has(O, IE_PROTO)) return O[IE_PROTO];
if (typeof O.constructor == 'function' && O instanceof O.constructor) {
return O.constructor.prototype;
} return O instanceof Object ? ObjectPrototype : null;
};
/***/ }),
/***/ "../../node_modules/core-js/internals/object-keys-internal.js":
/*!*******************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/object-keys-internal.js ***!
\*******************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var has = __webpack_require__(/*! ../internals/has */ "../../node_modules/core-js/internals/has.js");
var toIndexedObject = __webpack_require__(/*! ../internals/to-indexed-object */ "../../node_modules/core-js/internals/to-indexed-object.js");
var indexOf = __webpack_require__(/*! ../internals/array-includes */ "../../node_modules/core-js/internals/array-includes.js").indexOf;
var hiddenKeys = __webpack_require__(/*! ../internals/hidden-keys */ "../../node_modules/core-js/internals/hidden-keys.js");
module.exports = function (object, names) {
var O = toIndexedObject(object);
var i = 0;
var result = [];
var key;
for (key in O) !has(hiddenKeys, key) && has(O, key) && result.push(key);
// Don't enum bug & hidden keys
while (names.length > i) if (has(O, key = names[i++])) {
~indexOf(result, key) || result.push(key);
}
return result;
};
/***/ }),
/***/ "../../node_modules/core-js/internals/object-keys.js":
/*!**********************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/object-keys.js ***!
\**********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var internalObjectKeys = __webpack_require__(/*! ../internals/object-keys-internal */ "../../node_modules/core-js/internals/object-keys-internal.js");
var enumBugKeys = __webpack_require__(/*! ../internals/enum-bug-keys */ "../../node_modules/core-js/internals/enum-bug-keys.js");
// `Object.keys` method
// https://tc39.github.io/ecma262/#sec-object.keys
module.exports = Object.keys || function keys(O) {
return internalObjectKeys(O, enumBugKeys);
};
/***/ }),
/***/ "../../node_modules/core-js/internals/object-property-is-enumerable.js":
/*!****************************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/object-property-is-enumerable.js ***!
\****************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var nativePropertyIsEnumerable = {}.propertyIsEnumerable;
var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
// Nashorn ~ JDK8 bug
var NASHORN_BUG = getOwnPropertyDescriptor && !nativePropertyIsEnumerable.call({ 1: 2 }, 1);
// `Object.prototype.propertyIsEnumerable` method implementation
// https://tc39.github.io/ecma262/#sec-object.prototype.propertyisenumerable
exports.f = NASHORN_BUG ? function propertyIsEnumerable(V) {
var descriptor = getOwnPropertyDescriptor(this, V);
return !!descriptor && descriptor.enumerable;
} : nativePropertyIsEnumerable;
/***/ }),
/***/ "../../node_modules/core-js/internals/object-set-prototype-of.js":
/*!**********************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/object-set-prototype-of.js ***!
\**********************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var anObject = __webpack_require__(/*! ../internals/an-object */ "../../node_modules/core-js/internals/an-object.js");
var aPossiblePrototype = __webpack_require__(/*! ../internals/a-possible-prototype */ "../../node_modules/core-js/internals/a-possible-prototype.js");
// `Object.setPrototypeOf` method
// https://tc39.github.io/ecma262/#sec-object.setprototypeof
// Works with __proto__ only. Old v8 can't work with null proto objects.
/* eslint-disable no-proto */
module.exports = Object.setPrototypeOf || ('__proto__' in {} ? function () {
var CORRECT_SETTER = false;
var test = {};
var setter;
try {
setter = Object.getOwnPropertyDescriptor(Object.prototype, '__proto__').set;
setter.call(test, []);
CORRECT_SETTER = test instanceof Array;
} catch (error) { /* empty */ }
return function setPrototypeOf(O, proto) {
anObject(O);
aPossiblePrototype(proto);
if (CORRECT_SETTER) setter.call(O, proto);
else O.__proto__ = proto;
return O;
};
}() : undefined);
/***/ }),
/***/ "../../node_modules/core-js/internals/own-keys.js":
/*!*******************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/own-keys.js ***!
\*******************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var getBuiltIn = __webpack_require__(/*! ../internals/get-built-in */ "../../node_modules/core-js/internals/get-built-in.js");
var getOwnPropertyNamesModule = __webpack_require__(/*! ../internals/object-get-own-property-names */ "../../node_modules/core-js/internals/object-get-own-property-names.js");
var getOwnPropertySymbolsModule = __webpack_require__(/*! ../internals/object-get-own-property-symbols */ "../../node_modules/core-js/internals/object-get-own-property-symbols.js");
var anObject = __webpack_require__(/*! ../internals/an-object */ "../../node_modules/core-js/internals/an-object.js");
// all object keys, includes non-enumerable and symbols
module.exports = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) {
var keys = getOwnPropertyNamesModule.f(anObject(it));
var getOwnPropertySymbols = getOwnPropertySymbolsModule.f;
return getOwnPropertySymbols ? keys.concat(getOwnPropertySymbols(it)) : keys;
};
/***/ }),
/***/ "../../node_modules/core-js/internals/path.js":
/*!***************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/path.js ***!
\***************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(/*! ../internals/global */ "../../node_modules/core-js/internals/global.js");
module.exports = global;
/***/ }),
/***/ "../../node_modules/core-js/internals/redefine.js":
/*!*******************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/redefine.js ***!
\*******************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(/*! ../internals/global */ "../../node_modules/core-js/internals/global.js");
var createNonEnumerableProperty = __webpack_require__(/*! ../internals/create-non-enumerable-property */ "../../node_modules/core-js/internals/create-non-enumerable-property.js");
var has = __webpack_require__(/*! ../internals/has */ "../../node_modules/core-js/internals/has.js");
var setGlobal = __webpack_require__(/*! ../internals/set-global */ "../../node_modules/core-js/internals/set-global.js");
var inspectSource = __webpack_require__(/*! ../internals/inspect-source */ "../../node_modules/core-js/internals/inspect-source.js");
var InternalStateModule = __webpack_require__(/*! ../internals/internal-state */ "../../node_modules/core-js/internals/internal-state.js");
var getInternalState = InternalStateModule.get;
var enforceInternalState = InternalStateModule.enforce;
var TEMPLATE = String(String).split('String');
(module.exports = function (O, key, value, options) {
var unsafe = options ? !!options.unsafe : false;
var simple = options ? !!options.enumerable : false;
var noTargetGet = options ? !!options.noTargetGet : false;
if (typeof value == 'function') {
if (typeof key == 'string' && !has(value, 'name')) createNonEnumerableProperty(value, 'name', key);
enforceInternalState(value).source = TEMPLATE.join(typeof key == 'string' ? key : '');
}
if (O === global) {
if (simple) O[key] = value;
else setGlobal(key, value);
return;
} else if (!unsafe) {
delete O[key];
} else if (!noTargetGet && O[key]) {
simple = true;
}
if (simple) O[key] = value;
else createNonEnumerableProperty(O, key, value);
// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
})(Function.prototype, 'toString', function toString() {
return typeof this == 'function' && getInternalState(this).source || inspectSource(this);
});
/***/ }),
/***/ "../../node_modules/core-js/internals/require-object-coercible.js":
/*!***********************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/require-object-coercible.js ***!
\***********************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
// `RequireObjectCoercible` abstract operation
// https://tc39.github.io/ecma262/#sec-requireobjectcoercible
module.exports = function (it) {
if (it == undefined) throw TypeError("Can't call method on " + it);
return it;
};
/***/ }),
/***/ "../../node_modules/core-js/internals/set-global.js":
/*!*********************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/set-global.js ***!
\*********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(/*! ../internals/global */ "../../node_modules/core-js/internals/global.js");
var createNonEnumerableProperty = __webpack_require__(/*! ../internals/create-non-enumerable-property */ "../../node_modules/core-js/internals/create-non-enumerable-property.js");
module.exports = function (key, value) {
try {
createNonEnumerableProperty(global, key, value);
} catch (error) {
global[key] = value;
} return value;
};
/***/ }),
/***/ "../../node_modules/core-js/internals/set-species.js":
/*!**********************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/set-species.js ***!
\**********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var getBuiltIn = __webpack_require__(/*! ../internals/get-built-in */ "../../node_modules/core-js/internals/get-built-in.js");
var definePropertyModule = __webpack_require__(/*! ../internals/object-define-property */ "../../node_modules/core-js/internals/object-define-property.js");
var wellKnownSymbol = __webpack_require__(/*! ../internals/well-known-symbol */ "../../node_modules/core-js/internals/well-known-symbol.js");
var DESCRIPTORS = __webpack_require__(/*! ../internals/descriptors */ "../../node_modules/core-js/internals/descriptors.js");
var SPECIES = wellKnownSymbol('species');
module.exports = function (CONSTRUCTOR_NAME) {
var Constructor = getBuiltIn(CONSTRUCTOR_NAME);
var defineProperty = definePropertyModule.f;
if (DESCRIPTORS && Constructor && !Constructor[SPECIES]) {
defineProperty(Constructor, SPECIES, {
configurable: true,
get: function () { return this; }
});
}
};
/***/ }),
/***/ "../../node_modules/core-js/internals/set-to-string-tag.js":
/*!****************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/set-to-string-tag.js ***!
\****************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var defineProperty = __webpack_require__(/*! ../internals/object-define-property */ "../../node_modules/core-js/internals/object-define-property.js").f;
var has = __webpack_require__(/*! ../internals/has */ "../../node_modules/core-js/internals/has.js");
var wellKnownSymbol = __webpack_require__(/*! ../internals/well-known-symbol */ "../../node_modules/core-js/internals/well-known-symbol.js");
var TO_STRING_TAG = wellKnownSymbol('toStringTag');
module.exports = function (it, TAG, STATIC) {
if (it && !has(it = STATIC ? it : it.prototype, TO_STRING_TAG)) {
defineProperty(it, TO_STRING_TAG, { configurable: true, value: TAG });
}
};
/***/ }),
/***/ "../../node_modules/core-js/internals/shared-key.js":
/*!*********************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/shared-key.js ***!
\*********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var shared = __webpack_require__(/*! ../internals/shared */ "../../node_modules/core-js/internals/shared.js");
var uid = __webpack_require__(/*! ../internals/uid */ "../../node_modules/core-js/internals/uid.js");
var keys = shared('keys');
module.exports = function (key) {
return keys[key] || (keys[key] = uid(key));
};
/***/ }),
/***/ "../../node_modules/core-js/internals/shared-store.js":
/*!***********************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/shared-store.js ***!
\***********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(/*! ../internals/global */ "../../node_modules/core-js/internals/global.js");
var setGlobal = __webpack_require__(/*! ../internals/set-global */ "../../node_modules/core-js/internals/set-global.js");
var SHARED = '__core-js_shared__';
var store = global[SHARED] || setGlobal(SHARED, {});
module.exports = store;
/***/ }),
/***/ "../../node_modules/core-js/internals/shared.js":
/*!*****************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/shared.js ***!
\*****************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var IS_PURE = __webpack_require__(/*! ../internals/is-pure */ "../../node_modules/core-js/internals/is-pure.js");
var store = __webpack_require__(/*! ../internals/shared-store */ "../../node_modules/core-js/internals/shared-store.js");
(module.exports = function (key, value) {
return store[key] || (store[key] = value !== undefined ? value : {});
})('versions', []).push({
version: '3.6.5',
mode: IS_PURE ? 'pure' : 'global',
copyright: '© 2020 Denis Pushkarev (zloirock.ru)'
});
/***/ }),
/***/ "../../node_modules/core-js/internals/string-multibyte.js":
/*!***************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/string-multibyte.js ***!
\***************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var toInteger = __webpack_require__(/*! ../internals/to-integer */ "../../node_modules/core-js/internals/to-integer.js");
var requireObjectCoercible = __webpack_require__(/*! ../internals/require-object-coercible */ "../../node_modules/core-js/internals/require-object-coercible.js");
// `String.prototype.{ codePointAt, at }` methods implementation
var createMethod = function (CONVERT_TO_STRING) {
return function ($this, pos) {
var S = String(requireObjectCoercible($this));
var position = toInteger(pos);
var size = S.length;
var first, second;
if (position < 0 || position >= size) return CONVERT_TO_STRING ? '' : undefined;
first = S.charCodeAt(position);
return first < 0xD800 || first > 0xDBFF || position + 1 === size
|| (second = S.charCodeAt(position + 1)) < 0xDC00 || second > 0xDFFF
? CONVERT_TO_STRING ? S.charAt(position) : first
: CONVERT_TO_STRING ? S.slice(position, position + 2) : (first - 0xD800 << 10) + (second - 0xDC00) + 0x10000;
};
};
module.exports = {
// `String.prototype.codePointAt` method
// https://tc39.github.io/ecma262/#sec-string.prototype.codepointat
codeAt: createMethod(false),
// `String.prototype.at` method
// https://github.com/mathiasbynens/String.prototype.at
charAt: createMethod(true)
};
/***/ }),
/***/ "../../node_modules/core-js/internals/to-absolute-index.js":
/*!****************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/to-absolute-index.js ***!
\****************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var toInteger = __webpack_require__(/*! ../internals/to-integer */ "../../node_modules/core-js/internals/to-integer.js");
var max = Math.max;
var min = Math.min;
// Helper for a popular repeating case of the spec:
// Let integer be ? ToInteger(index).
// If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length).
module.exports = function (index, length) {
var integer = toInteger(index);
return integer < 0 ? max(integer + length, 0) : min(integer, length);
};
/***/ }),
/***/ "../../node_modules/core-js/internals/to-indexed-object.js":
/*!****************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/to-indexed-object.js ***!
\****************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
// toObject with fallback for non-array-like ES3 strings
var IndexedObject = __webpack_require__(/*! ../internals/indexed-object */ "../../node_modules/core-js/internals/indexed-object.js");
var requireObjectCoercible = __webpack_require__(/*! ../internals/require-object-coercible */ "../../node_modules/core-js/internals/require-object-coercible.js");
module.exports = function (it) {
return IndexedObject(requireObjectCoercible(it));
};
/***/ }),
/***/ "../../node_modules/core-js/internals/to-integer.js":
/*!*********************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/to-integer.js ***!
\*********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
var ceil = Math.ceil;
var floor = Math.floor;
// `ToInteger` abstract operation
// https://tc39.github.io/ecma262/#sec-tointeger
module.exports = function (argument) {
return isNaN(argument = +argument) ? 0 : (argument > 0 ? floor : ceil)(argument);
};
/***/ }),
/***/ "../../node_modules/core-js/internals/to-length.js":
/*!********************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/to-length.js ***!
\********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var toInteger = __webpack_require__(/*! ../internals/to-integer */ "../../node_modules/core-js/internals/to-integer.js");
var min = Math.min;
// `ToLength` abstract operation
// https://tc39.github.io/ecma262/#sec-tolength
module.exports = function (argument) {
return argument > 0 ? min(toInteger(argument), 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991
};
/***/ }),
/***/ "../../node_modules/core-js/internals/to-object.js":
/*!********************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/to-object.js ***!
\********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var requireObjectCoercible = __webpack_require__(/*! ../internals/require-object-coercible */ "../../node_modules/core-js/internals/require-object-coercible.js");
// `ToObject` abstract operation
// https://tc39.github.io/ecma262/#sec-toobject
module.exports = function (argument) {
return Object(requireObjectCoercible(argument));
};
/***/ }),
/***/ "../../node_modules/core-js/internals/to-primitive.js":
/*!***********************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/to-primitive.js ***!
\***********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(/*! ../internals/is-object */ "../../node_modules/core-js/internals/is-object.js");
// `ToPrimitive` abstract operation
// https://tc39.github.io/ecma262/#sec-toprimitive
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
module.exports = function (input, PREFERRED_STRING) {
if (!isObject(input)) return input;
var fn, val;
if (PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val;
if (typeof (fn = input.valueOf) == 'function' && !isObject(val = fn.call(input))) return val;
if (!PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val;
throw TypeError("Can't convert object to primitive value");
};
/***/ }),
/***/ "../../node_modules/core-js/internals/to-string-tag-support.js":
/*!********************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/to-string-tag-support.js ***!
\********************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var wellKnownSymbol = __webpack_require__(/*! ../internals/well-known-symbol */ "../../node_modules/core-js/internals/well-known-symbol.js");
var TO_STRING_TAG = wellKnownSymbol('toStringTag');
var test = {};
test[TO_STRING_TAG] = 'z';
module.exports = String(test) === '[object z]';
/***/ }),
/***/ "../../node_modules/core-js/internals/uid.js":
/*!**************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/uid.js ***!
\**************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
var id = 0;
var postfix = Math.random();
module.exports = function (key) {
return 'Symbol(' + String(key === undefined ? '' : key) + ')_' + (++id + postfix).toString(36);
};
/***/ }),
/***/ "../../node_modules/core-js/internals/use-symbol-as-uid.js":
/*!****************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/use-symbol-as-uid.js ***!
\****************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var NATIVE_SYMBOL = __webpack_require__(/*! ../internals/native-symbol */ "../../node_modules/core-js/internals/native-symbol.js");
module.exports = NATIVE_SYMBOL
// eslint-disable-next-line no-undef
&& !Symbol.sham
// eslint-disable-next-line no-undef
&& typeof Symbol.iterator == 'symbol';
/***/ }),
/***/ "../../node_modules/core-js/internals/well-known-symbol.js":
/*!****************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/internals/well-known-symbol.js ***!
\****************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(/*! ../internals/global */ "../../node_modules/core-js/internals/global.js");
var shared = __webpack_require__(/*! ../internals/shared */ "../../node_modules/core-js/internals/shared.js");
var has = __webpack_require__(/*! ../internals/has */ "../../node_modules/core-js/internals/has.js");
var uid = __webpack_require__(/*! ../internals/uid */ "../../node_modules/core-js/internals/uid.js");
var NATIVE_SYMBOL = __webpack_require__(/*! ../internals/native-symbol */ "../../node_modules/core-js/internals/native-symbol.js");
var USE_SYMBOL_AS_UID = __webpack_require__(/*! ../internals/use-symbol-as-uid */ "../../node_modules/core-js/internals/use-symbol-as-uid.js");
var WellKnownSymbolsStore = shared('wks');
var Symbol = global.Symbol;
var createWellKnownSymbol = USE_SYMBOL_AS_UID ? Symbol : Symbol && Symbol.withoutSetter || uid;
module.exports = function (name) {
if (!has(WellKnownSymbolsStore, name)) {
if (NATIVE_SYMBOL && has(Symbol, name)) WellKnownSymbolsStore[name] = Symbol[name];
else WellKnownSymbolsStore[name] = createWellKnownSymbol('Symbol.' + name);
} return WellKnownSymbolsStore[name];
};
/***/ }),
/***/ "../../node_modules/core-js/modules/es.array.concat.js":
/*!************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/modules/es.array.concat.js ***!
\************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $ = __webpack_require__(/*! ../internals/export */ "../../node_modules/core-js/internals/export.js");
var fails = __webpack_require__(/*! ../internals/fails */ "../../node_modules/core-js/internals/fails.js");
var isArray = __webpack_require__(/*! ../internals/is-array */ "../../node_modules/core-js/internals/is-array.js");
var isObject = __webpack_require__(/*! ../internals/is-object */ "../../node_modules/core-js/internals/is-object.js");
var toObject = __webpack_require__(/*! ../internals/to-object */ "../../node_modules/core-js/internals/to-object.js");
var toLength = __webpack_require__(/*! ../internals/to-length */ "../../node_modules/core-js/internals/to-length.js");
var createProperty = __webpack_require__(/*! ../internals/create-property */ "../../node_modules/core-js/internals/create-property.js");
var arraySpeciesCreate = __webpack_require__(/*! ../internals/array-species-create */ "../../node_modules/core-js/internals/array-species-create.js");
var arrayMethodHasSpeciesSupport = __webpack_require__(/*! ../internals/array-method-has-species-support */ "../../node_modules/core-js/internals/array-method-has-species-support.js");
var wellKnownSymbol = __webpack_require__(/*! ../internals/well-known-symbol */ "../../node_modules/core-js/internals/well-known-symbol.js");
var V8_VERSION = __webpack_require__(/*! ../internals/engine-v8-version */ "../../node_modules/core-js/internals/engine-v8-version.js");
var IS_CONCAT_SPREADABLE = wellKnownSymbol('isConcatSpreadable');
var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF;
var MAXIMUM_ALLOWED_INDEX_EXCEEDED = 'Maximum allowed index exceeded';
// We can't use this feature detection in V8 since it causes
// deoptimization and serious performance degradation
// https://github.com/zloirock/core-js/issues/679
var IS_CONCAT_SPREADABLE_SUPPORT = V8_VERSION >= 51 || !fails(function () {
var array = [];
array[IS_CONCAT_SPREADABLE] = false;
return array.concat()[0] !== array;
});
var SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('concat');
var isConcatSpreadable = function (O) {
if (!isObject(O)) return false;
var spreadable = O[IS_CONCAT_SPREADABLE];
return spreadable !== undefined ? !!spreadable : isArray(O);
};
var FORCED = !IS_CONCAT_SPREADABLE_SUPPORT || !SPECIES_SUPPORT;
// `Array.prototype.concat` method
// https://tc39.github.io/ecma262/#sec-array.prototype.concat
// with adding support of @@isConcatSpreadable and @@species
$({ target: 'Array', proto: true, forced: FORCED }, {
concat: function concat(arg) { // eslint-disable-line no-unused-vars
var O = toObject(this);
var A = arraySpeciesCreate(O, 0);
var n = 0;
var i, k, length, len, E;
for (i = -1, length = arguments.length; i < length; i++) {
E = i === -1 ? O : arguments[i];
if (isConcatSpreadable(E)) {
len = toLength(E.length);
if (n + len > MAX_SAFE_INTEGER) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED);
for (k = 0; k < len; k++, n++) if (k in E) createProperty(A, n, E[k]);
} else {
if (n >= MAX_SAFE_INTEGER) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED);
createProperty(A, n++, E);
}
}
A.length = n;
return A;
}
});
/***/ }),
/***/ "../../node_modules/core-js/modules/es.array.copy-within.js":
/*!*****************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/modules/es.array.copy-within.js ***!
\*****************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var $ = __webpack_require__(/*! ../internals/export */ "../../node_modules/core-js/internals/export.js");
var copyWithin = __webpack_require__(/*! ../internals/array-copy-within */ "../../node_modules/core-js/internals/array-copy-within.js");
var addToUnscopables = __webpack_require__(/*! ../internals/add-to-unscopables */ "../../node_modules/core-js/internals/add-to-unscopables.js");
// `Array.prototype.copyWithin` method
// https://tc39.github.io/ecma262/#sec-array.prototype.copywithin
$({ target: 'Array', proto: true }, {
copyWithin: copyWithin
});
// https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables
addToUnscopables('copyWithin');
/***/ }),
/***/ "../../node_modules/core-js/modules/es.array.every.js":
/*!***********************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/modules/es.array.every.js ***!
\***********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $ = __webpack_require__(/*! ../internals/export */ "../../node_modules/core-js/internals/export.js");
var $every = __webpack_require__(/*! ../internals/array-iteration */ "../../node_modules/core-js/internals/array-iteration.js").every;
var arrayMethodIsStrict = __webpack_require__(/*! ../internals/array-method-is-strict */ "../../node_modules/core-js/internals/array-method-is-strict.js");
var arrayMethodUsesToLength = __webpack_require__(/*! ../internals/array-method-uses-to-length */ "../../node_modules/core-js/internals/array-method-uses-to-length.js");
var STRICT_METHOD = arrayMethodIsStrict('every');
var USES_TO_LENGTH = arrayMethodUsesToLength('every');
// `Array.prototype.every` method
// https://tc39.github.io/ecma262/#sec-array.prototype.every
$({ target: 'Array', proto: true, forced: !STRICT_METHOD || !USES_TO_LENGTH }, {
every: function every(callbackfn /* , thisArg */) {
return $every(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
/***/ }),
/***/ "../../node_modules/core-js/modules/es.array.fill.js":
/*!**********************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/modules/es.array.fill.js ***!
\**********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var $ = __webpack_require__(/*! ../internals/export */ "../../node_modules/core-js/internals/export.js");
var fill = __webpack_require__(/*! ../internals/array-fill */ "../../node_modules/core-js/internals/array-fill.js");
var addToUnscopables = __webpack_require__(/*! ../internals/add-to-unscopables */ "../../node_modules/core-js/internals/add-to-unscopables.js");
// `Array.prototype.fill` method
// https://tc39.github.io/ecma262/#sec-array.prototype.fill
$({ target: 'Array', proto: true }, {
fill: fill
});
// https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables
addToUnscopables('fill');
/***/ }),
/***/ "../../node_modules/core-js/modules/es.array.filter.js":
/*!************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/modules/es.array.filter.js ***!
\************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $ = __webpack_require__(/*! ../internals/export */ "../../node_modules/core-js/internals/export.js");
var $filter = __webpack_require__(/*! ../internals/array-iteration */ "../../node_modules/core-js/internals/array-iteration.js").filter;
var arrayMethodHasSpeciesSupport = __webpack_require__(/*! ../internals/array-method-has-species-support */ "../../node_modules/core-js/internals/array-method-has-species-support.js");
var arrayMethodUsesToLength = __webpack_require__(/*! ../internals/array-method-uses-to-length */ "../../node_modules/core-js/internals/array-method-uses-to-length.js");
var HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('filter');
// Edge 14- issue
var USES_TO_LENGTH = arrayMethodUsesToLength('filter');
// `Array.prototype.filter` method
// https://tc39.github.io/ecma262/#sec-array.prototype.filter
// with adding support of @@species
$({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT || !USES_TO_LENGTH }, {
filter: function filter(callbackfn /* , thisArg */) {
return $filter(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
/***/ }),
/***/ "../../node_modules/core-js/modules/es.array.find-index.js":
/*!****************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/modules/es.array.find-index.js ***!
\****************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $ = __webpack_require__(/*! ../internals/export */ "../../node_modules/core-js/internals/export.js");
var $findIndex = __webpack_require__(/*! ../internals/array-iteration */ "../../node_modules/core-js/internals/array-iteration.js").findIndex;
var addToUnscopables = __webpack_require__(/*! ../internals/add-to-unscopables */ "../../node_modules/core-js/internals/add-to-unscopables.js");
var arrayMethodUsesToLength = __webpack_require__(/*! ../internals/array-method-uses-to-length */ "../../node_modules/core-js/internals/array-method-uses-to-length.js");
var FIND_INDEX = 'findIndex';
var SKIPS_HOLES = true;
var USES_TO_LENGTH = arrayMethodUsesToLength(FIND_INDEX);
// Shouldn't skip holes
if (FIND_INDEX in []) Array(1)[FIND_INDEX](function () { SKIPS_HOLES = false; });
// `Array.prototype.findIndex` method
// https://tc39.github.io/ecma262/#sec-array.prototype.findindex
$({ target: 'Array', proto: true, forced: SKIPS_HOLES || !USES_TO_LENGTH }, {
findIndex: function findIndex(callbackfn /* , that = undefined */) {
return $findIndex(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
// https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables
addToUnscopables(FIND_INDEX);
/***/ }),
/***/ "../../node_modules/core-js/modules/es.array.find.js":
/*!**********************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/modules/es.array.find.js ***!
\**********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $ = __webpack_require__(/*! ../internals/export */ "../../node_modules/core-js/internals/export.js");
var $find = __webpack_require__(/*! ../internals/array-iteration */ "../../node_modules/core-js/internals/array-iteration.js").find;
var addToUnscopables = __webpack_require__(/*! ../internals/add-to-unscopables */ "../../node_modules/core-js/internals/add-to-unscopables.js");
var arrayMethodUsesToLength = __webpack_require__(/*! ../internals/array-method-uses-to-length */ "../../node_modules/core-js/internals/array-method-uses-to-length.js");
var FIND = 'find';
var SKIPS_HOLES = true;
var USES_TO_LENGTH = arrayMethodUsesToLength(FIND);
// Shouldn't skip holes
if (FIND in []) Array(1)[FIND](function () { SKIPS_HOLES = false; });
// `Array.prototype.find` method
// https://tc39.github.io/ecma262/#sec-array.prototype.find
$({ target: 'Array', proto: true, forced: SKIPS_HOLES || !USES_TO_LENGTH }, {
find: function find(callbackfn /* , that = undefined */) {
return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
// https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables
addToUnscopables(FIND);
/***/ }),
/***/ "../../node_modules/core-js/modules/es.array.flat-map.js":
/*!**************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/modules/es.array.flat-map.js ***!
\**************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $ = __webpack_require__(/*! ../internals/export */ "../../node_modules/core-js/internals/export.js");
var flattenIntoArray = __webpack_require__(/*! ../internals/flatten-into-array */ "../../node_modules/core-js/internals/flatten-into-array.js");
var toObject = __webpack_require__(/*! ../internals/to-object */ "../../node_modules/core-js/internals/to-object.js");
var toLength = __webpack_require__(/*! ../internals/to-length */ "../../node_modules/core-js/internals/to-length.js");
var aFunction = __webpack_require__(/*! ../internals/a-function */ "../../node_modules/core-js/internals/a-function.js");
var arraySpeciesCreate = __webpack_require__(/*! ../internals/array-species-create */ "../../node_modules/core-js/internals/array-species-create.js");
// `Array.prototype.flatMap` method
// https://github.com/tc39/proposal-flatMap
$({ target: 'Array', proto: true }, {
flatMap: function flatMap(callbackfn /* , thisArg */) {
var O = toObject(this);
var sourceLen = toLength(O.length);
var A;
aFunction(callbackfn);
A = arraySpeciesCreate(O, 0);
A.length = flattenIntoArray(A, O, O, sourceLen, 0, 1, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
return A;
}
});
/***/ }),
/***/ "../../node_modules/core-js/modules/es.array.flat.js":
/*!**********************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/modules/es.array.flat.js ***!
\**********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $ = __webpack_require__(/*! ../internals/export */ "../../node_modules/core-js/internals/export.js");
var flattenIntoArray = __webpack_require__(/*! ../internals/flatten-into-array */ "../../node_modules/core-js/internals/flatten-into-array.js");
var toObject = __webpack_require__(/*! ../internals/to-object */ "../../node_modules/core-js/internals/to-object.js");
var toLength = __webpack_require__(/*! ../internals/to-length */ "../../node_modules/core-js/internals/to-length.js");
var toInteger = __webpack_require__(/*! ../internals/to-integer */ "../../node_modules/core-js/internals/to-integer.js");
var arraySpeciesCreate = __webpack_require__(/*! ../internals/array-species-create */ "../../node_modules/core-js/internals/array-species-create.js");
// `Array.prototype.flat` method
// https://github.com/tc39/proposal-flatMap
$({ target: 'Array', proto: true }, {
flat: function flat(/* depthArg = 1 */) {
var depthArg = arguments.length ? arguments[0] : undefined;
var O = toObject(this);
var sourceLen = toLength(O.length);
var A = arraySpeciesCreate(O, 0);
A.length = flattenIntoArray(A, O, O, sourceLen, 0, depthArg === undefined ? 1 : toInteger(depthArg));
return A;
}
});
/***/ }),
/***/ "../../node_modules/core-js/modules/es.array.for-each.js":
/*!**************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/modules/es.array.for-each.js ***!
\**************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $ = __webpack_require__(/*! ../internals/export */ "../../node_modules/core-js/internals/export.js");
var forEach = __webpack_require__(/*! ../internals/array-for-each */ "../../node_modules/core-js/internals/array-for-each.js");
// `Array.prototype.forEach` method
// https://tc39.github.io/ecma262/#sec-array.prototype.foreach
$({ target: 'Array', proto: true, forced: [].forEach != forEach }, {
forEach: forEach
});
/***/ }),
/***/ "../../node_modules/core-js/modules/es.array.from.js":
/*!**********************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/modules/es.array.from.js ***!
\**********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var $ = __webpack_require__(/*! ../internals/export */ "../../node_modules/core-js/internals/export.js");
var from = __webpack_require__(/*! ../internals/array-from */ "../../node_modules/core-js/internals/array-from.js");
var checkCorrectnessOfIteration = __webpack_require__(/*! ../internals/check-correctness-of-iteration */ "../../node_modules/core-js/internals/check-correctness-of-iteration.js");
var INCORRECT_ITERATION = !checkCorrectnessOfIteration(function (iterable) {
Array.from(iterable);
});
// `Array.from` method
// https://tc39.github.io/ecma262/#sec-array.from
$({ target: 'Array', stat: true, forced: INCORRECT_ITERATION }, {
from: from
});
/***/ }),
/***/ "../../node_modules/core-js/modules/es.array.includes.js":
/*!**************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/modules/es.array.includes.js ***!
\**************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $ = __webpack_require__(/*! ../internals/export */ "../../node_modules/core-js/internals/export.js");
var $includes = __webpack_require__(/*! ../internals/array-includes */ "../../node_modules/core-js/internals/array-includes.js").includes;
var addToUnscopables = __webpack_require__(/*! ../internals/add-to-unscopables */ "../../node_modules/core-js/internals/add-to-unscopables.js");
var arrayMethodUsesToLength = __webpack_require__(/*! ../internals/array-method-uses-to-length */ "../../node_modules/core-js/internals/array-method-uses-to-length.js");
var USES_TO_LENGTH = arrayMethodUsesToLength('indexOf', { ACCESSORS: true, 1: 0 });
// `Array.prototype.includes` method
// https://tc39.github.io/ecma262/#sec-array.prototype.includes
$({ target: 'Array', proto: true, forced: !USES_TO_LENGTH }, {
includes: function includes(el /* , fromIndex = 0 */) {
return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined);
}
});
// https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables
addToUnscopables('includes');
/***/ }),
/***/ "../../node_modules/core-js/modules/es.array.index-of.js":
/*!**************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/modules/es.array.index-of.js ***!
\**************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $ = __webpack_require__(/*! ../internals/export */ "../../node_modules/core-js/internals/export.js");
var $indexOf = __webpack_require__(/*! ../internals/array-includes */ "../../node_modules/core-js/internals/array-includes.js").indexOf;
var arrayMethodIsStrict = __webpack_require__(/*! ../internals/array-method-is-strict */ "../../node_modules/core-js/internals/array-method-is-strict.js");
var arrayMethodUsesToLength = __webpack_require__(/*! ../internals/array-method-uses-to-length */ "../../node_modules/core-js/internals/array-method-uses-to-length.js");
var nativeIndexOf = [].indexOf;
var NEGATIVE_ZERO = !!nativeIndexOf && 1 / [1].indexOf(1, -0) < 0;
var STRICT_METHOD = arrayMethodIsStrict('indexOf');
var USES_TO_LENGTH = arrayMethodUsesToLength('indexOf', { ACCESSORS: true, 1: 0 });
// `Array.prototype.indexOf` method
// https://tc39.github.io/ecma262/#sec-array.prototype.indexof
$({ target: 'Array', proto: true, forced: NEGATIVE_ZERO || !STRICT_METHOD || !USES_TO_LENGTH }, {
indexOf: function indexOf(searchElement /* , fromIndex = 0 */) {
return NEGATIVE_ZERO
// convert -0 to +0
? nativeIndexOf.apply(this, arguments) || 0
: $indexOf(this, searchElement, arguments.length > 1 ? arguments[1] : undefined);
}
});
/***/ }),
/***/ "../../node_modules/core-js/modules/es.array.is-array.js":
/*!**************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/modules/es.array.is-array.js ***!
\**************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var $ = __webpack_require__(/*! ../internals/export */ "../../node_modules/core-js/internals/export.js");
var isArray = __webpack_require__(/*! ../internals/is-array */ "../../node_modules/core-js/internals/is-array.js");
// `Array.isArray` method
// https://tc39.github.io/ecma262/#sec-array.isarray
$({ target: 'Array', stat: true }, {
isArray: isArray
});
/***/ }),
/***/ "../../node_modules/core-js/modules/es.array.iterator.js":
/*!**************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/modules/es.array.iterator.js ***!
\**************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var toIndexedObject = __webpack_require__(/*! ../internals/to-indexed-object */ "../../node_modules/core-js/internals/to-indexed-object.js");
var addToUnscopables = __webpack_require__(/*! ../internals/add-to-unscopables */ "../../node_modules/core-js/internals/add-to-unscopables.js");
var Iterators = __webpack_require__(/*! ../internals/iterators */ "../../node_modules/core-js/internals/iterators.js");
var InternalStateModule = __webpack_require__(/*! ../internals/internal-state */ "../../node_modules/core-js/internals/internal-state.js");
var defineIterator = __webpack_require__(/*! ../internals/define-iterator */ "../../node_modules/core-js/internals/define-iterator.js");
var ARRAY_ITERATOR = 'Array Iterator';
var setInternalState = InternalStateModule.set;
var getInternalState = InternalStateModule.getterFor(ARRAY_ITERATOR);
// `Array.prototype.entries` method
// https://tc39.github.io/ecma262/#sec-array.prototype.entries
// `Array.prototype.keys` method
// https://tc39.github.io/ecma262/#sec-array.prototype.keys
// `Array.prototype.values` method
// https://tc39.github.io/ecma262/#sec-array.prototype.values
// `Array.prototype[@@iterator]` method
// https://tc39.github.io/ecma262/#sec-array.prototype-@@iterator
// `CreateArrayIterator` internal method
// https://tc39.github.io/ecma262/#sec-createarrayiterator
module.exports = defineIterator(Array, 'Array', function (iterated, kind) {
setInternalState(this, {
type: ARRAY_ITERATOR,
target: toIndexedObject(iterated), // target
index: 0, // next index
kind: kind // kind
});
// `%ArrayIteratorPrototype%.next` method
// https://tc39.github.io/ecma262/#sec-%arrayiteratorprototype%.next
}, function () {
var state = getInternalState(this);
var target = state.target;
var kind = state.kind;
var index = state.index++;
if (!target || index >= target.length) {
state.target = undefined;
return { value: undefined, done: true };
}
if (kind == 'keys') return { value: index, done: false };
if (kind == 'values') return { value: target[index], done: false };
return { value: [index, target[index]], done: false };
}, 'values');
// argumentsList[@@iterator] is %ArrayProto_values%
// https://tc39.github.io/ecma262/#sec-createunmappedargumentsobject
// https://tc39.github.io/ecma262/#sec-createmappedargumentsobject
Iterators.Arguments = Iterators.Array;
// https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables
addToUnscopables('keys');
addToUnscopables('values');
addToUnscopables('entries');
/***/ }),
/***/ "../../node_modules/core-js/modules/es.array.join.js":
/*!**********************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/modules/es.array.join.js ***!
\**********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $ = __webpack_require__(/*! ../internals/export */ "../../node_modules/core-js/internals/export.js");
var IndexedObject = __webpack_require__(/*! ../internals/indexed-object */ "../../node_modules/core-js/internals/indexed-object.js");
var toIndexedObject = __webpack_require__(/*! ../internals/to-indexed-object */ "../../node_modules/core-js/internals/to-indexed-object.js");
var arrayMethodIsStrict = __webpack_require__(/*! ../internals/array-method-is-strict */ "../../node_modules/core-js/internals/array-method-is-strict.js");
var nativeJoin = [].join;
var ES3_STRINGS = IndexedObject != Object;
var STRICT_METHOD = arrayMethodIsStrict('join', ',');
// `Array.prototype.join` method
// https://tc39.github.io/ecma262/#sec-array.prototype.join
$({ target: 'Array', proto: true, forced: ES3_STRINGS || !STRICT_METHOD }, {
join: function join(separator) {
return nativeJoin.call(toIndexedObject(this), separator === undefined ? ',' : separator);
}
});
/***/ }),
/***/ "../../node_modules/core-js/modules/es.array.last-index-of.js":
/*!*******************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/modules/es.array.last-index-of.js ***!
\*******************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var $ = __webpack_require__(/*! ../internals/export */ "../../node_modules/core-js/internals/export.js");
var lastIndexOf = __webpack_require__(/*! ../internals/array-last-index-of */ "../../node_modules/core-js/internals/array-last-index-of.js");
// `Array.prototype.lastIndexOf` method
// https://tc39.github.io/ecma262/#sec-array.prototype.lastindexof
$({ target: 'Array', proto: true, forced: lastIndexOf !== [].lastIndexOf }, {
lastIndexOf: lastIndexOf
});
/***/ }),
/***/ "../../node_modules/core-js/modules/es.array.map.js":
/*!*********************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/modules/es.array.map.js ***!
\*********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $ = __webpack_require__(/*! ../internals/export */ "../../node_modules/core-js/internals/export.js");
var $map = __webpack_require__(/*! ../internals/array-iteration */ "../../node_modules/core-js/internals/array-iteration.js").map;
var arrayMethodHasSpeciesSupport = __webpack_require__(/*! ../internals/array-method-has-species-support */ "../../node_modules/core-js/internals/array-method-has-species-support.js");
var arrayMethodUsesToLength = __webpack_require__(/*! ../internals/array-method-uses-to-length */ "../../node_modules/core-js/internals/array-method-uses-to-length.js");
var HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('map');
// FF49- issue
var USES_TO_LENGTH = arrayMethodUsesToLength('map');
// `Array.prototype.map` method
// https://tc39.github.io/ecma262/#sec-array.prototype.map
// with adding support of @@species
$({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT || !USES_TO_LENGTH }, {
map: function map(callbackfn /* , thisArg */) {
return $map(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
/***/ }),
/***/ "../../node_modules/core-js/modules/es.array.of.js":
/*!********************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/modules/es.array.of.js ***!
\********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $ = __webpack_require__(/*! ../internals/export */ "../../node_modules/core-js/internals/export.js");
var fails = __webpack_require__(/*! ../internals/fails */ "../../node_modules/core-js/internals/fails.js");
var createProperty = __webpack_require__(/*! ../internals/create-property */ "../../node_modules/core-js/internals/create-property.js");
var ISNT_GENERIC = fails(function () {
function F() { /* empty */ }
return !(Array.of.call(F) instanceof F);
});
// `Array.of` method
// https://tc39.github.io/ecma262/#sec-array.of
// WebKit Array.of isn't generic
$({ target: 'Array', stat: true, forced: ISNT_GENERIC }, {
of: function of(/* ...args */) {
var index = 0;
var argumentsLength = arguments.length;
var result = new (typeof this == 'function' ? this : Array)(argumentsLength);
while (argumentsLength > index) createProperty(result, index, arguments[index++]);
result.length = argumentsLength;
return result;
}
});
/***/ }),
/***/ "../../node_modules/core-js/modules/es.array.reduce-right.js":
/*!******************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/modules/es.array.reduce-right.js ***!
\******************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $ = __webpack_require__(/*! ../internals/export */ "../../node_modules/core-js/internals/export.js");
var $reduceRight = __webpack_require__(/*! ../internals/array-reduce */ "../../node_modules/core-js/internals/array-reduce.js").right;
var arrayMethodIsStrict = __webpack_require__(/*! ../internals/array-method-is-strict */ "../../node_modules/core-js/internals/array-method-is-strict.js");
var arrayMethodUsesToLength = __webpack_require__(/*! ../internals/array-method-uses-to-length */ "../../node_modules/core-js/internals/array-method-uses-to-length.js");
var STRICT_METHOD = arrayMethodIsStrict('reduceRight');
// For preventing possible almost infinite loop in non-standard implementations, test the forward version of the method
var USES_TO_LENGTH = arrayMethodUsesToLength('reduce', { 1: 0 });
// `Array.prototype.reduceRight` method
// https://tc39.github.io/ecma262/#sec-array.prototype.reduceright
$({ target: 'Array', proto: true, forced: !STRICT_METHOD || !USES_TO_LENGTH }, {
reduceRight: function reduceRight(callbackfn /* , initialValue */) {
return $reduceRight(this, callbackfn, arguments.length, arguments.length > 1 ? arguments[1] : undefined);
}
});
/***/ }),
/***/ "../../node_modules/core-js/modules/es.array.reduce.js":
/*!************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/modules/es.array.reduce.js ***!
\************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $ = __webpack_require__(/*! ../internals/export */ "../../node_modules/core-js/internals/export.js");
var $reduce = __webpack_require__(/*! ../internals/array-reduce */ "../../node_modules/core-js/internals/array-reduce.js").left;
var arrayMethodIsStrict = __webpack_require__(/*! ../internals/array-method-is-strict */ "../../node_modules/core-js/internals/array-method-is-strict.js");
var arrayMethodUsesToLength = __webpack_require__(/*! ../internals/array-method-uses-to-length */ "../../node_modules/core-js/internals/array-method-uses-to-length.js");
var STRICT_METHOD = arrayMethodIsStrict('reduce');
var USES_TO_LENGTH = arrayMethodUsesToLength('reduce', { 1: 0 });
// `Array.prototype.reduce` method
// https://tc39.github.io/ecma262/#sec-array.prototype.reduce
$({ target: 'Array', proto: true, forced: !STRICT_METHOD || !USES_TO_LENGTH }, {
reduce: function reduce(callbackfn /* , initialValue */) {
return $reduce(this, callbackfn, arguments.length, arguments.length > 1 ? arguments[1] : undefined);
}
});
/***/ }),
/***/ "../../node_modules/core-js/modules/es.array.reverse.js":
/*!*************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/modules/es.array.reverse.js ***!
\*************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $ = __webpack_require__(/*! ../internals/export */ "../../node_modules/core-js/internals/export.js");
var isArray = __webpack_require__(/*! ../internals/is-array */ "../../node_modules/core-js/internals/is-array.js");
var nativeReverse = [].reverse;
var test = [1, 2];
// `Array.prototype.reverse` method
// https://tc39.github.io/ecma262/#sec-array.prototype.reverse
// fix for Safari 12.0 bug
// https://bugs.webkit.org/show_bug.cgi?id=188794
$({ target: 'Array', proto: true, forced: String(test) === String(test.reverse()) }, {
reverse: function reverse() {
// eslint-disable-next-line no-self-assign
if (isArray(this)) this.length = this.length;
return nativeReverse.call(this);
}
});
/***/ }),
/***/ "../../node_modules/core-js/modules/es.array.slice.js":
/*!***********************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/modules/es.array.slice.js ***!
\***********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $ = __webpack_require__(/*! ../internals/export */ "../../node_modules/core-js/internals/export.js");
var isObject = __webpack_require__(/*! ../internals/is-object */ "../../node_modules/core-js/internals/is-object.js");
var isArray = __webpack_require__(/*! ../internals/is-array */ "../../node_modules/core-js/internals/is-array.js");
var toAbsoluteIndex = __webpack_require__(/*! ../internals/to-absolute-index */ "../../node_modules/core-js/internals/to-absolute-index.js");
var toLength = __webpack_require__(/*! ../internals/to-length */ "../../node_modules/core-js/internals/to-length.js");
var toIndexedObject = __webpack_require__(/*! ../internals/to-indexed-object */ "../../node_modules/core-js/internals/to-indexed-object.js");
var createProperty = __webpack_require__(/*! ../internals/create-property */ "../../node_modules/core-js/internals/create-property.js");
var wellKnownSymbol = __webpack_require__(/*! ../internals/well-known-symbol */ "../../node_modules/core-js/internals/well-known-symbol.js");
var arrayMethodHasSpeciesSupport = __webpack_require__(/*! ../internals/array-method-has-species-support */ "../../node_modules/core-js/internals/array-method-has-species-support.js");
var arrayMethodUsesToLength = __webpack_require__(/*! ../internals/array-method-uses-to-length */ "../../node_modules/core-js/internals/array-method-uses-to-length.js");
var HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('slice');
var USES_TO_LENGTH = arrayMethodUsesToLength('slice', { ACCESSORS: true, 0: 0, 1: 2 });
var SPECIES = wellKnownSymbol('species');
var nativeSlice = [].slice;
var max = Math.max;
// `Array.prototype.slice` method
// https://tc39.github.io/ecma262/#sec-array.prototype.slice
// fallback for not array-like ES3 strings and DOM objects
$({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT || !USES_TO_LENGTH }, {
slice: function slice(start, end) {
var O = toIndexedObject(this);
var length = toLength(O.length);
var k = toAbsoluteIndex(start, length);
var fin = toAbsoluteIndex(end === undefined ? length : end, length);
// inline `ArraySpeciesCreate` for usage native `Array#slice` where it's possible
var Constructor, result, n;
if (isArray(O)) {
Constructor = O.constructor;
// cross-realm fallback
if (typeof Constructor == 'function' && (Constructor === Array || isArray(Constructor.prototype))) {
Constructor = undefined;
} else if (isObject(Constructor)) {
Constructor = Constructor[SPECIES];
if (Constructor === null) Constructor = undefined;
}
if (Constructor === Array || Constructor === undefined) {
return nativeSlice.call(O, k, fin);
}
}
result = new (Constructor === undefined ? Array : Constructor)(max(fin - k, 0));
for (n = 0; k < fin; k++, n++) if (k in O) createProperty(result, n, O[k]);
result.length = n;
return result;
}
});
/***/ }),
/***/ "../../node_modules/core-js/modules/es.array.some.js":
/*!**********************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/modules/es.array.some.js ***!
\**********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $ = __webpack_require__(/*! ../internals/export */ "../../node_modules/core-js/internals/export.js");
var $some = __webpack_require__(/*! ../internals/array-iteration */ "../../node_modules/core-js/internals/array-iteration.js").some;
var arrayMethodIsStrict = __webpack_require__(/*! ../internals/array-method-is-strict */ "../../node_modules/core-js/internals/array-method-is-strict.js");
var arrayMethodUsesToLength = __webpack_require__(/*! ../internals/array-method-uses-to-length */ "../../node_modules/core-js/internals/array-method-uses-to-length.js");
var STRICT_METHOD = arrayMethodIsStrict('some');
var USES_TO_LENGTH = arrayMethodUsesToLength('some');
// `Array.prototype.some` method
// https://tc39.github.io/ecma262/#sec-array.prototype.some
$({ target: 'Array', proto: true, forced: !STRICT_METHOD || !USES_TO_LENGTH }, {
some: function some(callbackfn /* , thisArg */) {
return $some(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
/***/ }),
/***/ "../../node_modules/core-js/modules/es.array.sort.js":
/*!**********************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/modules/es.array.sort.js ***!
\**********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $ = __webpack_require__(/*! ../internals/export */ "../../node_modules/core-js/internals/export.js");
var aFunction = __webpack_require__(/*! ../internals/a-function */ "../../node_modules/core-js/internals/a-function.js");
var toObject = __webpack_require__(/*! ../internals/to-object */ "../../node_modules/core-js/internals/to-object.js");
var fails = __webpack_require__(/*! ../internals/fails */ "../../node_modules/core-js/internals/fails.js");
var arrayMethodIsStrict = __webpack_require__(/*! ../internals/array-method-is-strict */ "../../node_modules/core-js/internals/array-method-is-strict.js");
var test = [];
var nativeSort = test.sort;
// IE8-
var FAILS_ON_UNDEFINED = fails(function () {
test.sort(undefined);
});
// V8 bug
var FAILS_ON_NULL = fails(function () {
test.sort(null);
});
// Old WebKit
var STRICT_METHOD = arrayMethodIsStrict('sort');
var FORCED = FAILS_ON_UNDEFINED || !FAILS_ON_NULL || !STRICT_METHOD;
// `Array.prototype.sort` method
// https://tc39.github.io/ecma262/#sec-array.prototype.sort
$({ target: 'Array', proto: true, forced: FORCED }, {
sort: function sort(comparefn) {
return comparefn === undefined
? nativeSort.call(toObject(this))
: nativeSort.call(toObject(this), aFunction(comparefn));
}
});
/***/ }),
/***/ "../../node_modules/core-js/modules/es.array.species.js":
/*!*************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/modules/es.array.species.js ***!
\*************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var setSpecies = __webpack_require__(/*! ../internals/set-species */ "../../node_modules/core-js/internals/set-species.js");
// `Array[@@species]` getter
// https://tc39.github.io/ecma262/#sec-get-array-@@species
setSpecies('Array');
/***/ }),
/***/ "../../node_modules/core-js/modules/es.array.splice.js":
/*!************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/modules/es.array.splice.js ***!
\************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $ = __webpack_require__(/*! ../internals/export */ "../../node_modules/core-js/internals/export.js");
var toAbsoluteIndex = __webpack_require__(/*! ../internals/to-absolute-index */ "../../node_modules/core-js/internals/to-absolute-index.js");
var toInteger = __webpack_require__(/*! ../internals/to-integer */ "../../node_modules/core-js/internals/to-integer.js");
var toLength = __webpack_require__(/*! ../internals/to-length */ "../../node_modules/core-js/internals/to-length.js");
var toObject = __webpack_require__(/*! ../internals/to-object */ "../../node_modules/core-js/internals/to-object.js");
var arraySpeciesCreate = __webpack_require__(/*! ../internals/array-species-create */ "../../node_modules/core-js/internals/array-species-create.js");
var createProperty = __webpack_require__(/*! ../internals/create-property */ "../../node_modules/core-js/internals/create-property.js");
var arrayMethodHasSpeciesSupport = __webpack_require__(/*! ../internals/array-method-has-species-support */ "../../node_modules/core-js/internals/array-method-has-species-support.js");
var arrayMethodUsesToLength = __webpack_require__(/*! ../internals/array-method-uses-to-length */ "../../node_modules/core-js/internals/array-method-uses-to-length.js");
var HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('splice');
var USES_TO_LENGTH = arrayMethodUsesToLength('splice', { ACCESSORS: true, 0: 0, 1: 2 });
var max = Math.max;
var min = Math.min;
var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF;
var MAXIMUM_ALLOWED_LENGTH_EXCEEDED = 'Maximum allowed length exceeded';
// `Array.prototype.splice` method
// https://tc39.github.io/ecma262/#sec-array.prototype.splice
// with adding support of @@species
$({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT || !USES_TO_LENGTH }, {
splice: function splice(start, deleteCount /* , ...items */) {
var O = toObject(this);
var len = toLength(O.length);
var actualStart = toAbsoluteIndex(start, len);
var argumentsLength = arguments.length;
var insertCount, actualDeleteCount, A, k, from, to;
if (argumentsLength === 0) {
insertCount = actualDeleteCount = 0;
} else if (argumentsLength === 1) {
insertCount = 0;
actualDeleteCount = len - actualStart;
} else {
insertCount = argumentsLength - 2;
actualDeleteCount = min(max(toInteger(deleteCount), 0), len - actualStart);
}
if (len + insertCount - actualDeleteCount > MAX_SAFE_INTEGER) {
throw TypeError(MAXIMUM_ALLOWED_LENGTH_EXCEEDED);
}
A = arraySpeciesCreate(O, actualDeleteCount);
for (k = 0; k < actualDeleteCount; k++) {
from = actualStart + k;
if (from in O) createProperty(A, k, O[from]);
}
A.length = actualDeleteCount;
if (insertCount < actualDeleteCount) {
for (k = actualStart; k < len - actualDeleteCount; k++) {
from = k + actualDeleteCount;
to = k + insertCount;
if (from in O) O[to] = O[from];
else delete O[to];
}
for (k = len; k > len - actualDeleteCount + insertCount; k--) delete O[k - 1];
} else if (insertCount > actualDeleteCount) {
for (k = len - actualDeleteCount; k > actualStart; k--) {
from = k + actualDeleteCount - 1;
to = k + insertCount - 1;
if (from in O) O[to] = O[from];
else delete O[to];
}
}
for (k = 0; k < insertCount; k++) {
O[k + actualStart] = arguments[k + 2];
}
O.length = len - actualDeleteCount + insertCount;
return A;
}
});
/***/ }),
/***/ "../../node_modules/core-js/modules/es.array.unscopables.flat-map.js":
/*!**************************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/modules/es.array.unscopables.flat-map.js ***!
\**************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
// this method was added to unscopables after implementation
// in popular engines, so it's moved to a separate module
var addToUnscopables = __webpack_require__(/*! ../internals/add-to-unscopables */ "../../node_modules/core-js/internals/add-to-unscopables.js");
addToUnscopables('flatMap');
/***/ }),
/***/ "../../node_modules/core-js/modules/es.array.unscopables.flat.js":
/*!**********************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/modules/es.array.unscopables.flat.js ***!
\**********************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
// this method was added to unscopables after implementation
// in popular engines, so it's moved to a separate module
var addToUnscopables = __webpack_require__(/*! ../internals/add-to-unscopables */ "../../node_modules/core-js/internals/add-to-unscopables.js");
addToUnscopables('flat');
/***/ }),
/***/ "../../node_modules/core-js/modules/es.function.bind.js":
/*!*************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/modules/es.function.bind.js ***!
\*************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var $ = __webpack_require__(/*! ../internals/export */ "../../node_modules/core-js/internals/export.js");
var bind = __webpack_require__(/*! ../internals/function-bind */ "../../node_modules/core-js/internals/function-bind.js");
// `Function.prototype.bind` method
// https://tc39.github.io/ecma262/#sec-function.prototype.bind
$({ target: 'Function', proto: true }, {
bind: bind
});
/***/ }),
/***/ "../../node_modules/core-js/modules/es.function.has-instance.js":
/*!*********************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/modules/es.function.has-instance.js ***!
\*********************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var isObject = __webpack_require__(/*! ../internals/is-object */ "../../node_modules/core-js/internals/is-object.js");
var definePropertyModule = __webpack_require__(/*! ../internals/object-define-property */ "../../node_modules/core-js/internals/object-define-property.js");
var getPrototypeOf = __webpack_require__(/*! ../internals/object-get-prototype-of */ "../../node_modules/core-js/internals/object-get-prototype-of.js");
var wellKnownSymbol = __webpack_require__(/*! ../internals/well-known-symbol */ "../../node_modules/core-js/internals/well-known-symbol.js");
var HAS_INSTANCE = wellKnownSymbol('hasInstance');
var FunctionPrototype = Function.prototype;
// `Function.prototype[@@hasInstance]` method
// https://tc39.github.io/ecma262/#sec-function.prototype-@@hasinstance
if (!(HAS_INSTANCE in FunctionPrototype)) {
definePropertyModule.f(FunctionPrototype, HAS_INSTANCE, { value: function (O) {
if (typeof this != 'function' || !isObject(O)) return false;
if (!isObject(this.prototype)) return O instanceof this;
// for environment w/o native `@@hasInstance` logic enough `instanceof`, but add this:
while (O = getPrototypeOf(O)) if (this.prototype === O) return true;
return false;
} });
}
/***/ }),
/***/ "../../node_modules/core-js/modules/es.function.name.js":
/*!*************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/modules/es.function.name.js ***!
\*************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var DESCRIPTORS = __webpack_require__(/*! ../internals/descriptors */ "../../node_modules/core-js/internals/descriptors.js");
var defineProperty = __webpack_require__(/*! ../internals/object-define-property */ "../../node_modules/core-js/internals/object-define-property.js").f;
var FunctionPrototype = Function.prototype;
var FunctionPrototypeToString = FunctionPrototype.toString;
var nameRE = /^\s*function ([^ (]*)/;
var NAME = 'name';
// Function instances `.name` property
// https://tc39.github.io/ecma262/#sec-function-instances-name
if (DESCRIPTORS && !(NAME in FunctionPrototype)) {
defineProperty(FunctionPrototype, NAME, {
configurable: true,
get: function () {
try {
return FunctionPrototypeToString.call(this).match(nameRE)[1];
} catch (error) {
return '';
}
}
});
}
/***/ }),
/***/ "../../node_modules/core-js/modules/es.string.iterator.js":
/*!***************************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/core-js/modules/es.string.iterator.js ***!
\***************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var charAt = __webpack_require__(/*! ../internals/string-multibyte */ "../../node_modules/core-js/internals/string-multibyte.js").charAt;
var InternalStateModule = __webpack_require__(/*! ../internals/internal-state */ "../../node_modules/core-js/internals/internal-state.js");
var defineIterator = __webpack_require__(/*! ../internals/define-iterator */ "../../node_modules/core-js/internals/define-iterator.js");
var STRING_ITERATOR = 'String Iterator';
var setInternalState = InternalStateModule.set;
var getInternalState = InternalStateModule.getterFor(STRING_ITERATOR);
// `String.prototype[@@iterator]` method
// https://tc39.github.io/ecma262/#sec-string.prototype-@@iterator
defineIterator(String, 'String', function (iterated) {
setInternalState(this, {
type: STRING_ITERATOR,
string: String(iterated),
index: 0
});
// `%StringIteratorPrototype%.next` method
// https://tc39.github.io/ecma262/#sec-%stringiteratorprototype%.next
}, function next() {
var state = getInternalState(this);
var string = state.string;
var index = state.index;
var point;
if (index >= string.length) return { value: undefined, done: true };
point = charAt(string, index);
state.index += point.length;
return { value: point, done: false };
});
/***/ }),
/***/ "../../node_modules/css-loader/dist/runtime/api.js":
/*!********************************************************************************************!*\
!*** /home/travis/build/excaliburjs/Excalibur/node_modules/css-loader/dist/runtime/api.js ***!
\********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
// css base code, injected by the css-loader
// eslint-disable-next-line func-names
module.exports = function (useSourceMap) {
var list = []; // return the list of modules as css string
list.toString = function toString() {
return this.map(function (item) {
var content = cssWithMappingToString(item, useSourceMap);
if (item[2]) {
return "@media ".concat(item[2], " {").concat(content, "}");
}
return content;
}).join('');
}; // import a list of modules into the list
// eslint-disable-next-line func-names
list.i = function (modules, mediaQuery, dedupe) {
if (typeof modules === 'string') {
// eslint-disable-next-line no-param-reassign
modules = [[null, modules, '']];
}
var alreadyImportedModules = {};
if (dedupe) {
for (var i = 0; i < this.length; i++) {
// eslint-disable-next-line prefer-destructuring
var id = this[i][0];
if (id != null) {
alreadyImportedModules[id] = true;
}
}
}
for (var _i = 0; _i < modules.length; _i++) {
var item = [].concat(modules[_i]);
if (dedupe && alreadyImportedModules[item[0]]) {
// eslint-disable-next-line no-continue
continue;
}
if (mediaQuery) {
if (!item[2]) {
item[2] = mediaQuery;
} else {
item[2] = "".concat(mediaQuery, " and ").concat(item[2]);
}
}
list.push(item);
}
};
return list;
};
function cssWithMappingToString(item, useSourceMap) {
var content = item[1] || ''; // eslint-disable-next-line prefer-destructuring
var cssMapping = item[3];
if (!cssMapping) {
return content;
}
if (useSourceMap && typeof btoa === 'function') {
var sourceMapping = toComment(cssMapping);
var sourceURLs = cssMapping.sources.map(function (source) {
return "/*# sourceURL=".concat(cssMapping.sourceRoot || '').concat(source, " */");
});
return [content].concat(sourceURLs).concat([sourceMapping]).join('\n');
}
return [content].join('\n');
} // Adapted from convert-source-map (MIT)
function toComment(sourceMap) {
// eslint-disable-next-line no-undef
var base64 = btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap))));
var data = "sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(base64);
return "/*# ".concat(data, " */");
}
/***/ }),
/***/ "../../node_modules/webpack/buildin/global.js":
/*!***********************************!*\
!*** (webpack)/buildin/global.js ***!
\***********************************/
/*! no static exports found */
/***/ (function(module, exports) {
var g;
// This works in non-strict mode
g = (function() {
return this;
})();
try {
// This works if eval is allowed (see CSP)
g = g || new Function("return this")();
} catch (e) {
// This works if the window reference is available
if (typeof window === "object") g = window;
}
// g can still be undefined, but nothing to do about it...
// We return undefined, instead of nothing here, so it's
// easier to handle this case. if(!global) { ...}
module.exports = g;
/***/ }),
/***/ "./Actions/Action.ts":
/*!***************************!*\
!*** ./Actions/Action.ts ***!
\***************************/
/*! exports provided: EaseTo, MoveTo, MoveBy, Follow, Meet, RotateTo, RotateBy, ScaleTo, ScaleBy, Delay, Blink, Fade, Die, CallMethod, Repeat, RepeatForever, ActionQueue */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EaseTo", function() { return EaseTo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MoveTo", function() { return MoveTo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MoveBy", function() { return MoveBy; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Follow", function() { return Follow; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Meet", function() { return Meet; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RotateTo", function() { return RotateTo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RotateBy", function() { return RotateBy; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ScaleTo", function() { return ScaleTo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ScaleBy", function() { return ScaleBy; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Delay", function() { return Delay; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Blink", function() { return Blink; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Fade", function() { return Fade; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Die", function() { return Die; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CallMethod", function() { return CallMethod; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Repeat", function() { return Repeat; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RepeatForever", function() { return RepeatForever; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ActionQueue", function() { return ActionQueue; });
/* harmony import */ var _RotationType__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./RotationType */ "./Actions/RotationType.ts");
/* harmony import */ var _Algebra__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Algebra */ "./Algebra.ts");
/* harmony import */ var _Util_Log__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Util/Log */ "./Util/Log.ts");
/* harmony import */ var _Util_Util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Util/Util */ "./Util/Util.ts");
/* harmony import */ var _Util_Decorators__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Util/Decorators */ "./Util/Decorators.ts");
var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var EaseTo = /** @class */ (function () {
function EaseTo(actor, x, y, duration, easingFcn) {
this.actor = actor;
this.easingFcn = easingFcn;
this._currentLerpTime = 0;
this._lerpDuration = 1 * 1000; // 1 second
this._lerpStart = new _Algebra__WEBPACK_IMPORTED_MODULE_1__["Vector"](0, 0);
this._lerpEnd = new _Algebra__WEBPACK_IMPORTED_MODULE_1__["Vector"](0, 0);
this._initialized = false;
this._stopped = false;
this._distance = 0;
this._lerpDuration = duration;
this._lerpEnd = new _Algebra__WEBPACK_IMPORTED_MODULE_1__["Vector"](x, y);
}
EaseTo.prototype._initialize = function () {
this._lerpStart = new _Algebra__WEBPACK_IMPORTED_MODULE_1__["Vector"](this.actor.pos.x, this.actor.pos.y);
this._currentLerpTime = 0;
this._distance = this._lerpStart.distance(this._lerpEnd);
};
EaseTo.prototype.update = function (delta) {
if (!this._initialized) {
this._initialize();
this._initialized = true;
}
var newX = this.actor.pos.x;
var newY = this.actor.pos.y;
if (this._currentLerpTime < this._lerpDuration) {
if (this._lerpEnd.x < this._lerpStart.x) {
newX =
this._lerpStart.x -
(this.easingFcn(this._currentLerpTime, this._lerpEnd.x, this._lerpStart.x, this._lerpDuration) - this._lerpEnd.x);
}
else {
newX = this.easingFcn(this._currentLerpTime, this._lerpStart.x, this._lerpEnd.x, this._lerpDuration);
}
if (this._lerpEnd.y < this._lerpStart.y) {
newY =
this._lerpStart.y -
(this.easingFcn(this._currentLerpTime, this._lerpEnd.y, this._lerpStart.y, this._lerpDuration) - this._lerpEnd.y);
}
else {
newY = this.easingFcn(this._currentLerpTime, this._lerpStart.y, this._lerpEnd.y, this._lerpDuration);
}
this.actor.pos.x = newX;
this.actor.pos.y = newY;
this._currentLerpTime += delta;
}
else {
this.actor.pos.x = this._lerpEnd.x;
this.actor.pos.y = this._lerpEnd.y;
//this._lerpStart = null;
//this._lerpEnd = null;
//this._currentLerpTime = 0;
}
};
EaseTo.prototype.isComplete = function (actor) {
return this._stopped || new _Algebra__WEBPACK_IMPORTED_MODULE_1__["Vector"](actor.pos.x, actor.pos.y).distance(this._lerpStart) >= this._distance;
};
EaseTo.prototype.reset = function () {
this._initialized = false;
};
EaseTo.prototype.stop = function () {
this._stopped = true;
};
return EaseTo;
}());
var MoveTo = /** @class */ (function () {
function MoveTo(actor, destx, desty, speed) {
this._started = false;
this._stopped = false;
this._actor = actor;
this._end = new _Algebra__WEBPACK_IMPORTED_MODULE_1__["Vector"](destx, desty);
this._speed = speed;
}
MoveTo.prototype.update = function (_delta) {
if (!this._started) {
this._started = true;
this._start = new _Algebra__WEBPACK_IMPORTED_MODULE_1__["Vector"](this._actor.pos.x, this._actor.pos.y);
this._distance = this._start.distance(this._end);
this._dir = this._end.sub(this._start).normalize();
}
var m = this._dir.scale(this._speed);
this._actor.vel.x = m.x;
this._actor.vel.y = m.y;
if (this.isComplete(this._actor)) {
this._actor.pos.x = this._end.x;
this._actor.pos.y = this._end.y;
this._actor.vel.y = 0;
this._actor.vel.x = 0;
}
};
MoveTo.prototype.isComplete = function (actor) {
return this._stopped || new _Algebra__WEBPACK_IMPORTED_MODULE_1__["Vector"](actor.pos.x, actor.pos.y).distance(this._start) >= this._distance;
};
MoveTo.prototype.stop = function () {
this._actor.vel.y = 0;
this._actor.vel.x = 0;
this._stopped = true;
};
MoveTo.prototype.reset = function () {
this._started = false;
};
return MoveTo;
}());
var MoveBy = /** @class */ (function () {
function MoveBy(actor, offsetX, offsetY, speed) {
this._started = false;
this._stopped = false;
this._actor = actor;
this._speed = speed;
this._offset = new _Algebra__WEBPACK_IMPORTED_MODULE_1__["Vector"](offsetX, offsetY);
if (speed <= 0) {
_Util_Log__WEBPACK_IMPORTED_MODULE_2__["Logger"].getInstance().error('Attempted to moveBy with speed less than or equal to zero : ' + speed);
throw new Error('Speed must be greater than 0 pixels per second');
}
}
MoveBy.prototype.update = function (_delta) {
if (!this._started) {
this._started = true;
this._start = new _Algebra__WEBPACK_IMPORTED_MODULE_1__["Vector"](this._actor.pos.x, this._actor.pos.y);
this._end = this._start.add(this._offset);
this._distance = this._offset.size;
this._dir = this._end.sub(this._start).normalize();
}
this._actor.vel = this._dir.scale(this._speed);
if (this.isComplete(this._actor)) {
this._actor.pos.x = this._end.x;
this._actor.pos.y = this._end.y;
this._actor.vel.y = 0;
this._actor.vel.x = 0;
}
};
MoveBy.prototype.isComplete = function (actor) {
return this._stopped || actor.pos.distance(this._start) >= this._distance;
};
MoveBy.prototype.stop = function () {
this._actor.vel.y = 0;
this._actor.vel.x = 0;
this._stopped = true;
};
MoveBy.prototype.reset = function () {
this._started = false;
};
return MoveBy;
}());
var Follow = /** @class */ (function () {
function Follow(actor, actorToFollow, followDistance) {
this._started = false;
this._stopped = false;
this._actor = actor;
this._actorToFollow = actorToFollow;
this._current = new _Algebra__WEBPACK_IMPORTED_MODULE_1__["Vector"](this._actor.pos.x, this._actor.pos.y);
this._end = new _Algebra__WEBPACK_IMPORTED_MODULE_1__["Vector"](actorToFollow.pos.x, actorToFollow.pos.y);
this._maximumDistance = followDistance !== undefined ? followDistance : this._current.distance(this._end);
this._speed = 0;
}
Follow.prototype.update = function (_delta) {
if (!this._started) {
this._started = true;
this._distanceBetween = this._current.distance(this._end);
this._dir = this._end.sub(this._current).normalize();
}
var actorToFollowSpeed = Math.sqrt(Math.pow(this._actorToFollow.vel.x, 2) + Math.pow(this._actorToFollow.vel.y, 2));
if (actorToFollowSpeed !== 0) {
this._speed = actorToFollowSpeed;
}
this._current.x = this._actor.pos.x;
this._current.y = this._actor.pos.y;
this._end.x = this._actorToFollow.pos.x;
this._end.y = this._actorToFollow.pos.y;
this._distanceBetween = this._current.distance(this._end);
this._dir = this._end.sub(this._current).normalize();
if (this._distanceBetween >= this._maximumDistance) {
var m = this._dir.scale(this._speed);
this._actor.vel.x = m.x;
this._actor.vel.y = m.y;
}
else {
this._actor.vel.x = 0;
this._actor.vel.y = 0;
}
if (this.isComplete()) {
this._actor.pos.x = this._end.x;
this._actor.pos.y = this._end.y;
this._actor.vel.y = 0;
this._actor.vel.x = 0;
}
};
Follow.prototype.stop = function () {
this._actor.vel.y = 0;
this._actor.vel.x = 0;
this._stopped = true;
};
Follow.prototype.isComplete = function () {
// the actor following should never stop unless specified to do so
return this._stopped;
};
Follow.prototype.reset = function () {
this._started = false;
};
return Follow;
}());
var Meet = /** @class */ (function () {
function Meet(actor, actorToMeet, speed) {
this._started = false;
this._stopped = false;
this._speedWasSpecified = false;
this._actor = actor;
this._actorToMeet = actorToMeet;
this._current = new _Algebra__WEBPACK_IMPORTED_MODULE_1__["Vector"](this._actor.pos.x, this._actor.pos.y);
this._end = new _Algebra__WEBPACK_IMPORTED_MODULE_1__["Vector"](actorToMeet.pos.x, actorToMeet.pos.y);
this._speed = speed || 0;
if (speed !== undefined) {
this._speedWasSpecified = true;
}
}
Meet.prototype.update = function (_delta) {
if (!this._started) {
this._started = true;
this._distanceBetween = this._current.distance(this._end);
this._dir = this._end.sub(this._current).normalize();
}
var actorToMeetSpeed = Math.sqrt(Math.pow(this._actorToMeet.vel.x, 2) + Math.pow(this._actorToMeet.vel.y, 2));
if (actorToMeetSpeed !== 0 && !this._speedWasSpecified) {
this._speed = actorToMeetSpeed;
}
this._current.x = this._actor.pos.x;
this._current.y = this._actor.pos.y;
this._end.x = this._actorToMeet.pos.x;
this._end.y = this._actorToMeet.pos.y;
this._distanceBetween = this._current.distance(this._end);
this._dir = this._end.sub(this._current).normalize();
var m = this._dir.scale(this._speed);
this._actor.vel.x = m.x;
this._actor.vel.y = m.y;
if (this.isComplete()) {
this._actor.pos.x = this._end.x;
this._actor.pos.y = this._end.y;
this._actor.vel.y = 0;
this._actor.vel.x = 0;
}
};
Meet.prototype.isComplete = function () {
return this._stopped || this._distanceBetween <= 1;
};
Meet.prototype.stop = function () {
this._actor.vel.y = 0;
this._actor.vel.x = 0;
this._stopped = true;
};
Meet.prototype.reset = function () {
this._started = false;
};
return Meet;
}());
var RotateTo = /** @class */ (function () {
function RotateTo(actor, angleRadians, speed, rotationType) {
this._started = false;
this._stopped = false;
this._actor = actor;
this._end = angleRadians;
this._speed = speed;
this._rotationType = rotationType || _RotationType__WEBPACK_IMPORTED_MODULE_0__["RotationType"].ShortestPath;
}
RotateTo.prototype.update = function (_delta) {
if (!this._started) {
this._started = true;
this._start = this._actor.rotation;
var distance1 = Math.abs(this._end - this._start);
var distance2 = _Util_Util__WEBPACK_IMPORTED_MODULE_3__["TwoPI"] - distance1;
if (distance1 > distance2) {
this._shortDistance = distance2;
this._longDistance = distance1;
}
else {
this._shortDistance = distance1;
this._longDistance = distance2;
}
this._shortestPathIsPositive = (this._start - this._end + _Util_Util__WEBPACK_IMPORTED_MODULE_3__["TwoPI"]) % _Util_Util__WEBPACK_IMPORTED_MODULE_3__["TwoPI"] >= Math.PI;
switch (this._rotationType) {
case _RotationType__WEBPACK_IMPORTED_MODULE_0__["RotationType"].ShortestPath:
this._distance = this._shortDistance;
if (this._shortestPathIsPositive) {
this._direction = 1;
}
else {
this._direction = -1;
}
break;
case _RotationType__WEBPACK_IMPORTED_MODULE_0__["RotationType"].LongestPath:
this._distance = this._longDistance;
if (this._shortestPathIsPositive) {
this._direction = -1;
}
else {
this._direction = 1;
}
break;
case _RotationType__WEBPACK_IMPORTED_MODULE_0__["RotationType"].Clockwise:
this._direction = 1;
if (this._shortestPathIsPositive) {
this._distance = this._shortDistance;
}
else {
this._distance = this._longDistance;
}
break;
case _RotationType__WEBPACK_IMPORTED_MODULE_0__["RotationType"].CounterClockwise:
this._direction = -1;
if (!this._shortestPathIsPositive) {
this._distance = this._shortDistance;
}
else {
this._distance = this._longDistance;
}
break;
}
}
this._actor.rx = this._direction * this._speed;
if (this.isComplete()) {
this._actor.rotation = this._end;
this._actor.rx = 0;
this._stopped = true;
}
};
RotateTo.prototype.isComplete = function () {
var distanceTravelled = Math.abs(this._actor.rotation - this._start);
return this._stopped || distanceTravelled >= Math.abs(this._distance);
};
RotateTo.prototype.stop = function () {
this._actor.rx = 0;
this._stopped = true;
};
RotateTo.prototype.reset = function () {
this._started = false;
};
return RotateTo;
}());
var RotateBy = /** @class */ (function () {
function RotateBy(actor, angleRadiansOffset, speed, rotationType) {
this._started = false;
this._stopped = false;
this._actor = actor;
this._speed = speed;
this._offset = angleRadiansOffset;
this._rotationType = rotationType || _RotationType__WEBPACK_IMPORTED_MODULE_0__["RotationType"].ShortestPath;
}
RotateBy.prototype.update = function (_delta) {
if (!this._started) {
this._started = true;
this._start = this._actor.rotation;
this._end = this._start + this._offset;
var distance1 = Math.abs(this._end - this._start);
var distance2 = _Util_Util__WEBPACK_IMPORTED_MODULE_3__["TwoPI"] - distance1;
if (distance1 > distance2) {
this._shortDistance = distance2;
this._longDistance = distance1;
}
else {
this._shortDistance = distance1;
this._longDistance = distance2;
}
this._shortestPathIsPositive = (this._start - this._end + _Util_Util__WEBPACK_IMPORTED_MODULE_3__["TwoPI"]) % _Util_Util__WEBPACK_IMPORTED_MODULE_3__["TwoPI"] >= Math.PI;
switch (this._rotationType) {
case _RotationType__WEBPACK_IMPORTED_MODULE_0__["RotationType"].ShortestPath:
this._distance = this._shortDistance;
if (this._shortestPathIsPositive) {
this._direction = 1;
}
else {
this._direction = -1;
}
break;
case _RotationType__WEBPACK_IMPORTED_MODULE_0__["RotationType"].LongestPath:
this._distance = this._longDistance;
if (this._shortestPathIsPositive) {
this._direction = -1;
}
else {
this._direction = 1;
}
break;
case _RotationType__WEBPACK_IMPORTED_MODULE_0__["RotationType"].Clockwise:
this._direction = 1;
if (this._shortDistance >= 0) {
this._distance = this._shortDistance;
}
else {
this._distance = this._longDistance;
}
break;
case _RotationType__WEBPACK_IMPORTED_MODULE_0__["RotationType"].CounterClockwise:
this._direction = -1;
if (this._shortDistance <= 0) {
this._distance = this._shortDistance;
}
else {
this._distance = this._longDistance;
}
break;
}
}
this._actor.rx = this._direction * this._speed;
if (this.isComplete()) {
this._actor.rotation = this._end;
this._actor.rx = 0;
this._stopped = true;
}
};
RotateBy.prototype.isComplete = function () {
var distanceTravelled = Math.abs(this._actor.rotation - this._start);
return this._stopped || distanceTravelled >= Math.abs(this._distance);
};
RotateBy.prototype.stop = function () {
this._actor.rx = 0;
this._stopped = true;
};
RotateBy.prototype.reset = function () {
this._started = false;
};
return RotateBy;
}());
var ScaleTo = /** @class */ (function () {
function ScaleTo(actor, scaleX, scaleY, speedX, speedY) {
this._started = false;
this._stopped = false;
this._actor = actor;
this._endX = scaleX;
this._endY = scaleY;
this._speedX = speedX;
this._speedY = speedY;
}
ScaleTo.prototype.update = function (_delta) {
if (!this._started) {
this._started = true;
this._startX = this._actor.scale.x;
this._startY = this._actor.scale.y;
this._distanceX = Math.abs(this._endX - this._startX);
this._distanceY = Math.abs(this._endY - this._startY);
}
if (!(Math.abs(this._actor.scale.x - this._startX) >= this._distanceX)) {
var directionX = this._endY < this._startY ? -1 : 1;
this._actor.sx = this._speedX * directionX;
}
else {
this._actor.sx = 0;
}
if (!(Math.abs(this._actor.scale.y - this._startY) >= this._distanceY)) {
var directionY = this._endY < this._startY ? -1 : 1;
this._actor.sy = this._speedY * directionY;
}
else {
this._actor.sy = 0;
}
if (this.isComplete()) {
this._actor.scale.x = this._endX;
this._actor.scale.y = this._endY;
this._actor.sx = 0;
this._actor.sy = 0;
}
};
ScaleTo.prototype.isComplete = function () {
return (this._stopped ||
(Math.abs(this._actor.scale.y - this._startX) >= this._distanceX && Math.abs(this._actor.scale.y - this._startY) >= this._distanceY));
};
ScaleTo.prototype.stop = function () {
this._actor.sx = 0;
this._actor.sy = 0;
this._stopped = true;
};
ScaleTo.prototype.reset = function () {
this._started = false;
};
ScaleTo = __decorate([
Object(_Util_Decorators__WEBPACK_IMPORTED_MODULE_4__["obsolete"])({ message: 'ex.Action.ScaleTo will be removed in v0.25.0', alternateMethod: 'Set width and hight directly' })
], ScaleTo);
return ScaleTo;
}());
var ScaleBy = /** @class */ (function () {
function ScaleBy(actor, scaleOffsetX, scaleOffsetY, speed) {
this._started = false;
this._stopped = false;
this._actor = actor;
this._offset = new _Algebra__WEBPACK_IMPORTED_MODULE_1__["Vector"](scaleOffsetX, scaleOffsetY);
this._speedX = this._speedY = speed;
}
ScaleBy.prototype.update = function (_delta) {
if (!this._started) {
this._started = true;
this._startScale = this._actor.scale.clone();
this._endScale = this._startScale.add(this._offset);
this._distanceX = Math.abs(this._endScale.x - this._startScale.x);
this._distanceY = Math.abs(this._endScale.y - this._startScale.y);
this._directionX = this._endScale.x < this._startScale.x ? -1 : 1;
this._directionY = this._endScale.y < this._startScale.y ? -1 : 1;
}
this._actor.sx = this._speedX * this._directionX;
this._actor.sy = this._speedY * this._directionY;
if (this.isComplete()) {
this._actor.scale = this._endScale;
this._actor.sx = 0;
this._actor.sy = 0;
}
};
ScaleBy.prototype.isComplete = function () {
return (this._stopped ||
(Math.abs(this._actor.scale.x - this._startScale.x) >= this._distanceX &&
Math.abs(this._actor.scale.y - this._startScale.y) >= this._distanceY));
};
ScaleBy.prototype.stop = function () {
this._actor.sx = 0;
this._actor.sy = 0;
this._stopped = true;
};
ScaleBy.prototype.reset = function () {
this._started = false;
};
ScaleBy = __decorate([
Object(_Util_Decorators__WEBPACK_IMPORTED_MODULE_4__["obsolete"])({ message: 'ex.Action.ScaleBy will be removed in v0.25.0', alternateMethod: 'Set width and hight directly' })
], ScaleBy);
return ScaleBy;
}());
var Delay = /** @class */ (function () {
function Delay(actor, delay) {
this._elapsedTime = 0;
this._started = false;
this._stopped = false;
this._actor = actor;
this._delay = delay;
}
Delay.prototype.update = function (delta) {
if (!this._started) {
this._started = true;
}
this.x = this._actor.pos.x;
this.y = this._actor.pos.y;
this._elapsedTime += delta;
};
Delay.prototype.isComplete = function () {
return this._stopped || this._elapsedTime >= this._delay;
};
Delay.prototype.stop = function () {
this._stopped = true;
};
Delay.prototype.reset = function () {
this._elapsedTime = 0;
this._started = false;
};
return Delay;
}());
var Blink = /** @class */ (function () {
function Blink(actor, timeVisible, timeNotVisible, numBlinks) {
if (numBlinks === void 0) { numBlinks = 1; }
this._timeVisible = 0;
this._timeNotVisible = 0;
this._elapsedTime = 0;
this._totalTime = 0;
this._stopped = false;
this._started = false;
this._actor = actor;
this._timeVisible = timeVisible;
this._timeNotVisible = timeNotVisible;
this._duration = (timeVisible + timeNotVisible) * numBlinks;
}
Blink.prototype.update = function (delta) {
if (!this._started) {
this._started = true;
}
this._elapsedTime += delta;
this._totalTime += delta;
if (this._actor.visible && this._elapsedTime >= this._timeVisible) {
this._actor.visible = false;
this._elapsedTime = 0;
}
if (!this._actor.visible && this._elapsedTime >= this._timeNotVisible) {
this._actor.visible = true;
this._elapsedTime = 0;
}
if (this.isComplete()) {
this._actor.visible = true;
}
};
Blink.prototype.isComplete = function () {
return this._stopped || this._totalTime >= this._duration;
};
Blink.prototype.stop = function () {
this._actor.visible = true;
this._stopped = true;
};
Blink.prototype.reset = function () {
this._started = false;
this._elapsedTime = 0;
this._totalTime = 0;
};
return Blink;
}());
var Fade = /** @class */ (function () {
function Fade(actor, endOpacity, speed) {
this._multiplier = 1;
this._started = false;
this._stopped = false;
this._actor = actor;
this._endOpacity = endOpacity;
this._speed = speed;
}
Fade.prototype.update = function (delta) {
if (!this._started) {
this._started = true;
// determine direction when we start
if (this._endOpacity < this._actor.opacity) {
this._multiplier = -1;
}
else {
this._multiplier = 1;
}
}
if (this._speed > 0) {
this._actor.opacity += (this._multiplier * (Math.abs(this._actor.opacity - this._endOpacity) * delta)) / this._speed;
}
this._speed -= delta;
if (this.isComplete()) {
this._actor.opacity = this._endOpacity;
}
_Util_Log__WEBPACK_IMPORTED_MODULE_2__["Logger"].getInstance().debug('[Action fade] Actor opacity:', this._actor.opacity);
};
Fade.prototype.isComplete = function () {
return this._stopped || Math.abs(this._actor.opacity - this._endOpacity) < 0.05;
};
Fade.prototype.stop = function () {
this._stopped = true;
};
Fade.prototype.reset = function () {
this._started = false;
};
return Fade;
}());
var Die = /** @class */ (function () {
function Die(actor) {
this._stopped = false;
this._actor = actor;
}
Die.prototype.update = function (_delta) {
this._actor.actionQueue.clearActions();
this._actor.kill();
this._stopped = true;
};
Die.prototype.isComplete = function () {
return this._stopped;
};
Die.prototype.stop = function () {
return;
};
Die.prototype.reset = function () {
return;
};
return Die;
}());
var CallMethod = /** @class */ (function () {
function CallMethod(actor, method) {
this._method = null;
this._actor = null;
this._hasBeenCalled = false;
this._actor = actor;
this._method = method;
}
CallMethod.prototype.update = function (_delta) {
this._method.call(this._actor);
this._hasBeenCalled = true;
};
CallMethod.prototype.isComplete = function () {
return this._hasBeenCalled;
};
CallMethod.prototype.reset = function () {
this._hasBeenCalled = false;
};
CallMethod.prototype.stop = function () {
this._hasBeenCalled = true;
};
return CallMethod;
}());
var Repeat = /** @class */ (function () {
function Repeat(actor, repeat, actions) {
this._stopped = false;
this._actor = actor;
this._actionQueue = new ActionQueue(actor);
this._repeat = repeat;
this._originalRepeat = repeat;
var len = actions.length;
for (var i = 0; i < len; i++) {
actions[i].reset();
this._actionQueue.add(actions[i]);
}
}
Repeat.prototype.update = function (delta) {
this.x = this._actor.pos.x;
this.y = this._actor.pos.y;
if (!this._actionQueue.hasNext()) {
this._actionQueue.reset();
this._repeat--;
}
this._actionQueue.update(delta);
};
Repeat.prototype.isComplete = function () {
return this._stopped || this._repeat <= 0;
};
Repeat.prototype.stop = function () {
this._stopped = true;
};
Repeat.prototype.reset = function () {
this._repeat = this._originalRepeat;
};
return Repeat;
}());
var RepeatForever = /** @class */ (function () {
function RepeatForever(actor, actions) {
this._stopped = false;
this._actor = actor;
this._actionQueue = new ActionQueue(actor);
var len = actions.length;
for (var i = 0; i < len; i++) {
actions[i].reset();
this._actionQueue.add(actions[i]);
}
}
RepeatForever.prototype.update = function (delta) {
this.x = this._actor.pos.x;
this.y = this._actor.pos.y;
if (this._stopped) {
return;
}
if (!this._actionQueue.hasNext()) {
this._actionQueue.reset();
}
this._actionQueue.update(delta);
};
RepeatForever.prototype.isComplete = function () {
return this._stopped;
};
RepeatForever.prototype.stop = function () {
this._stopped = true;
this._actionQueue.clearActions();
};
RepeatForever.prototype.reset = function () {
return;
};
return RepeatForever;
}());
/**
* Action Queues
*
* Action queues are part of the [[ActionContext|Action API]] and
* store the list of actions to be executed for an [[Actor]].
*
* Actors implement [[Actor.actions]] which can be manipulated by
* advanced users to adjust the actions currently being executed in the
* queue.
*/
var ActionQueue = /** @class */ (function () {
function ActionQueue(actor) {
this._actions = [];
this._completedActions = [];
this._actor = actor;
}
ActionQueue.prototype.add = function (action) {
this._actions.push(action);
};
ActionQueue.prototype.remove = function (action) {
var index = this._actions.indexOf(action);
this._actions.splice(index, 1);
};
ActionQueue.prototype.clearActions = function () {
this._actions.length = 0;
this._completedActions.length = 0;
if (this._currentAction) {
this._currentAction.stop();
}
};
ActionQueue.prototype.getActions = function () {
return this._actions.concat(this._completedActions);
};
ActionQueue.prototype.hasNext = function () {
return this._actions.length > 0;
};
ActionQueue.prototype.reset = function () {
this._actions = this.getActions();
var len = this._actions.length;
for (var i = 0; i < len; i++) {
this._actions[i].reset();
}
this._completedActions = [];
};
ActionQueue.prototype.update = function (delta) {
if (this._actions.length > 0) {
this._currentAction = this._actions[0];
this._currentAction.update(delta);
if (this._currentAction.isComplete(this._actor)) {
this._completedActions.push(this._actions.shift());
}
}
};
return ActionQueue;
}());
/***/ }),
/***/ "./Actions/ActionContext.ts":
/*!**********************************!*\
!*** ./Actions/ActionContext.ts ***!
\**********************************/
/*! exports provided: ActionContext */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ActionContext", function() { return ActionContext; });
/* harmony import */ var _Action__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Action */ "./Actions/Action.ts");
/* harmony import */ var _Promises__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Promises */ "./Promises.ts");
/* harmony import */ var _Util_EasingFunctions__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Util/EasingFunctions */ "./Util/EasingFunctions.ts");
/**
* The fluent Action API allows you to perform "actions" on
* [[Actor|Actors]] such as following, moving, rotating, and
* more. You can implement your own actions by implementing
* the [[Action]] interface.
*
* [[include:Actions.md]]
*/
var ActionContext = /** @class */ (function () {
function ActionContext() {
this._actors = [];
this._queues = [];
if (arguments !== null) {
this._actors = Array.prototype.slice.call(arguments, 0);
this._queues = this._actors.map(function (a) {
return a.actionQueue;
});
}
}
/**
* Clears all queued actions from the Actor
*/
ActionContext.prototype.clearActions = function () {
var len = this._queues.length;
for (var i = 0; i < len; i++) {
this._queues[i].clearActions();
}
};
ActionContext.prototype.addActorToContext = function (actor) {
this._actors.push(actor);
// if we run into problems replace the line below with:
this._queues.push(actor.actionQueue);
};
ActionContext.prototype.removeActorFromContext = function (actor) {
var index = this._actors.indexOf(actor);
if (index > -1) {
this._actors.splice(index, 1);
this._queues.splice(index, 1);
}
};
/**
* This method will move an actor to the specified `x` and `y` position over the
* specified duration using a given [[EasingFunctions]] and return back the actor. This
* method is part of the actor 'Action' fluent API allowing action chaining.
* @param x The x location to move the actor to
* @param y The y location to move the actor to
* @param duration The time it should take the actor to move to the new location in milliseconds
* @param easingFcn Use [[EasingFunctions]] or a custom function to use to calculate position
*/
ActionContext.prototype.easeTo = function (x, y, duration, easingFcn) {
if (easingFcn === void 0) { easingFcn = _Util_EasingFunctions__WEBPACK_IMPORTED_MODULE_2__["EasingFunctions"].Linear; }
var len = this._queues.length;
for (var i = 0; i < len; i++) {
this._queues[i].add(new _Action__WEBPACK_IMPORTED_MODULE_0__["EaseTo"](this._actors[i], x, y, duration, easingFcn));
}
return this;
};
/**
* This method will move an actor to the specified x and y position at the
* speed specified (in pixels per second) and return back the actor. This
* method is part of the actor 'Action' fluent API allowing action chaining.
* @param x The x location to move the actor to
* @param y The y location to move the actor to
* @param speed The speed in pixels per second to move
*/
ActionContext.prototype.moveTo = function (x, y, speed) {
var len = this._queues.length;
for (var i = 0; i < len; i++) {
this._queues[i].add(new _Action__WEBPACK_IMPORTED_MODULE_0__["MoveTo"](this._actors[i], x, y, speed));
}
return this;
};
/**
* This method will move an actor by the specified x offset and y offset from its current position, at a certain speed.
* This method is part of the actor 'Action' fluent API allowing action chaining.
* @param xOffset The x offset to apply to this actor
* @param yOffset The y location to move the actor to
* @param speed The speed in pixels per second the actor should move
*/
ActionContext.prototype.moveBy = function (xOffset, yOffset, speed) {
var len = this._queues.length;
for (var i = 0; i < len; i++) {
this._queues[i].add(new _Action__WEBPACK_IMPORTED_MODULE_0__["MoveBy"](this._actors[i], xOffset, yOffset, speed));
}
return this;
};
/**
* This method will rotate an actor to the specified angle at the speed
* specified (in radians per second) and return back the actor. This
* method is part of the actor 'Action' fluent API allowing action chaining.
* @param angleRadians The angle to rotate to in radians
* @param speed The angular velocity of the rotation specified in radians per second
* @param rotationType The [[RotationType]] to use for this rotation
*/
ActionContext.prototype.rotateTo = function (angleRadians, speed, rotationType) {
var len = this._queues.length;
for (var i = 0; i < len; i++) {
this._queues[i].add(new _Action__WEBPACK_IMPORTED_MODULE_0__["RotateTo"](this._actors[i], angleRadians, speed, rotationType));
}
return this;
};
/**
* This method will rotate an actor by the specified angle offset, from it's current rotation given a certain speed
* in radians/sec and return back the actor. This method is part
* of the actor 'Action' fluent API allowing action chaining.
* @param angleRadiansOffset The angle to rotate to in radians relative to the current rotation
* @param speed The speed in radians/sec the actor should rotate at
* @param rotationType The [[RotationType]] to use for this rotation, default is shortest path
*/
ActionContext.prototype.rotateBy = function (angleRadiansOffset, speed, rotationType) {
var len = this._queues.length;
for (var i = 0; i < len; i++) {
this._queues[i].add(new _Action__WEBPACK_IMPORTED_MODULE_0__["RotateBy"](this._actors[i], angleRadiansOffset, speed, rotationType));
}
return this;
};
/**
* This method will scale an actor to the specified size at the speed
* specified (in magnitude increase per second) and return back the
* actor. This method is part of the actor 'Action' fluent API allowing
* action chaining.
* @param sizeX The scaling factor to apply on X axis
* @param sizeY The scaling factor to apply on Y axis
* @param speedX The speed of scaling specified in magnitude increase per second on X axis
* @param speedY The speed of scaling specified in magnitude increase per second on Y axis
*/
ActionContext.prototype.scaleTo = function (sizeX, sizeY, speedX, speedY) {
var len = this._queues.length;
for (var i = 0; i < len; i++) {
this._queues[i].add(new _Action__WEBPACK_IMPORTED_MODULE_0__["ScaleTo"](this._actors[i], sizeX, sizeY, speedX, speedY));
}
return this;
};
/**
* This method will scale an actor by an amount relative to the current scale at a certain speed in scale units/sec
* and return back the actor. This method is part of the
* actor 'Action' fluent API allowing action chaining.
* @param sizeOffsetX The scaling factor to apply on X axis
* @param sizeOffsetY The scaling factor to apply on Y axis
* @param speed The speed to scale at in scale units/sec
*/
ActionContext.prototype.scaleBy = function (sizeOffsetX, sizeOffsetY, speed) {
var len = this._queues.length;
for (var i = 0; i < len; i++) {
this._queues[i].add(new _Action__WEBPACK_IMPORTED_MODULE_0__["ScaleBy"](this._actors[i], sizeOffsetX, sizeOffsetY, speed));
}
return this;
};
/**
* This method will cause an actor to blink (become visible and not
* visible). Optionally, you may specify the number of blinks. Specify the amount of time
* the actor should be visible per blink, and the amount of time not visible.
* This method is part of the actor 'Action' fluent API allowing action chaining.
* @param timeVisible The amount of time to stay visible per blink in milliseconds
* @param timeNotVisible The amount of time to stay not visible per blink in milliseconds
* @param numBlinks The number of times to blink
*/
ActionContext.prototype.blink = function (timeVisible, timeNotVisible, numBlinks) {
if (numBlinks === void 0) { numBlinks = 1; }
var len = this._queues.length;
for (var i = 0; i < len; i++) {
this._queues[i].add(new _Action__WEBPACK_IMPORTED_MODULE_0__["Blink"](this._actors[i], timeVisible, timeNotVisible, numBlinks));
}
return this;
};
/**
* This method will cause an actor's opacity to change from its current value
* to the provided value by a specified time (in milliseconds). This method is
* part of the actor 'Action' fluent API allowing action chaining.
* @param opacity The ending opacity
* @param time The time it should take to fade the actor (in milliseconds)
*/
ActionContext.prototype.fade = function (opacity, time) {
var len = this._queues.length;
for (var i = 0; i < len; i++) {
this._queues[i].add(new _Action__WEBPACK_IMPORTED_MODULE_0__["Fade"](this._actors[i], opacity, time));
}
return this;
};
/**
* This method will delay the next action from executing for a certain
* amount of time (in milliseconds). This method is part of the actor
* 'Action' fluent API allowing action chaining.
* @param time The amount of time to delay the next action in the queue from executing in milliseconds
*/
ActionContext.prototype.delay = function (time) {
var len = this._queues.length;
for (var i = 0; i < len; i++) {
this._queues[i].add(new _Action__WEBPACK_IMPORTED_MODULE_0__["Delay"](this._actors[i], time));
}
return this;
};
/**
* This method will add an action to the queue that will remove the actor from the
* scene once it has completed its previous actions. Any actions on the
* action queue after this action will not be executed.
*/
ActionContext.prototype.die = function () {
var len = this._queues.length;
for (var i = 0; i < len; i++) {
this._queues[i].add(new _Action__WEBPACK_IMPORTED_MODULE_0__["Die"](this._actors[i]));
}
return this;
};
/**
* This method allows you to call an arbitrary method as the next action in the
* action queue. This is useful if you want to execute code in after a specific
* action, i.e An actor arrives at a destination after traversing a path
*/
ActionContext.prototype.callMethod = function (method) {
var len = this._queues.length;
for (var i = 0; i < len; i++) {
this._queues[i].add(new _Action__WEBPACK_IMPORTED_MODULE_0__["CallMethod"](this._actors[i], method));
}
return this;
};
/**
* This method will cause the actor to repeat all of the previously
* called actions a certain number of times. If the number of repeats
* is not specified it will repeat forever. This method is part of
* the actor 'Action' fluent API allowing action chaining
* @param times The number of times to repeat all the previous actions in the action queue. If nothing is specified the actions
* will repeat forever
*/
ActionContext.prototype.repeat = function (times) {
if (!times) {
this.repeatForever();
return this;
}
var len = this._queues.length;
for (var i = 0; i < len; i++) {
this._queues[i].add(new _Action__WEBPACK_IMPORTED_MODULE_0__["Repeat"](this._actors[i], times, this._actors[i].actionQueue.getActions()));
}
return this;
};
/**
* This method will cause the actor to repeat all of the previously
* called actions forever. This method is part of the actor 'Action'
* fluent API allowing action chaining.
*/
ActionContext.prototype.repeatForever = function () {
var len = this._queues.length;
for (var i = 0; i < len; i++) {
this._queues[i].add(new _Action__WEBPACK_IMPORTED_MODULE_0__["RepeatForever"](this._actors[i], this._actors[i].actionQueue.getActions()));
}
return this;
};
/**
* This method will cause the actor to follow another at a specified distance
* @param actor The actor to follow
* @param followDistance The distance to maintain when following, if not specified the actor will follow at the current distance.
*/
ActionContext.prototype.follow = function (actor, followDistance) {
var len = this._queues.length;
for (var i = 0; i < len; i++) {
if (followDistance === undefined) {
this._queues[i].add(new _Action__WEBPACK_IMPORTED_MODULE_0__["Follow"](this._actors[i], actor));
}
else {
this._queues[i].add(new _Action__WEBPACK_IMPORTED_MODULE_0__["Follow"](this._actors[i], actor, followDistance));
}
}
return this;
};
/**
* This method will cause the actor to move towards another until they
* collide "meet" at a specified speed.
* @param actor The actor to meet
* @param speed The speed in pixels per second to move, if not specified it will match the speed of the other actor
*/
ActionContext.prototype.meet = function (actor, speed) {
var len = this._queues.length;
for (var i = 0; i < len; i++) {
if (speed === undefined) {
this._queues[i].add(new _Action__WEBPACK_IMPORTED_MODULE_0__["Meet"](this._actors[i], actor));
}
else {
this._queues[i].add(new _Action__WEBPACK_IMPORTED_MODULE_0__["Meet"](this._actors[i], actor, speed));
}
}
return this;
};
/**
* Returns a promise that resolves when the current action queue up to now
* is finished.
*/
ActionContext.prototype.asPromise = function () {
var _this = this;
var promises = this._queues.map(function (q, i) {
var temp = new _Promises__WEBPACK_IMPORTED_MODULE_1__["Promise"]();
q.add(new _Action__WEBPACK_IMPORTED_MODULE_0__["CallMethod"](_this._actors[i], function () {
temp.resolve();
}));
return temp;
});
return _Promises__WEBPACK_IMPORTED_MODULE_1__["Promise"].join.apply(this, promises);
};
return ActionContext;
}());
/***/ }),
/***/ "./Actions/Actionable.ts":
/*!*******************************!*\
!*** ./Actions/Actionable.ts ***!
\*******************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/***/ }),
/***/ "./Actions/Index.ts":
/*!**************************!*\
!*** ./Actions/Index.ts ***!
\**************************/
/*! exports provided: ActionContext, RotationType, Actions, Internal */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Internal", function() { return Internal; });
/* harmony import */ var _ActionContext__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ActionContext */ "./Actions/ActionContext.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ActionContext", function() { return _ActionContext__WEBPACK_IMPORTED_MODULE_0__["ActionContext"]; });
/* harmony import */ var _Actionable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Actionable */ "./Actions/Actionable.ts");
/* empty/unused harmony star reexport *//* harmony import */ var _RotationType__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./RotationType */ "./Actions/RotationType.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RotationType", function() { return _RotationType__WEBPACK_IMPORTED_MODULE_2__["RotationType"]; });
/* harmony import */ var _Action__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Action */ "./Actions/Action.ts");
/* harmony reexport (module object) */ __webpack_require__.d(__webpack_exports__, "Actions", function() { return _Action__WEBPACK_IMPORTED_MODULE_3__; });
// legacy Internal.Actions namespace support
var Internal = { Actions: _Action__WEBPACK_IMPORTED_MODULE_3__ };
/***/ }),
/***/ "./Actions/RotationType.ts":
/*!*********************************!*\
!*** ./Actions/RotationType.ts ***!
\*********************************/
/*! exports provided: RotationType */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RotationType", function() { return RotationType; });
/**
* An enum that describes the strategies that rotation actions can use
*/
var RotationType;
(function (RotationType) {
/**
* Rotation via `ShortestPath` will use the smallest angle
* between the starting and ending points. This strategy is the default behavior.
*/
RotationType[RotationType["ShortestPath"] = 0] = "ShortestPath";
/**
* Rotation via `LongestPath` will use the largest angle
* between the starting and ending points.
*/
RotationType[RotationType["LongestPath"] = 1] = "LongestPath";
/**
* Rotation via `Clockwise` will travel in a clockwise direction,
* regardless of the starting and ending points.
*/
RotationType[RotationType["Clockwise"] = 2] = "Clockwise";
/**
* Rotation via `CounterClockwise` will travel in a counterclockwise direction,
* regardless of the starting and ending points.
*/
RotationType[RotationType["CounterClockwise"] = 3] = "CounterClockwise";
})(RotationType || (RotationType = {}));
/***/ }),
/***/ "./Actor.ts":
/*!******************!*\
!*** ./Actor.ts ***!
\******************/
/*! exports provided: isActor, ActorImpl, Actor */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isActor", function() { return isActor; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ActorImpl", function() { return ActorImpl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Actor", function() { return Actor; });
/* harmony import */ var _Resources_Texture__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Resources/Texture */ "./Resources/Texture.ts");
/* harmony import */ var _Events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Events */ "./Events.ts");
/* harmony import */ var _Drawing_Color__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Drawing/Color */ "./Drawing/Color.ts");
/* harmony import */ var _Drawing_Sprite__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Drawing/Sprite */ "./Drawing/Sprite.ts");
/* harmony import */ var _Drawing_Animation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Drawing/Animation */ "./Drawing/Animation.ts");
/* harmony import */ var _Util_Log__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Util/Log */ "./Util/Log.ts");
/* harmony import */ var _Actions_ActionContext__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Actions/ActionContext */ "./Actions/ActionContext.ts");
/* harmony import */ var _Actions_Action__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Actions/Action */ "./Actions/Action.ts");
/* harmony import */ var _Algebra__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Algebra */ "./Algebra.ts");
/* harmony import */ var _Collision_Body__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Collision/Body */ "./Collision/Body.ts");
/* harmony import */ var _Configurable__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./Configurable */ "./Configurable.ts");
/* harmony import */ var _Traits_Index__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./Traits/Index */ "./Traits/Index.ts");
/* harmony import */ var _Util_Util__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./Util/Util */ "./Util/Util.ts");
/* harmony import */ var _Collision_CollisionType__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./Collision/CollisionType */ "./Collision/CollisionType.ts");
/* harmony import */ var _Util_Decorators__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./Util/Decorators */ "./Util/Decorators.ts");
/* harmony import */ var _Collision_Collider__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./Collision/Collider */ "./Collision/Collider.ts");
/* harmony import */ var _Collision_Shape__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./Collision/Shape */ "./Collision/Shape.ts");
/* harmony import */ var _EntityComponentSystem_Entity__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./EntityComponentSystem/Entity */ "./EntityComponentSystem/Entity.ts");
var __extends = (undefined && undefined.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
function isActor(x) {
return x instanceof Actor;
}
/**
* @hidden
*/
var ActorImpl = /** @class */ (function (_super) {
__extends(ActorImpl, _super);
// #endregion
/**
* @param x The starting x coordinate of the actor
* @param y The starting y coordinate of the actor
* @param width The starting width of the actor
* @param height The starting height of the actor
* @param color The starting color of the actor. Leave null to draw a transparent actor. The opacity of the color will be used as the
* initial [[opacity]].
*/
function ActorImpl(xOrConfig, y, width, height, color) {
var _this = _super.call(this) || this;
/**
* The unique identifier for the actor
*/
_this.id = ActorImpl.maxId++;
_this._height = 0;
_this._width = 0;
/**
* Indicates whether the actor is physically in the viewport
*/
_this.isOffScreen = false;
/**
* The visibility of an actor
*/
_this.visible = true;
/**
* The opacity of an actor. Passing in a color in the [[constructor]] will use the
* color's opacity.
*/
_this.opacity = 1;
_this.previousOpacity = 1;
/**
* Convenience reference to the global logger
*/
_this.logger = _Util_Log__WEBPACK_IMPORTED_MODULE_5__["Logger"].getInstance();
/**
* The scene that the actor is in
*/
_this.scene = null;
/**
* The parent of this actor
*/
_this.parent = null;
/**
* The children of this actor
*/
_this.children = [];
_this.frames = {};
/**
* Access to the current drawing for the actor, this can be
* an [[Animation]], [[Sprite]], or [[Polygon]].
* Set drawings with [[setDrawing]].
*/
_this.currentDrawing = null;
/**
* Draggable helper
*/
_this._draggable = false;
_this._dragging = false;
_this._pointerDragStartHandler = function () {
_this._dragging = true;
};
_this._pointerDragEndHandler = function () {
_this._dragging = false;
};
_this._pointerDragMoveHandler = function (pe) {
if (_this._dragging) {
_this.pos = pe.pointer.lastWorldPos;
}
};
_this._pointerDragLeaveHandler = function (pe) {
if (_this._dragging) {
_this.pos = pe.pointer.lastWorldPos;
}
};
/**
* Modify the current actor update pipeline.
*/
_this.traits = [];
/**
* Whether or not to enable the [[CapturePointer]] trait that propagates
* pointer events to this actor
*/
_this.enableCapturePointer = false;
/**
* Configuration for [[CapturePointer]] trait
*/
_this.capturePointer = {
captureMoveEvents: false,
captureDragEvents: false
};
_this._zIndex = 0;
_this._isKilled = false;
// #region Events
_this._capturePointerEvents = [
'pointerup',
'pointerdown',
'pointermove',
'pointerenter',
'pointerleave',
'pointerdragstart',
'pointerdragend',
'pointerdragmove',
'pointerdragenter',
'pointerdragleave'
];
_this._captureMoveEvents = [
'pointermove',
'pointerenter',
'pointerleave',
'pointerdragmove',
'pointerdragenter',
'pointerdragleave'
];
_this._captureDragEvents = [
'pointerdragstart',
'pointerdragend',
'pointerdragmove',
'pointerdragenter',
'pointerdragleave'
];
// initialize default options
_this._initDefaults();
var shouldInitializeBody = true;
var collisionType = _Collision_CollisionType__WEBPACK_IMPORTED_MODULE_13__["CollisionType"].Passive;
if (xOrConfig && typeof xOrConfig === 'object') {
var config = xOrConfig;
if (config.pos) {
xOrConfig = config.pos ? config.pos.x : 0;
y = config.pos ? config.pos.y : 0;
}
else {
xOrConfig = config.x || 0;
y = config.y || 0;
}
width = config.width;
height = config.height;
if (config.body) {
shouldInitializeBody = false;
_this.body = config.body;
}
if (config.anchor) {
_this.anchor = config.anchor;
}
if (config.collisionType) {
collisionType = config.collisionType;
}
}
// Body and collider bounds are still determined by actor width/height
_this._width = width || 0;
_this._height = height || 0;
// Initialize default collider to be a box
if (shouldInitializeBody) {
_this.body = new _Collision_Body__WEBPACK_IMPORTED_MODULE_9__["Body"]({
collider: new _Collision_Collider__WEBPACK_IMPORTED_MODULE_15__["Collider"]({
type: collisionType,
shape: _Collision_Shape__WEBPACK_IMPORTED_MODULE_16__["Shape"].Box(_this._width, _this._height, _this.anchor)
})
});
}
// Position uses body to store values must be initialized after body
_this.pos.x = xOrConfig || 0;
_this.pos.y = y || 0;
if (color) {
_this.color = color;
// set default opacity of an actor to the color
_this.opacity = color.a;
}
// Build default pipeline
_this.traits.push(new _Traits_Index__WEBPACK_IMPORTED_MODULE_11__["TileMapCollisionDetection"]());
_this.traits.push(new _Traits_Index__WEBPACK_IMPORTED_MODULE_11__["OffscreenCulling"]());
_this.traits.push(new _Traits_Index__WEBPACK_IMPORTED_MODULE_11__["CapturePointer"]());
// Build the action queue
_this.actionQueue = new _Actions_Action__WEBPACK_IMPORTED_MODULE_7__["ActionQueue"](_this);
_this.actions = new _Actions_ActionContext__WEBPACK_IMPORTED_MODULE_6__["ActionContext"](_this);
return _this;
}
Object.defineProperty(ActorImpl.prototype, "body", {
/**
* The physics body the is associated with this actor. The body is the container for all physical properties, like position, velocity,
* acceleration, mass, inertia, etc.
*/
get: function () {
return this._body;
},
set: function (body) {
this._body = body;
this._body.actor = this;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ActorImpl.prototype, "pos", {
/**
* Gets the position vector of the actor in pixels
*/
get: function () {
return this.body.pos;
},
/**
* Sets the position vector of the actor in pixels
*/
set: function (thePos) {
this.body.pos.setTo(thePos.x, thePos.y);
},
enumerable: false,
configurable: true
});
Object.defineProperty(ActorImpl.prototype, "oldPos", {
/**
* Gets the position vector of the actor from the last frame
*/
get: function () {
return this.body.oldPos;
},
/**
* Sets the position vector of the actor in the last frame
*/
set: function (thePos) {
this.body.oldPos.setTo(thePos.x, thePos.y);
},
enumerable: false,
configurable: true
});
Object.defineProperty(ActorImpl.prototype, "vel", {
/**
* Gets the velocity vector of the actor in pixels/sec
*/
get: function () {
return this.body.vel;
},
/**
* Sets the velocity vector of the actor in pixels/sec
*/
set: function (theVel) {
this.body.vel.setTo(theVel.x, theVel.y);
},
enumerable: false,
configurable: true
});
Object.defineProperty(ActorImpl.prototype, "oldVel", {
/**
* Gets the velocity vector of the actor from the last frame
*/
get: function () {
return this.body.oldVel;
},
/**
* Sets the velocity vector of the actor from the last frame
*/
set: function (theVel) {
this.body.oldVel.setTo(theVel.x, theVel.y);
},
enumerable: false,
configurable: true
});
Object.defineProperty(ActorImpl.prototype, "acc", {
/**
* Gets the acceleration vector of the actor in pixels/second/second. An acceleration pointing down such as (0, 100) may be
* useful to simulate a gravitational effect.
*/
get: function () {
return this.body.acc;
},
/**
* Sets the acceleration vector of teh actor in pixels/second/second
*/
set: function (theAcc) {
this.body.acc.setTo(theAcc.x, theAcc.y);
},
enumerable: false,
configurable: true
});
Object.defineProperty(ActorImpl.prototype, "oldAcc", {
/**
* Gets the acceleration of the actor from the last frame. This does not include the global acc [[Physics.acc]].
*/
get: function () {
return this.body.oldAcc;
},
/**
* Sets the acceleration of the actor from the last frame. This does not include the global acc [[Physics.acc]].
*/
set: function (theAcc) {
this.body.oldAcc.setTo(theAcc.x, theAcc.y);
},
enumerable: false,
configurable: true
});
Object.defineProperty(ActorImpl.prototype, "rotation", {
/**
* Gets the rotation of the actor in radians. 1 radian = 180/PI Degrees.
*/
get: function () {
return this.body.rotation;
},
/**
* Sets the rotation of the actor in radians. 1 radian = 180/PI Degrees.
*/
set: function (theAngle) {
this.body.rotation = theAngle;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ActorImpl.prototype, "rx", {
/**
* Gets the rotational velocity of the actor in radians/second
*/
get: function () {
return this.body.rx;
},
/**
* Sets the rotational velocity of the actor in radians/sec
*/
set: function (angularVelocity) {
this.body.rx = angularVelocity;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ActorImpl.prototype, "scale", {
/**
* Gets the scale vector of the actor
* @obsolete ex.Actor.scale will be removed in v0.25.0, set width and height directly in constructor
*/
get: function () {
return this.body.scale;
},
/**
* Sets the scale vector of the actor for
* @obsolete ex.Actor.scale will be removed in v0.25.0, set width and height directly in constructor
*/
set: function (scale) {
this.body.scale = scale;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ActorImpl.prototype, "oldScale", {
/**
* Gets the old scale of the actor last frame
* @obsolete ex.Actor.scale will be removed in v0.25.0, set width and height directly in constructor
*/
get: function () {
return this.body.oldScale;
},
/**
* Sets the the old scale of the actor last frame
* @obsolete ex.Actor.scale will be removed in v0.25.0, set width and height directly in constructor
*/
set: function (scale) {
this.body.oldScale = scale;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ActorImpl.prototype, "sx", {
/**
* Gets the x scalar velocity of the actor in scale/second
* @obsolete ex.Actor.sx will be removed in v0.25.0, set width and height directly in constructor
*/
get: function () {
return this.body.sx;
},
/**
* Sets the x scalar velocity of the actor in scale/second
* @obsolete ex.Actor.sx will be removed in v0.25.0, set width and height directly in constructor
*/
set: function (scalePerSecondX) {
this.body.sx = scalePerSecondX;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ActorImpl.prototype, "sy", {
/**
* Gets the y scalar velocity of the actor in scale/second
* @obsolete ex.Actor.sy will be removed in v0.25.0, set width and height directly in constructor
*/
get: function () {
return this.body.sy;
},
/**
* Sets the y scale velocity of the actor in scale/second
* @obsolete ex.Actor.sy will be removed in v0.25.0, set width and height directly in constructor
*/
set: function (scalePerSecondY) {
this.body.sy = scalePerSecondY;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ActorImpl.prototype, "draggable", {
get: function () {
return this._draggable;
},
set: function (isDraggable) {
if (isDraggable) {
if (isDraggable && !this._draggable) {
this.on('pointerdragstart', this._pointerDragStartHandler);
this.on('pointerdragend', this._pointerDragEndHandler);
this.on('pointerdragmove', this._pointerDragMoveHandler);
this.on('pointerdragleave', this._pointerDragLeaveHandler);
}
else if (!isDraggable && this._draggable) {
this.off('pointerdragstart', this._pointerDragStartHandler);
this.off('pointerdragend', this._pointerDragEndHandler);
this.off('pointerdragmove', this._pointerDragMoveHandler);
this.off('pointerdragleave', this._pointerDragLeaveHandler);
}
this._draggable = isDraggable;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(ActorImpl.prototype, "color", {
/**
* Sets the color of the actor. A rectangle of this color will be
* drawn if no [[Drawable]] is specified as the actors drawing.
*
* The default is `null` which prevents a rectangle from being drawn.
*/
get: function () {
return this._color;
},
set: function (v) {
this._color = v.clone();
},
enumerable: false,
configurable: true
});
/**
* `onInitialize` is called before the first update of the actor. This method is meant to be
* overridden. This is where initialization of child actors should take place.
*
* Synonymous with the event handler `.on('initialize', (evt) => {...})`
*/
ActorImpl.prototype.onInitialize = function (_engine) {
// Override me
};
/**
* Initializes this actor and all it's child actors, meant to be called by the Scene before first update not by users of Excalibur.
*
* It is not recommended that internal excalibur methods be overridden, do so at your own risk.
*
* @internal
*/
ActorImpl.prototype._initialize = function (engine) {
_super.prototype._initialize.call(this, engine);
for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
var child = _a[_i];
child._initialize(engine);
}
};
ActorImpl.prototype._initDefaults = function () {
this.anchor = Actor.defaults.anchor.clone();
};
ActorImpl.prototype._checkForPointerOptIn = function (eventName) {
if (eventName) {
var normalized = eventName.toLowerCase();
if (this._capturePointerEvents.indexOf(normalized) !== -1) {
this.enableCapturePointer = true;
if (this._captureMoveEvents.indexOf(normalized) !== -1) {
this.capturePointer.captureMoveEvents = true;
}
if (this._captureDragEvents.indexOf(normalized) !== -1) {
this.capturePointer.captureDragEvents = true;
}
}
}
};
ActorImpl.prototype.on = function (eventName, handler) {
this._checkForPointerOptIn(eventName);
_super.prototype.on.call(this, eventName, handler);
};
ActorImpl.prototype.once = function (eventName, handler) {
this._checkForPointerOptIn(eventName);
_super.prototype.once.call(this, eventName, handler);
};
ActorImpl.prototype.off = function (eventName, handler) {
_super.prototype.off.call(this, eventName, handler);
};
// #endregion
/**
* It is not recommended that internal excalibur methods be overridden, do so at your own risk.
*
* Internal _prekill handler for [[onPreKill]] lifecycle event
* @internal
*/
ActorImpl.prototype._prekill = function (_scene) {
_super.prototype.emit.call(this, 'prekill', new _Events__WEBPACK_IMPORTED_MODULE_1__["PreKillEvent"](this));
this.onPreKill(_scene);
};
/**
* Safe to override onPreKill lifecycle event handler. Synonymous with `.on('prekill', (evt) =>{...})`
*
* `onPreKill` is called directly before an actor is killed and removed from its current [[Scene]].
*/
ActorImpl.prototype.onPreKill = function (_scene) {
// Override me
};
/**
* It is not recommended that internal excalibur methods be overridden, do so at your own risk.
*
* Internal _prekill handler for [[onPostKill]] lifecycle event
* @internal
*/
ActorImpl.prototype._postkill = function (_scene) {
_super.prototype.emit.call(this, 'postkill', new _Events__WEBPACK_IMPORTED_MODULE_1__["PostKillEvent"](this));
this.onPostKill(_scene);
};
/**
* Safe to override onPostKill lifecycle event handler. Synonymous with `.on('postkill', (evt) => {...})`
*
* `onPostKill` is called directly after an actor is killed and remove from its current [[Scene]].
*/
ActorImpl.prototype.onPostKill = function (_scene) {
// Override me
};
/**
* If the current actor is a member of the scene, this will remove
* it from the scene graph. It will no longer be drawn or updated.
*/
ActorImpl.prototype.kill = function () {
if (this.scene) {
this._prekill(this.scene);
this.emit('kill', new _Events__WEBPACK_IMPORTED_MODULE_1__["KillEvent"](this));
this._isKilled = true;
this.scene.remove(this);
this._postkill(this.scene);
}
else {
this.logger.warn('Cannot kill actor, it was never added to the Scene');
}
};
/**
* If the current actor is killed, it will now not be killed.
*/
ActorImpl.prototype.unkill = function () {
this._isKilled = false;
};
/**
* Indicates wether the actor has been killed.
*/
ActorImpl.prototype.isKilled = function () {
return this._isKilled;
};
/**
* Adds a child actor to this actor. All movement of the child actor will be
* relative to the parent actor. Meaning if the parent moves the child will
* move with it.
* @param actor The child actor to add
*/
ActorImpl.prototype.add = function (actor) {
actor.body.collider.type = _Collision_CollisionType__WEBPACK_IMPORTED_MODULE_13__["CollisionType"].PreventCollision;
if (_Util_Util__WEBPACK_IMPORTED_MODULE_12__["addItemToArray"](actor, this.children)) {
actor.parent = this;
}
};
/**
* Removes a child actor from this actor.
* @param actor The child actor to remove
*/
ActorImpl.prototype.remove = function (actor) {
if (_Util_Util__WEBPACK_IMPORTED_MODULE_12__["removeItemFromArray"](actor, this.children)) {
actor.parent = null;
}
};
ActorImpl.prototype.setDrawing = function (key) {
key = key.toString();
if (this.currentDrawing !== this.frames[key]) {
if (this.frames[key] != null) {
this.frames[key].reset();
this.currentDrawing = this.frames[key];
}
else {
_Util_Log__WEBPACK_IMPORTED_MODULE_5__["Logger"].getInstance().error("the specified drawing key " + key + " does not exist");
}
}
};
ActorImpl.prototype.addDrawing = function () {
if (arguments.length === 2) {
this.frames[arguments[0]] = arguments[1];
if (!this.currentDrawing) {
this.currentDrawing = arguments[1];
}
}
else {
if (arguments[0] instanceof _Drawing_Sprite__WEBPACK_IMPORTED_MODULE_3__["Sprite"]) {
this.addDrawing('default', arguments[0]);
}
if (arguments[0] instanceof _Resources_Texture__WEBPACK_IMPORTED_MODULE_0__["Texture"]) {
this.addDrawing('default', arguments[0].asSprite());
}
}
};
Object.defineProperty(ActorImpl.prototype, "z", {
get: function () {
return this.getZIndex();
},
set: function (newZ) {
this.setZIndex(newZ);
},
enumerable: false,
configurable: true
});
/**
* Gets the z-index of an actor. The z-index determines the relative order an actor is drawn in.
* Actors with a higher z-index are drawn on top of actors with a lower z-index
*/
ActorImpl.prototype.getZIndex = function () {
return this._zIndex;
};
/**
* Sets the z-index of an actor and updates it in the drawing list for the scene.
* The z-index determines the relative order an actor is drawn in.
* Actors with a higher z-index are drawn on top of actors with a lower z-index
* @param newIndex new z-index to assign
*/
ActorImpl.prototype.setZIndex = function (newIndex) {
this.scene.cleanupDrawTree(this);
this._zIndex = newIndex;
this.scene.updateDrawTree(this);
};
Object.defineProperty(ActorImpl.prototype, "center", {
/**
* Get the center point of an actor
*/
get: function () {
return new _Algebra__WEBPACK_IMPORTED_MODULE_8__["Vector"](this.pos.x + this.width / 2 - this.anchor.x * this.width, this.pos.y + this.height / 2 - this.anchor.y * this.height);
},
enumerable: false,
configurable: true
});
Object.defineProperty(ActorImpl.prototype, "width", {
get: function () {
return this._width * this.getGlobalScale().x;
},
set: function (width) {
this._width = width / this.scale.x;
this.body.collider.shape = _Collision_Shape__WEBPACK_IMPORTED_MODULE_16__["Shape"].Box(this._width, this._height, this.anchor);
this.body.markCollisionShapeDirty();
},
enumerable: false,
configurable: true
});
Object.defineProperty(ActorImpl.prototype, "height", {
get: function () {
return this._height * this.getGlobalScale().y;
},
set: function (height) {
this._height = height / this.scale.y;
this.body.collider.shape = _Collision_Shape__WEBPACK_IMPORTED_MODULE_16__["Shape"].Box(this._width, this._height, this.anchor);
this.body.markCollisionShapeDirty();
},
enumerable: false,
configurable: true
});
/**
* Gets this actor's rotation taking into account any parent relationships
*
* @returns Rotation angle in radians
*/
ActorImpl.prototype.getWorldRotation = function () {
if (!this.parent) {
return this.rotation;
}
return this.rotation + this.parent.getWorldRotation();
};
/**
* Gets an actor's world position taking into account parent relationships, scaling, rotation, and translation
*
* @returns Position in world coordinates
*/
ActorImpl.prototype.getWorldPos = function () {
if (!this.parent) {
return this.pos.clone();
}
// collect parents
var parents = [];
var root = this;
parents.push(this);
// find parents
while (root.parent) {
root = root.parent;
parents.push(root);
}
// calculate position
var x = parents.reduceRight(function (px, p) {
if (p.parent) {
return px + p.pos.x * p.getGlobalScale().x;
}
return px + p.pos.x;
}, 0);
var y = parents.reduceRight(function (py, p) {
if (p.parent) {
return py + p.pos.y * p.getGlobalScale().y;
}
return py + p.pos.y;
}, 0);
// rotate around root anchor
var ra = root.getWorldPos(); // 10, 10
var r = this.getWorldRotation();
return new _Algebra__WEBPACK_IMPORTED_MODULE_8__["Vector"](x, y).rotate(r, ra);
};
/**
* Gets the global scale of the Actor
*/
ActorImpl.prototype.getGlobalScale = function () {
if (!this.parent) {
return new _Algebra__WEBPACK_IMPORTED_MODULE_8__["Vector"](this.scale.x, this.scale.y);
}
var parentScale = this.parent.getGlobalScale();
return new _Algebra__WEBPACK_IMPORTED_MODULE_8__["Vector"](this.scale.x * parentScale.x, this.scale.y * parentScale.y);
};
// #region Collision
/**
* Tests whether the x/y specified are contained in the actor
* @param x X coordinate to test (in world coordinates)
* @param y Y coordinate to test (in world coordinates)
* @param recurse checks whether the x/y are contained in any child actors (if they exist).
*/
ActorImpl.prototype.contains = function (x, y, recurse) {
if (recurse === void 0) { recurse = false; }
// These shenanigans are to handle child actor containment,
// the only time getWorldPos and pos are different is a child actor
var childShift = this.getWorldPos().sub(this.pos);
var containment = this.body.collider.bounds.translate(childShift).contains(new _Algebra__WEBPACK_IMPORTED_MODULE_8__["Vector"](x, y));
if (recurse) {
return (containment ||
this.children.some(function (child) {
return child.contains(x, y, true);
}));
}
return containment;
};
/**
* Returns true if the two actor.body.collider.shape's surfaces are less than or equal to the distance specified from each other
* @param actor Actor to test
* @param distance Distance in pixels to test
*/
ActorImpl.prototype.within = function (actor, distance) {
return this.body.collider.shape.getClosestLineBetween(actor.body.collider.shape).getLength() <= distance;
};
// #endregion
// #region Update
/**
* Called by the Engine, updates the state of the actor
* @param engine The reference to the current game engine
* @param delta The time elapsed since the last update in milliseconds
*/
ActorImpl.prototype.update = function (engine, delta) {
this._initialize(engine);
this._preupdate(engine, delta);
// Tick animations
var drawing = this.currentDrawing;
if (drawing && drawing instanceof _Drawing_Animation__WEBPACK_IMPORTED_MODULE_4__["Animation"]) {
drawing.tick(delta, engine.stats.currFrame.id);
}
// Update action queue
this.actionQueue.update(delta);
// Update color only opacity
if (this.color) {
this.color.a = this.opacity;
}
if (this.opacity === 0) {
this.visible = false;
}
// capture old transform
this.body.captureOldTransform();
// Run Euler integration
this.body.integrate(delta);
// Update actor pipeline (movement, collision detection, event propagation, offscreen culling)
for (var _i = 0, _a = this.traits; _i < _a.length; _i++) {
var trait = _a[_i];
trait.update(this, engine, delta);
}
// Update child actors
for (var i = 0; i < this.children.length; i++) {
this.children[i].update(engine, delta);
}
this._postupdate(engine, delta);
};
/**
* Safe to override onPreUpdate lifecycle event handler. Synonymous with `.on('preupdate', (evt) =>{...})`
*
* `onPreUpdate` is called directly before an actor is updated.
*/
ActorImpl.prototype.onPreUpdate = function (_engine, _delta) {
// Override me
};
/**
* Safe to override onPostUpdate lifecycle event handler. Synonymous with `.on('postupdate', (evt) =>{...})`
*
* `onPostUpdate` is called directly after an actor is updated.
*/
ActorImpl.prototype.onPostUpdate = function (_engine, _delta) {
// Override me
};
/**
* It is not recommended that internal excalibur methods be overridden, do so at your own risk.
*
* Internal _preupdate handler for [[onPreUpdate]] lifecycle event
* @internal
*/
ActorImpl.prototype._preupdate = function (engine, delta) {
this.emit('preupdate', new _Events__WEBPACK_IMPORTED_MODULE_1__["PreUpdateEvent"](engine, delta, this));
this.onPreUpdate(engine, delta);
};
/**
* It is not recommended that internal excalibur methods be overridden, do so at your own risk.
*
* Internal _preupdate handler for [[onPostUpdate]] lifecycle event
* @internal
*/
ActorImpl.prototype._postupdate = function (engine, delta) {
this.emit('postupdate', new _Events__WEBPACK_IMPORTED_MODULE_1__["PreUpdateEvent"](engine, delta, this));
this.onPostUpdate(engine, delta);
};
// endregion
// #region Drawing
/**
* Called by the Engine, draws the actor to the screen
* @param ctx The rendering context
* @param delta The time since the last draw in milliseconds
*/
ActorImpl.prototype.draw = function (ctx, delta) {
ctx.save();
ctx.translate(this.pos.x, this.pos.y);
ctx.rotate(this.rotation);
ctx.scale(this.scale.x, this.scale.y);
// translate canvas by anchor offset
ctx.save();
ctx.translate(-(this._width * this.anchor.x), -(this._height * this.anchor.y));
this._predraw(ctx, delta);
if (this.currentDrawing) {
var drawing = this.currentDrawing;
// See https://github.com/excaliburjs/Excalibur/pull/619 for discussion on this formula
var offsetX = (this._width - drawing.width * drawing.scale.x) * this.anchor.x;
var offsetY = (this._height - drawing.height * drawing.scale.y) * this.anchor.y;
this.currentDrawing.draw({ ctx: ctx, x: offsetX, y: offsetY, opacity: this.opacity });
}
else {
if (this.color && this.body && this.body.collider && this.body.collider.shape) {
this.body.collider.shape.draw(ctx, this.color, new _Algebra__WEBPACK_IMPORTED_MODULE_8__["Vector"](this.width * this.anchor.x, this.height * this.anchor.y));
}
}
ctx.restore();
// Draw child actors
for (var i = 0; i < this.children.length; i++) {
if (this.children[i].visible) {
this.children[i].draw(ctx, delta);
}
}
this._postdraw(ctx, delta);
ctx.restore();
};
/**
* Safe to override onPreDraw lifecycle event handler. Synonymous with `.on('predraw', (evt) =>{...})`
*
* `onPreDraw` is called directly before an actor is drawn, but after local transforms are made.
*/
ActorImpl.prototype.onPreDraw = function (_ctx, _delta) {
// Override me
};
/**
* Safe to override onPostDraw lifecycle event handler. Synonymous with `.on('postdraw', (evt) =>{...})`
*
* `onPostDraw` is called directly after an actor is drawn, and before local transforms are removed.
*/
ActorImpl.prototype.onPostDraw = function (_ctx, _delta) {
// Override me
};
/**
* It is not recommended that internal excalibur methods be overridden, do so at your own risk.
*
* Internal _predraw handler for [[onPreDraw]] lifecycle event
* @internal
*/
ActorImpl.prototype._predraw = function (ctx, delta) {
this.emit('predraw', new _Events__WEBPACK_IMPORTED_MODULE_1__["PreDrawEvent"](ctx, delta, this));
this.onPreDraw(ctx, delta);
};
/**
* It is not recommended that internal excalibur methods be overridden, do so at your own risk.
*
* Internal _postdraw handler for [[onPostDraw]] lifecycle event
* @internal
*/
ActorImpl.prototype._postdraw = function (ctx, delta) {
this.emit('postdraw', new _Events__WEBPACK_IMPORTED_MODULE_1__["PreDrawEvent"](ctx, delta, this));
this.onPostDraw(ctx, delta);
};
/**
* Called by the Engine, draws the actors debugging to the screen
* @param ctx The rendering context
*/
/* istanbul ignore next */
ActorImpl.prototype.debugDraw = function (ctx) {
this.emit('predebugdraw', new _Events__WEBPACK_IMPORTED_MODULE_1__["PreDebugDrawEvent"](ctx, this));
this.body.collider.debugDraw(ctx);
// Draw actor bounding box
var bb = this.body.collider.localBounds.translate(this.getWorldPos());
bb.debugDraw(ctx);
// Draw actor Id
ctx.fillText('id: ' + this.id, bb.left + 3, bb.top + 10);
// Draw actor anchor Vector
ctx.fillStyle = _Drawing_Color__WEBPACK_IMPORTED_MODULE_2__["Color"].Yellow.toString();
ctx.beginPath();
ctx.arc(this.getWorldPos().x, this.getWorldPos().y, 3, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
// Culling Box debug draw
for (var j = 0; j < this.traits.length; j++) {
if (this.traits[j] instanceof _Traits_Index__WEBPACK_IMPORTED_MODULE_11__["OffscreenCulling"]) {
this.traits[j].cullingBox.debugDraw(ctx); // eslint-disable-line
}
}
// Unit Circle debug draw
ctx.strokeStyle = _Drawing_Color__WEBPACK_IMPORTED_MODULE_2__["Color"].Yellow.toString();
ctx.beginPath();
var radius = Math.min(this.width, this.height);
ctx.arc(this.getWorldPos().x, this.getWorldPos().y, radius, 0, Math.PI * 2);
ctx.closePath();
ctx.stroke();
var ticks = {
'0 Pi': 0,
'Pi/2': Math.PI / 2,
Pi: Math.PI,
'3/2 Pi': (3 * Math.PI) / 2
};
var oldFont = ctx.font;
for (var tick in ticks) {
ctx.fillStyle = _Drawing_Color__WEBPACK_IMPORTED_MODULE_2__["Color"].Yellow.toString();
ctx.font = '14px';
ctx.textAlign = 'center';
ctx.fillText(tick, this.getWorldPos().x + Math.cos(ticks[tick]) * (radius + 10), this.getWorldPos().y + Math.sin(ticks[tick]) * (radius + 10));
}
ctx.font = oldFont;
// Draw child actors
for (var i = 0; i < this.children.length; i++) {
this.children[i].debugDraw(ctx);
}
this.emit('postdebugdraw', new _Events__WEBPACK_IMPORTED_MODULE_1__["PostDebugDrawEvent"](ctx, this));
};
/**
* Returns the full array of ancestors
*/
ActorImpl.prototype.getAncestors = function () {
var path = [this];
var currentActor = this;
var parent;
while ((parent = currentActor.parent)) {
currentActor = parent;
path.push(currentActor);
}
return path.reverse();
};
// #region Properties
/**
* Indicates the next id to be set
*/
ActorImpl.defaults = {
anchor: _Algebra__WEBPACK_IMPORTED_MODULE_8__["Vector"].Half
};
/**
* Indicates the next id to be set
*/
ActorImpl.maxId = 0;
__decorate([
Object(_Util_Decorators__WEBPACK_IMPORTED_MODULE_14__["obsolete"])({ message: 'ex.Actor.sx will be removed in v0.25.0', alternateMethod: 'Set width and height directly in constructor' })
], ActorImpl.prototype, "sx", null);
__decorate([
Object(_Util_Decorators__WEBPACK_IMPORTED_MODULE_14__["obsolete"])({ message: 'ex.Actor.sy will be removed in v0.25.0', alternateMethod: 'Set width and height directly in constructor' })
], ActorImpl.prototype, "sy", null);
return ActorImpl;
}(_EntityComponentSystem_Entity__WEBPACK_IMPORTED_MODULE_17__["Entity"]));
/**
* The most important primitive in Excalibur is an `Actor`. Anything that
* can move on the screen, collide with another `Actor`, respond to events,
* or interact with the current scene, must be an actor. An `Actor` **must**
* be part of a [[Scene]] for it to be drawn to the screen.
*
* [[include:Actors.md]]
*
*
* [[include:Constructors.md]]
*
*/
var Actor = /** @class */ (function (_super) {
__extends(Actor, _super);
function Actor(xOrConfig, y, width, height, color) {
return _super.call(this, xOrConfig, y, width, height, color) || this;
}
return Actor;
}(Object(_Configurable__WEBPACK_IMPORTED_MODULE_10__["Configurable"])(ActorImpl)));
/***/ }),
/***/ "./Algebra.ts":
/*!********************!*\
!*** ./Algebra.ts ***!
\********************/
/*! exports provided: Vector, Ray, Line, Projection, GlobalCoordinates, vec */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Vector", function() { return Vector; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Ray", function() { return Ray; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Line", function() { return Line; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Projection", function() { return Projection; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GlobalCoordinates", function() { return GlobalCoordinates; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "vec", function() { return vec; });
/* harmony import */ var _Util_Util__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Util/Util */ "./Util/Util.ts");
/* harmony import */ var _Util_Decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Util/Decorators */ "./Util/Decorators.ts");
var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
/**
* A 2D vector on a plane.
*/
var Vector = /** @class */ (function () {
/**
* @param x X component of the Vector
* @param y Y component of the Vector
*/
function Vector(x, y) {
this.x = x;
this.y = y;
}
Object.defineProperty(Vector, "Zero", {
/**
* A (0, 0) vector
*/
get: function () {
return new Vector(0, 0);
},
enumerable: false,
configurable: true
});
Object.defineProperty(Vector, "One", {
/**
* A (1, 1) vector
*/
get: function () {
return new Vector(1, 1);
},
enumerable: false,
configurable: true
});
Object.defineProperty(Vector, "Half", {
/**
* A (0.5, 0.5) vector
*/
get: function () {
return new Vector(0.5, 0.5);
},
enumerable: false,
configurable: true
});
Object.defineProperty(Vector, "Up", {
/**
* A unit vector pointing up (0, -1)
*/
get: function () {
return new Vector(0, -1);
},
enumerable: false,
configurable: true
});
Object.defineProperty(Vector, "Down", {
/**
* A unit vector pointing down (0, 1)
*/
get: function () {
return new Vector(0, 1);
},
enumerable: false,
configurable: true
});
Object.defineProperty(Vector, "Left", {
/**
* A unit vector pointing left (-1, 0)
*/
get: function () {
return new Vector(-1, 0);
},
enumerable: false,
configurable: true
});
Object.defineProperty(Vector, "Right", {
/**
* A unit vector pointing right (1, 0)
*/
get: function () {
return new Vector(1, 0);
},
enumerable: false,
configurable: true
});
/**
* Returns a vector of unit length in the direction of the specified angle in Radians.
* @param angle The angle to generate the vector
*/
Vector.fromAngle = function (angle) {
return new Vector(Math.cos(angle), Math.sin(angle));
};
/**
* Checks if vector is not null, undefined, or if any of its components are NaN or Infinity.
*/
Vector.isValid = function (vec) {
if (vec === null || vec === undefined) {
return false;
}
if (isNaN(vec.x) || isNaN(vec.y)) {
return false;
}
if (vec.x === Infinity || vec.y === Infinity || vec.x === -Infinity || vec.y === -Infinity) {
return false;
}
return true;
};
/**
* Calculates distance between two Vectors
* @param vec1
* @param vec2
*/
Vector.distance = function (vec1, vec2) {
return Math.sqrt(Math.pow(vec1.x - vec2.x, 2) + Math.pow(vec1.y - vec2.y, 2));
};
/**
* Sets the x and y components at once
*/
Vector.prototype.setTo = function (x, y) {
this.x = x;
this.y = y;
};
/**
* Compares this point against another and tests for equality
* @param point The other point to compare to
*/
Vector.prototype.equals = function (vector, tolerance) {
if (tolerance === void 0) { tolerance = 0.001; }
return Math.abs(this.x - vector.x) <= tolerance && Math.abs(this.y - vector.y) <= tolerance;
};
/**
* The distance to another vector. If no other Vector is specified, this will return the [[magnitude]].
* @param v The other vector. Leave blank to use origin vector.
*/
Vector.prototype.distance = function (v) {
if (!v) {
v = Vector.Zero;
}
return Math.sqrt(Math.pow(this.x - v.x, 2) + Math.pow(this.y - v.y, 2));
};
/**
* The magnitude (size) of the Vector
* @obsolete magnitude will be removed in favour of '.size' in version 0.25.0
*/
Vector.prototype.magnitude = function () {
return this.distance();
};
Object.defineProperty(Vector.prototype, "size", {
/**
* The size(magnitude) of the Vector
*/
get: function () {
return this.distance();
},
set: function (newLength) {
var v = this.normalize().scale(newLength);
this.x = v.x;
this.y = v.y;
},
enumerable: false,
configurable: true
});
/**
* Normalizes a vector to have a magnitude of 1.
*/
Vector.prototype.normalize = function () {
var d = this.distance();
if (d > 0) {
return new Vector(this.x / d, this.y / d);
}
else {
return new Vector(0, 1);
}
};
/**
* Returns the average (midpoint) between the current point and the specified
*/
Vector.prototype.average = function (vec) {
return this.add(vec).scale(0.5);
};
Vector.prototype.scale = function (sizeOrScale) {
if (sizeOrScale instanceof Vector) {
return new Vector(this.x * sizeOrScale.x, this.y * sizeOrScale.y);
}
else {
return new Vector(this.x * sizeOrScale, this.y * sizeOrScale);
}
};
/**
* Adds one vector to another
* @param v The vector to add
*/
Vector.prototype.add = function (v) {
return new Vector(this.x + v.x, this.y + v.y);
};
/**
* Subtracts a vector from another, if you subtract vector `B.sub(A)` the resulting vector points from A -> B
* @param v The vector to subtract
*/
Vector.prototype.sub = function (v) {
return new Vector(this.x - v.x, this.y - v.y);
};
/**
* Adds one vector to this one modifying the original
* @param v The vector to add
*/
Vector.prototype.addEqual = function (v) {
this.x += v.x;
this.y += v.y;
return this;
};
/**
* Subtracts a vector from this one modifying the original
* @parallel v The vector to subtract
*/
Vector.prototype.subEqual = function (v) {
this.x -= v.x;
this.y -= v.y;
return this;
};
/**
* Scales this vector by a factor of size and modifies the original
*/
Vector.prototype.scaleEqual = function (size) {
this.x *= size;
this.y *= size;
return this;
};
/**
* Performs a dot product with another vector
* @param v The vector to dot
*/
Vector.prototype.dot = function (v) {
return this.x * v.x + this.y * v.y;
};
Vector.prototype.cross = function (v) {
if (v instanceof Vector) {
return this.x * v.y - this.y * v.x;
}
else if (typeof v === 'number') {
return new Vector(v * this.y, -v * this.x);
}
};
/**
* Returns the perpendicular vector to this one
*/
Vector.prototype.perpendicular = function () {
return new Vector(this.y, -this.x);
};
/**
* Returns the normal vector to this one, same as the perpendicular of length 1
*/
Vector.prototype.normal = function () {
return this.perpendicular().normalize();
};
/**
* Negate the current vector
*/
Vector.prototype.negate = function () {
return this.scale(-1);
};
/**
* Returns the angle of this vector.
*/
Vector.prototype.toAngle = function () {
return Math.atan2(this.y, this.x);
};
/**
* Rotates the current vector around a point by a certain number of
* degrees in radians
*/
Vector.prototype.rotate = function (angle, anchor) {
if (!anchor) {
anchor = new Vector(0, 0);
}
var sinAngle = Math.sin(angle);
var cosAngle = Math.cos(angle);
var x = cosAngle * (this.x - anchor.x) - sinAngle * (this.y - anchor.y) + anchor.x;
var y = sinAngle * (this.x - anchor.x) + cosAngle * (this.y - anchor.y) + anchor.y;
return new Vector(x, y);
};
/**
* Creates new vector that has the same values as the previous.
*/
Vector.prototype.clone = function () {
return new Vector(this.x, this.y);
};
/**
* Returns a string representation of the vector.
*/
Vector.prototype.toString = function () {
return "(" + this.x + ", " + this.y + ")";
};
__decorate([
Object(_Util_Decorators__WEBPACK_IMPORTED_MODULE_1__["obsolete"])({ message: 'will be removed in favour of `.size` in version 0.25.0' })
], Vector.prototype, "magnitude", null);
return Vector;
}());
/**
* A 2D ray that can be cast into the scene to do collision detection
*/
var Ray = /** @class */ (function () {
/**
* @param pos The starting position for the ray
* @param dir The vector indicating the direction of the ray
*/
function Ray(pos, dir) {
this.pos = pos;
this.dir = dir.normalize();
}
/**
* Tests a whether this ray intersects with a line segment. Returns a number greater than or equal to 0 on success.
* This number indicates the mathematical intersection time.
* @param line The line to test
*/
Ray.prototype.intersect = function (line) {
var numerator = line.begin.sub(this.pos);
// Test is line and ray are parallel and non intersecting
if (this.dir.cross(line.getSlope()) === 0 && numerator.cross(this.dir) !== 0) {
return -1;
}
// Lines are parallel
var divisor = this.dir.cross(line.getSlope());
if (divisor === 0) {
return -1;
}
var t = numerator.cross(line.getSlope()) / divisor;
if (t >= 0) {
var u = numerator.cross(this.dir) / divisor / line.getLength();
if (u >= 0 && u <= 1) {
return t;
}
}
return -1;
};
/**
* Returns the point of intersection given the intersection time
*/
Ray.prototype.getPoint = function (time) {
return this.pos.add(this.dir.scale(time));
};
return Ray;
}());
/**
* A 2D line segment
*/
var Line = /** @class */ (function () {
/**
* @param begin The starting point of the line segment
* @param end The ending point of the line segment
*/
function Line(begin, end) {
this.begin = begin;
this.end = end;
}
Object.defineProperty(Line.prototype, "slope", {
/**
* Gets the raw slope (m) of the line. Will return (+/-)Infinity for vertical lines.
*/
get: function () {
return (this.end.y - this.begin.y) / (this.end.x - this.begin.x);
},
enumerable: false,
configurable: true
});
Object.defineProperty(Line.prototype, "intercept", {
/**
* Gets the Y-intercept (b) of the line. Will return (+/-)Infinity if there is no intercept.
*/
get: function () {
return this.begin.y - this.slope * this.begin.x;
},
enumerable: false,
configurable: true
});
/**
* Gets the normal of the line
*/
Line.prototype.normal = function () {
return this.end.sub(this.begin).normal();
};
/**
* Returns the slope of the line in the form of a vector of length 1
*/
Line.prototype.getSlope = function () {
var begin = this.begin;
var end = this.end;
var distance = begin.distance(end);
return end.sub(begin).scale(1 / distance);
};
/**
* Returns the edge of the line as vector, the length of the vector is the length of the edge
*/
Line.prototype.getEdge = function () {
var begin = this.begin;
var end = this.end;
return end.sub(begin);
};
/**
* Returns the length of the line segment in pixels
*/
Line.prototype.getLength = function () {
var begin = this.begin;
var end = this.end;
var distance = begin.distance(end);
return distance;
};
Object.defineProperty(Line.prototype, "midpoint", {
/**
* Returns the midpoint of the edge
*/
get: function () {
return this.begin.add(this.end).scale(0.5);
},
enumerable: false,
configurable: true
});
/**
* Flips the direction of the line segment
*/
Line.prototype.flip = function () {
return new Line(this.end, this.begin);
};
/**
* Find the perpendicular distance from the line to a point
* https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line
* @param point
*/
Line.prototype.distanceToPoint = function (point) {
var x0 = point.x;
var y0 = point.y;
var l = this.getLength();
var dy = this.end.y - this.begin.y;
var dx = this.end.x - this.begin.x;
var distance = Math.abs(dy * x0 - dx * y0 + this.end.x * this.begin.y - this.end.y * this.begin.x) / l;
return distance;
};
/**
* Find the perpendicular line from the line to a point
* https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line
* (a - p) - ((a - p) * n)n
* a is a point on the line
* p is the arbitrary point above the line
* n is a unit vector in direction of the line
* @param point
*/
Line.prototype.findVectorToPoint = function (point) {
var aMinusP = this.begin.sub(point);
var n = this.getSlope();
return aMinusP.sub(n.scale(aMinusP.dot(n)));
};
/**
* Finds a point on the line given only an X or a Y value. Given an X value, the function returns
* a new point with the calculated Y value and vice-versa.
*
* @param x The known X value of the target point
* @param y The known Y value of the target point
* @returns A new point with the other calculated axis value
*/
Line.prototype.findPoint = function (x, y) {
if (x === void 0) { x = null; }
if (y === void 0) { y = null; }
var m = this.slope;
var b = this.intercept;
if (x !== null) {
return new Vector(x, m * x + b);
}
else if (y !== null) {
return new Vector((y - b) / m, y);
}
else {
throw new Error('You must provide an X or a Y value');
}
};
/**
* @see http://stackoverflow.com/a/11908158/109458
*/
Line.prototype.hasPoint = function () {
var currPoint;
var threshold = 0;
if (typeof arguments[0] === 'number' && typeof arguments[1] === 'number') {
currPoint = new Vector(arguments[0], arguments[1]);
threshold = arguments[2] || 0;
}
else if (arguments[0] instanceof Vector) {
currPoint = arguments[0];
threshold = arguments[1] || 0;
}
else {
throw 'Could not determine the arguments for Vector.hasPoint';
}
var dxc = currPoint.x - this.begin.x;
var dyc = currPoint.y - this.begin.y;
var dx1 = this.end.x - this.begin.x;
var dy1 = this.end.y - this.begin.y;
var cross = dxc * dy1 - dyc * dx1;
// check whether point lines on the line
if (Math.abs(cross) > threshold) {
return false;
}
// check whether point lies in-between start and end
if (Math.abs(dx1) >= Math.abs(dy1)) {
return dx1 > 0 ? this.begin.x <= currPoint.x && currPoint.x <= this.end.x : this.end.x <= currPoint.x && currPoint.x <= this.begin.x;
}
else {
return dy1 > 0 ? this.begin.y <= currPoint.y && currPoint.y <= this.end.y : this.end.y <= currPoint.y && currPoint.y <= this.begin.y;
}
};
return Line;
}());
/**
* A 1 dimensional projection on an axis, used to test overlaps
*/
var Projection = /** @class */ (function () {
function Projection(min, max) {
this.min = min;
this.max = max;
}
Projection.prototype.overlaps = function (projection) {
return this.max > projection.min && projection.max > this.min;
};
Projection.prototype.getOverlap = function (projection) {
if (this.overlaps(projection)) {
if (this.max > projection.max) {
return projection.max - this.min;
}
else {
return this.max - projection.min;
}
}
return 0;
};
return Projection;
}());
var GlobalCoordinates = /** @class */ (function () {
function GlobalCoordinates(worldPos, pagePos, screenPos) {
this.worldPos = worldPos;
this.pagePos = pagePos;
this.screenPos = screenPos;
}
GlobalCoordinates.fromPagePosition = function (xOrPos, yOrEngine, engineOrUndefined) {
var pageX;
var pageY;
var pagePos;
var engine;
if (arguments.length === 3) {
pageX = xOrPos;
pageY = yOrEngine;
pagePos = new Vector(pageX, pageY);
engine = engineOrUndefined;
}
else {
pagePos = xOrPos;
pageX = pagePos.x;
pageY = pagePos.y;
engine = yOrEngine;
}
var screenX = pageX - _Util_Util__WEBPACK_IMPORTED_MODULE_0__["getPosition"](engine.canvas).x;
var screenY = pageY - _Util_Util__WEBPACK_IMPORTED_MODULE_0__["getPosition"](engine.canvas).y;
var screenPos = new Vector(screenX, screenY);
var worldPos = engine.screenToWorldCoordinates(screenPos);
return new GlobalCoordinates(worldPos, pagePos, screenPos);
};
return GlobalCoordinates;
}());
/**
* Shorthand for creating new Vectors - returns a new Vector instance with the
* provided X and Y components.
*
* @param x X component of the Vector
* @param y Y component of the Vector
*/
function vec(x, y) {
return new Vector(x, y);
}
/***/ }),
/***/ "./Camera.ts":
/*!*******************!*\
!*** ./Camera.ts ***!
\*******************/
/*! exports provided: StrategyContainer, Axis, LockCameraToActorStrategy, LockCameraToActorAxisStrategy, ElasticToActorStrategy, RadiusAroundActorStrategy, LimitCameraBoundsStrategy, Camera */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StrategyContainer", function() { return StrategyContainer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Axis", function() { return Axis; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LockCameraToActorStrategy", function() { return LockCameraToActorStrategy; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LockCameraToActorAxisStrategy", function() { return LockCameraToActorAxisStrategy; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ElasticToActorStrategy", function() { return ElasticToActorStrategy; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RadiusAroundActorStrategy", function() { return RadiusAroundActorStrategy; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LimitCameraBoundsStrategy", function() { return LimitCameraBoundsStrategy; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Camera", function() { return Camera; });
/* harmony import */ var _Util_EasingFunctions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Util/EasingFunctions */ "./Util/EasingFunctions.ts");
/* harmony import */ var _Promises__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Promises */ "./Promises.ts");
/* harmony import */ var _Algebra__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Algebra */ "./Algebra.ts");
/* harmony import */ var _Util_Util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Util/Util */ "./Util/Util.ts");
/* harmony import */ var _Events__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Events */ "./Events.ts");
/* harmony import */ var _Class__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Class */ "./Class.ts");
/* harmony import */ var _Collision_BoundingBox__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Collision/BoundingBox */ "./Collision/BoundingBox.ts");
/* harmony import */ var _Util_Log__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Util/Log */ "./Util/Log.ts");
var __extends = (undefined && undefined.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
/**
* Container to house convenience strategy methods
* @internal
*/
var StrategyContainer = /** @class */ (function () {
function StrategyContainer(camera) {
this.camera = camera;
}
/**
* Creates and adds the [[LockCameraToActorStrategy]] on the current camera.
* @param actor The actor to lock the camera to
*/
StrategyContainer.prototype.lockToActor = function (actor) {
this.camera.addStrategy(new LockCameraToActorStrategy(actor));
};
/**
* Creates and adds the [[LockCameraToActorAxisStrategy]] on the current camera
* @param actor The actor to lock the camera to
* @param axis The axis to follow the actor on
*/
StrategyContainer.prototype.lockToActorAxis = function (actor, axis) {
this.camera.addStrategy(new LockCameraToActorAxisStrategy(actor, axis));
};
/**
* Creates and adds the [[ElasticToActorStrategy]] on the current camera
* If cameraElasticity < cameraFriction < 1.0, the behavior will be a dampened spring that will slowly end at the target without bouncing
* If cameraFriction < cameraElasticity < 1.0, the behavior will be an oscillating spring that will over
* correct and bounce around the target
*
* @param target Target actor to elastically follow
* @param cameraElasticity [0 - 1.0] The higher the elasticity the more force that will drive the camera towards the target
* @param cameraFriction [0 - 1.0] The higher the friction the more that the camera will resist motion towards the target
*/
StrategyContainer.prototype.elasticToActor = function (actor, cameraElasticity, cameraFriction) {
this.camera.addStrategy(new ElasticToActorStrategy(actor, cameraElasticity, cameraFriction));
};
/**
* Creates and adds the [[RadiusAroundActorStrategy]] on the current camera
* @param target Target actor to follow when it is "radius" pixels away
* @param radius Number of pixels away before the camera will follow
*/
StrategyContainer.prototype.radiusAroundActor = function (actor, radius) {
this.camera.addStrategy(new RadiusAroundActorStrategy(actor, radius));
};
/**
* Creates and adds the [[LimitCameraBoundsStrategy]] on the current camera
* @param box The bounding box to limit the camera to.
*/
StrategyContainer.prototype.limitCameraBounds = function (box) {
this.camera.addStrategy(new LimitCameraBoundsStrategy(box));
};
return StrategyContainer;
}());
/**
* Camera axis enum
*/
var Axis;
(function (Axis) {
Axis[Axis["X"] = 0] = "X";
Axis[Axis["Y"] = 1] = "Y";
})(Axis || (Axis = {}));
/**
* Lock a camera to the exact x/y position of an actor.
*/
var LockCameraToActorStrategy = /** @class */ (function () {
function LockCameraToActorStrategy(target) {
this.target = target;
this.action = function (target, _cam, _eng, _delta) {
var center = target.center;
return center;
};
}
return LockCameraToActorStrategy;
}());
/**
* Lock a camera to a specific axis around an actor.
*/
var LockCameraToActorAxisStrategy = /** @class */ (function () {
function LockCameraToActorAxisStrategy(target, axis) {
var _this = this;
this.target = target;
this.axis = axis;
this.action = function (target, cam, _eng, _delta) {
var center = target.center;
var currentFocus = cam.getFocus();
if (_this.axis === Axis.X) {
return new _Algebra__WEBPACK_IMPORTED_MODULE_2__["Vector"](center.x, currentFocus.y);
}
else {
return new _Algebra__WEBPACK_IMPORTED_MODULE_2__["Vector"](currentFocus.x, center.y);
}
};
}
return LockCameraToActorAxisStrategy;
}());
/**
* Using [Hook's law](https://en.wikipedia.org/wiki/Hooke's_law), elastically move the camera towards the target actor.
*/
var ElasticToActorStrategy = /** @class */ (function () {
/**
* If cameraElasticity < cameraFriction < 1.0, the behavior will be a dampened spring that will slowly end at the target without bouncing
* If cameraFriction < cameraElasticity < 1.0, the behavior will be an oscillating spring that will over
* correct and bounce around the target
*
* @param target Target actor to elastically follow
* @param cameraElasticity [0 - 1.0] The higher the elasticity the more force that will drive the camera towards the target
* @param cameraFriction [0 - 1.0] The higher the friction the more that the camera will resist motion towards the target
*/
function ElasticToActorStrategy(target, cameraElasticity, cameraFriction) {
var _this = this;
this.target = target;
this.cameraElasticity = cameraElasticity;
this.cameraFriction = cameraFriction;
this.action = function (target, cam, _eng, _delta) {
var position = target.center;
var focus = cam.getFocus();
var cameraVel = cam.vel.clone();
// Calculate the stretch vector, using the spring equation
// F = kX
// https://en.wikipedia.org/wiki/Hooke's_law
// Apply to the current camera velocity
var stretch = position.sub(focus).scale(_this.cameraElasticity); // stretch is X
cameraVel = cameraVel.add(stretch);
// Calculate the friction (-1 to apply a force in the opposition of motion)
// Apply to the current camera velocity
var friction = cameraVel.scale(-1).scale(_this.cameraFriction);
cameraVel = cameraVel.add(friction);
// Update position by velocity deltas
focus = focus.add(cameraVel);
return focus;
};
}
return ElasticToActorStrategy;
}());
var RadiusAroundActorStrategy = /** @class */ (function () {
/**
*
* @param target Target actor to follow when it is "radius" pixels away
* @param radius Number of pixels away before the camera will follow
*/
function RadiusAroundActorStrategy(target, radius) {
var _this = this;
this.target = target;
this.radius = radius;
this.action = function (target, cam, _eng, _delta) {
var position = target.center;
var focus = cam.getFocus();
var direction = position.sub(focus);
var distance = direction.size;
if (distance >= _this.radius) {
var offset = distance - _this.radius;
return focus.add(direction.normalize().scale(offset));
}
return focus;
};
}
return RadiusAroundActorStrategy;
}());
/**
* Prevent a camera from going beyond the given camera dimensions.
*/
var LimitCameraBoundsStrategy = /** @class */ (function () {
function LimitCameraBoundsStrategy(target) {
var _this = this;
this.target = target;
/**
* Useful for limiting the camera to a [[TileMap]]'s dimensions, or a specific area inside the map.
*
* Note that this strategy does not perform any movement by itself.
* It only sets the camera position to within the given bounds when the camera has gone beyond them.
* Thus, it is a good idea to combine it with other camera strategies and set this strategy as the last one.
*
* Make sure that the camera bounds are at least as large as the viewport size.
*
* @param target The bounding box to limit the camera to
*/
this.boundSizeChecked = false; // Check and warn only once
this.action = function (target, cam, _eng, _delta) {
var focus = cam.getFocus();
if (!_this.boundSizeChecked) {
if (target.bottom - target.top < _eng.drawHeight || target.right - target.left < _eng.drawWidth) {
_Util_Log__WEBPACK_IMPORTED_MODULE_7__["Logger"].getInstance().warn('Camera bounds should not be smaller than the engine viewport');
}
_this.boundSizeChecked = true;
}
if (focus.x < target.left + _eng.halfDrawWidth) {
focus.x = target.left + _eng.halfDrawWidth;
}
else if (focus.x > target.right - _eng.halfDrawWidth) {
focus.x = target.right - _eng.halfDrawWidth;
}
if (focus.y < target.top + _eng.halfDrawHeight) {
focus.y = target.top + _eng.halfDrawHeight;
}
else if (focus.y > target.bottom - _eng.halfDrawHeight) {
focus.y = target.bottom - _eng.halfDrawHeight;
}
return focus;
};
}
return LimitCameraBoundsStrategy;
}());
/**
* Cameras
*
* [[Camera]] is the base class for all Excalibur cameras. Cameras are used
* to move around your game and set focus. They are used to determine
* what is "off screen" and can be used to scale the game.
*
* [[include:Cameras.md]]
*/
var Camera = /** @class */ (function (_super) {
__extends(Camera, _super);
function Camera() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this._cameraStrategies = [];
_this.strategy = new StrategyContainer(_this);
/**
* Get or set current zoom of the camera, defaults to 1
*/
_this.z = 1;
/**
* Get or set rate of change in zoom, defaults to 0
*/
_this.dz = 0;
/**
* Get or set zoom acceleration
*/
_this.az = 0;
/**
* Current rotation of the camera
*/
_this.rotation = 0;
/**
* Current angular velocity
*/
_this.rx = 0;
/**
* Get or set the camera's position
*/
_this.pos = _Algebra__WEBPACK_IMPORTED_MODULE_2__["Vector"].Zero;
/**
* Get or set the camera's velocity
*/
_this.vel = _Algebra__WEBPACK_IMPORTED_MODULE_2__["Vector"].Zero;
/**
* GEt or set the camera's acceleration
*/
_this.acc = _Algebra__WEBPACK_IMPORTED_MODULE_2__["Vector"].Zero;
_this._cameraMoving = false;
_this._currentLerpTime = 0;
_this._lerpDuration = 1000; // 1 second
_this._lerpStart = null;
_this._lerpEnd = null;
//camera effects
_this._isShaking = false;
_this._shakeMagnitudeX = 0;
_this._shakeMagnitudeY = 0;
_this._shakeDuration = 0;
_this._elapsedShakeTime = 0;
_this._xShake = 0;
_this._yShake = 0;
_this._isZooming = false;
_this._zoomStart = 1;
_this._zoomEnd = 1;
_this._currentZoomTime = 0;
_this._zoomDuration = 0;
_this._zoomEasing = _Util_EasingFunctions__WEBPACK_IMPORTED_MODULE_0__["EasingFunctions"].EaseInOutCubic;
_this._easing = _Util_EasingFunctions__WEBPACK_IMPORTED_MODULE_0__["EasingFunctions"].EaseInOutCubic;
_this._isInitialized = false;
return _this;
}
Object.defineProperty(Camera.prototype, "angularVelocity", {
/**
* Get or set the camera's angular velocity
*/
get: function () {
return this.rx;
},
set: function (value) {
this.rx = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Camera.prototype, "x", {
/**
* Get the camera's x position
*/
get: function () {
return this.pos.x;
},
/**
* Set the camera's x position (cannot be set when following an [[Actor]] or when moving)
*/
set: function (value) {
if (!this._follow && !this._cameraMoving) {
this.pos.x = value;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(Camera.prototype, "y", {
/**
* Get the camera's y position
*/
get: function () {
return this.pos.y;
},
/**
* Set the camera's y position (cannot be set when following an [[Actor]] or when moving)
*/
set: function (value) {
if (!this._follow && !this._cameraMoving) {
this.pos.y = value;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(Camera.prototype, "dx", {
/**
* Get or set the camera's x velocity
*/
get: function () {
return this.vel.x;
},
set: function (value) {
this.vel.x = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Camera.prototype, "dy", {
/**
* Get or set the camera's y velocity
*/
get: function () {
return this.vel.y;
},
set: function (value) {
this.vel.y = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Camera.prototype, "ax", {
/**
* Get or set the camera's x acceleration
*/
get: function () {
return this.acc.x;
},
set: function (value) {
this.acc.x = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Camera.prototype, "ay", {
/**
* Get or set the camera's y acceleration
*/
get: function () {
return this.acc.y;
},
set: function (value) {
this.acc.y = value;
},
enumerable: false,
configurable: true
});
/**
* Returns the focal point of the camera, a new point giving the x and y position of the camera
*/
Camera.prototype.getFocus = function () {
return this.pos;
};
/**
* This moves the camera focal point to the specified position using specified easing function. Cannot move when following an Actor.
*
* @param pos The target position to move to
* @param duration The duration in milliseconds the move should last
* @param [easingFn] An optional easing function ([[ex.EasingFunctions.EaseInOutCubic]] by default)
* @returns A [[Promise]] that resolves when movement is finished, including if it's interrupted.
* The [[Promise]] value is the [[Vector]] of the target position. It will be rejected if a move cannot be made.
*/
Camera.prototype.move = function (pos, duration, easingFn) {
if (easingFn === void 0) { easingFn = _Util_EasingFunctions__WEBPACK_IMPORTED_MODULE_0__["EasingFunctions"].EaseInOutCubic; }
if (typeof easingFn !== 'function') {
throw 'Please specify an EasingFunction';
}
// cannot move when following an actor
if (this._follow) {
return new _Promises__WEBPACK_IMPORTED_MODULE_1__["Promise"]().reject(pos);
}
// resolve existing promise, if any
if (this._lerpPromise && this._lerpPromise.state() === _Promises__WEBPACK_IMPORTED_MODULE_1__["PromiseState"].Pending) {
this._lerpPromise.resolve(pos);
}
this._lerpPromise = new _Promises__WEBPACK_IMPORTED_MODULE_1__["Promise"]();
this._lerpStart = this.getFocus().clone();
this._lerpDuration = duration;
this._lerpEnd = pos;
this._currentLerpTime = 0;
this._cameraMoving = true;
this._easing = easingFn;
return this._lerpPromise;
};
/**
* Sets the camera to shake at the specified magnitudes for the specified duration
* @param magnitudeX The x magnitude of the shake
* @param magnitudeY The y magnitude of the shake
* @param duration The duration of the shake in milliseconds
*/
Camera.prototype.shake = function (magnitudeX, magnitudeY, duration) {
this._isShaking = true;
this._shakeMagnitudeX = magnitudeX;
this._shakeMagnitudeY = magnitudeY;
this._shakeDuration = duration;
};
/**
* Zooms the camera in or out by the specified scale over the specified duration.
* If no duration is specified, it take effect immediately.
* @param scale The scale of the zoom
* @param duration The duration of the zoom in milliseconds
*/
Camera.prototype.zoom = function (scale, duration, easingFn) {
if (duration === void 0) { duration = 0; }
if (easingFn === void 0) { easingFn = _Util_EasingFunctions__WEBPACK_IMPORTED_MODULE_0__["EasingFunctions"].EaseInOutCubic; }
this._zoomPromise = new _Promises__WEBPACK_IMPORTED_MODULE_1__["Promise"]();
if (duration) {
this._isZooming = true;
this._zoomEasing = easingFn;
this._currentZoomTime = 0;
this._zoomDuration = duration;
this._zoomStart = this.z;
this._zoomEnd = scale;
}
else {
this._isZooming = false;
this.z = scale;
this._zoomPromise.resolve(true);
}
return this._zoomPromise;
};
/**
* Gets the current zoom scale
*/
Camera.prototype.getZoom = function () {
return this.z;
};
Object.defineProperty(Camera.prototype, "viewport", {
/**
* Gets the bounding box of the viewport of this camera in world coordinates
*/
get: function () {
if (this._engine) {
var halfWidth = this._engine.halfDrawWidth;
var halfHeight = this._engine.halfDrawHeight;
return new _Collision_BoundingBox__WEBPACK_IMPORTED_MODULE_6__["BoundingBox"](this.x - halfWidth, this.y - halfHeight, this.x + halfWidth, this.y + halfHeight);
}
return new _Collision_BoundingBox__WEBPACK_IMPORTED_MODULE_6__["BoundingBox"](0, 0, 0, 0);
},
enumerable: false,
configurable: true
});
/**
* Adds a new camera strategy to this camera
* @param cameraStrategy Instance of an [[CameraStrategy]]
*/
Camera.prototype.addStrategy = function (cameraStrategy) {
this._cameraStrategies.push(cameraStrategy);
};
/**
* Removes a camera strategy by reference
* @param cameraStrategy Instance of an [[CameraStrategy]]
*/
Camera.prototype.removeStrategy = function (cameraStrategy) {
Object(_Util_Util__WEBPACK_IMPORTED_MODULE_3__["removeItemFromArray"])(cameraStrategy, this._cameraStrategies);
};
/**
* Clears all camera strategies from the camera
*/
Camera.prototype.clearAllStrategies = function () {
this._cameraStrategies.length = 0;
};
/**
* It is not recommended that internal excalibur methods be overridden, do so at your own risk.
*
* Internal _preupdate handler for [[onPreUpdate]] lifecycle event
* @internal
*/
Camera.prototype._preupdate = function (engine, delta) {
this.emit('preupdate', new _Events__WEBPACK_IMPORTED_MODULE_4__["PreUpdateEvent"](engine, delta, this));
this.onPreUpdate(engine, delta);
};
/**
* Safe to override onPreUpdate lifecycle event handler. Synonymous with `.on('preupdate', (evt) =>{...})`
*
* `onPreUpdate` is called directly before a scene is updated.
*/
Camera.prototype.onPreUpdate = function (_engine, _delta) {
// Overridable
};
/**
* It is not recommended that internal excalibur methods be overridden, do so at your own risk.
*
* Internal _preupdate handler for [[onPostUpdate]] lifecycle event
* @internal
*/
Camera.prototype._postupdate = function (engine, delta) {
this.emit('postupdate', new _Events__WEBPACK_IMPORTED_MODULE_4__["PostUpdateEvent"](engine, delta, this));
this.onPostUpdate(engine, delta);
};
/**
* Safe to override onPostUpdate lifecycle event handler. Synonymous with `.on('preupdate', (evt) =>{...})`
*
* `onPostUpdate` is called directly after a scene is updated.
*/
Camera.prototype.onPostUpdate = function (_engine, _delta) {
// Overridable
};
Object.defineProperty(Camera.prototype, "isInitialized", {
get: function () {
return this._isInitialized;
},
enumerable: false,
configurable: true
});
Camera.prototype._initialize = function (_engine) {
if (!this.isInitialized) {
this.onInitialize(_engine);
_super.prototype.emit.call(this, 'initialize', new _Events__WEBPACK_IMPORTED_MODULE_4__["InitializeEvent"](_engine, this));
this._isInitialized = true;
this._engine = _engine;
}
};
/**
* Safe to override onPostUpdate lifecycle event handler. Synonymous with `.on('preupdate', (evt) =>{...})`
*
* `onPostUpdate` is called directly after a scene is updated.
*/
Camera.prototype.onInitialize = function (_engine) {
// Overridable
};
Camera.prototype.on = function (eventName, handler) {
_super.prototype.on.call(this, eventName, handler);
};
Camera.prototype.off = function (eventName, handler) {
_super.prototype.off.call(this, eventName, handler);
};
Camera.prototype.once = function (eventName, handler) {
_super.prototype.once.call(this, eventName, handler);
};
Camera.prototype.update = function (_engine, delta) {
this._initialize(_engine);
this._preupdate(_engine, delta);
// Update placements based on linear algebra
this.pos = this.pos.add(this.vel.scale(delta / 1000));
this.z += (this.dz * delta) / 1000;
this.vel = this.vel.add(this.acc.scale(delta / 1000));
this.dz += (this.az * delta) / 1000;
this.rotation += (this.angularVelocity * delta) / 1000;
if (this._isZooming) {
if (this._currentZoomTime < this._zoomDuration) {
var zoomEasing = this._zoomEasing;
var newZoom = zoomEasing(this._currentZoomTime, this._zoomStart, this._zoomEnd, this._zoomDuration);
this.z = newZoom;
this._currentZoomTime += delta;
}
else {
this._isZooming = false;
this.z = this._zoomEnd;
this._currentZoomTime = 0;
this._zoomPromise.resolve(true);
}
}
if (this._cameraMoving) {
if (this._currentLerpTime < this._lerpDuration) {
var moveEasing = _Util_EasingFunctions__WEBPACK_IMPORTED_MODULE_0__["EasingFunctions"].CreateVectorEasingFunction(this._easing);
var lerpPoint = moveEasing(this._currentLerpTime, this._lerpStart, this._lerpEnd, this._lerpDuration);
this.pos = lerpPoint;
this._currentLerpTime += delta;
}
else {
this.pos = this._lerpEnd;
var end = this._lerpEnd.clone();
this._lerpStart = null;
this._lerpEnd = null;
this._currentLerpTime = 0;
this._cameraMoving = false;
// Order matters here, resolve should be last so any chain promises have a clean slate
this._lerpPromise.resolve(end);
}
}
if (this._isDoneShaking()) {
this._isShaking = false;
this._elapsedShakeTime = 0;
this._shakeMagnitudeX = 0;
this._shakeMagnitudeY = 0;
this._shakeDuration = 0;
this._xShake = 0;
this._yShake = 0;
}
else {
this._elapsedShakeTime += delta;
this._xShake = ((Math.random() * this._shakeMagnitudeX) | 0) + 1;
this._yShake = ((Math.random() * this._shakeMagnitudeY) | 0) + 1;
}
for (var _i = 0, _a = this._cameraStrategies; _i < _a.length; _i++) {
var s = _a[_i];
this.pos = s.action.call(s, s.target, this, _engine, delta);
}
this._postupdate(_engine, delta);
};
/**
* Applies the relevant transformations to the game canvas to "move" or apply effects to the Camera
* @param ctx Canvas context to apply transformations
* @param delta The number of milliseconds since the last update
*/
Camera.prototype.draw = function (ctx) {
var focus = this.getFocus();
var canvasWidth = ctx.canvas.width;
var canvasHeight = ctx.canvas.height;
var pixelRatio = this._engine ? this._engine.pixelRatio : window.devicePixelRatio;
var zoom = this.getZoom();
var newCanvasWidth = canvasWidth / zoom / pixelRatio;
var newCanvasHeight = canvasHeight / zoom / pixelRatio;
ctx.scale(zoom, zoom);
ctx.translate(-focus.x + newCanvasWidth / 2 + this._xShake, -focus.y + newCanvasHeight / 2 + this._yShake);
};
Camera.prototype.debugDraw = function (ctx) {
var focus = this.getFocus();
ctx.fillStyle = 'red';
ctx.strokeStyle = 'white';
ctx.lineWidth = 3;
ctx.beginPath();
ctx.arc(focus.x, focus.y, 15, 0, Math.PI * 2);
ctx.closePath();
ctx.stroke();
ctx.beginPath();
ctx.arc(focus.x, focus.y, 5, 0, Math.PI * 2);
ctx.closePath();
ctx.stroke();
ctx.beginPath();
ctx.setLineDash([5, 15]);
ctx.lineWidth = 5;
ctx.strokeStyle = 'white';
ctx.strokeRect(this.viewport.left, this.viewport.top, this.viewport.width, this.viewport.height);
ctx.closePath();
};
Camera.prototype._isDoneShaking = function () {
return !this._isShaking || this._elapsedShakeTime >= this._shakeDuration;
};
return Camera;
}(_Class__WEBPACK_IMPORTED_MODULE_5__["Class"]));
/***/ }),
/***/ "./Class.ts":
/*!******************!*\
!*** ./Class.ts ***!
\******************/
/*! exports provided: Class */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Class", function() { return Class; });
/* harmony import */ var _EventDispatcher__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./EventDispatcher */ "./EventDispatcher.ts");
/**
* Excalibur base class that provides basic functionality such as [[EventDispatcher]]
* and extending abilities for vanilla Javascript projects
*/
var Class = /** @class */ (function () {
function Class() {
this.eventDispatcher = new _EventDispatcher__WEBPACK_IMPORTED_MODULE_0__["EventDispatcher"](this);
}
/**
* Alias for `addEventListener`. You can listen for a variety of
* events off of the engine; see the events section below for a complete list.
* @param eventName Name of the event to listen for
* @param handler Event handler for the thrown event
*/
Class.prototype.on = function (eventName, handler) {
this.eventDispatcher.on(eventName, handler);
};
/**
* Alias for `removeEventListener`. If only the eventName is specified
* it will remove all handlers registered for that specific event. If the eventName
* and the handler instance are specified only that handler will be removed.
*
* @param eventName Name of the event to listen for
* @param handler Event handler for the thrown event
*/
Class.prototype.off = function (eventName, handler) {
this.eventDispatcher.off(eventName, handler);
};
/**
* Emits a new event
* @param eventName Name of the event to emit
* @param eventObject Data associated with this event
*/
Class.prototype.emit = function (eventName, eventObject) {
this.eventDispatcher.emit(eventName, eventObject);
};
/**
* Once listens to an event one time, then unsubscribes from that event
*
* @param eventName The name of the event to subscribe to once
* @param handler The handler of the event that will be auto unsubscribed
*/
Class.prototype.once = function (eventName, handler) {
this.eventDispatcher.once(eventName, handler);
};
return Class;
}());
/***/ }),
/***/ "./Collision/Body.ts":
/*!***************************!*\
!*** ./Collision/Body.ts ***!
\***************************/
/*! exports provided: Body */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Body", function() { return Body; });
/* harmony import */ var _Algebra__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Algebra */ "./Algebra.ts");
/* harmony import */ var _CollisionType__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./CollisionType */ "./Collision/CollisionType.ts");
/* harmony import */ var _Physics__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Physics */ "./Physics.ts");
/* harmony import */ var _Events__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Events */ "./Events.ts");
/* harmony import */ var _Shape__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Shape */ "./Collision/Shape.ts");
/**
* Body describes all the physical properties pos, vel, acc, rotation, angular velocity
*/
var Body = /** @class */ (function () {
/**
* Constructs a new physics body associated with an actor
*/
function Body(_a) {
var actor = _a.actor, collider = _a.collider;
/**
* The (x, y) position of the actor this will be in the middle of the actor if the
* [[Actor.anchor]] is set to (0.5, 0.5) which is default.
* If you want the (x, y) position to be the top left of the actor specify an anchor of (0, 0).
*/
this.pos = new _Algebra__WEBPACK_IMPORTED_MODULE_0__["Vector"](0, 0);
/**
* The position of the actor last frame (x, y) in pixels
*/
this.oldPos = new _Algebra__WEBPACK_IMPORTED_MODULE_0__["Vector"](0, 0);
/**
* The current velocity vector (vx, vy) of the actor in pixels/second
*/
this.vel = new _Algebra__WEBPACK_IMPORTED_MODULE_0__["Vector"](0, 0);
/**
* The velocity of the actor last frame (vx, vy) in pixels/second
*/
this.oldVel = new _Algebra__WEBPACK_IMPORTED_MODULE_0__["Vector"](0, 0);
/**
* The current acceleration vector (ax, ay) of the actor in pixels/second/second. An acceleration pointing down such as (0, 100) may
* be useful to simulate a gravitational effect.
*/
this.acc = new _Algebra__WEBPACK_IMPORTED_MODULE_0__["Vector"](0, 0);
/**
* Gets/sets the acceleration of the actor from the last frame. This does not include the global acc [[Physics.acc]].
*/
this.oldAcc = _Algebra__WEBPACK_IMPORTED_MODULE_0__["Vector"].Zero;
/**
* The current torque applied to the actor
*/
this.torque = 0;
/**
* The current "motion" of the actor, used to calculated sleep in the physics simulation
*/
this.motion = 10;
/**
* Gets/sets the rotation of the body from the last frame.
*/
this.oldRotation = 0; // radians
/**
* The rotation of the actor in radians
*/
this.rotation = 0; // radians
/**
* The scale vector of the actor
* @obsolete ex.Body.scale will be removed in v0.25.0
*/
this.scale = _Algebra__WEBPACK_IMPORTED_MODULE_0__["Vector"].One;
/**
* The scale of the actor last frame
* @obsolete ex.Body.scale will be removed in v0.25.0
*/
this.oldScale = _Algebra__WEBPACK_IMPORTED_MODULE_0__["Vector"].One;
/**
* The x scalar velocity of the actor in scale/second
* @obsolete ex.Body.scale will be removed in v0.25.0
*/
this.sx = 0; //scale/sec
/**
* The y scalar velocity of the actor in scale/second
* @obsolete ex.Body.scale will be removed in v0.25.0
*/
this.sy = 0; //scale/sec
/**
* The rotational velocity of the actor in radians/second
*/
this.rx = 0; //radians/sec
this._geometryDirty = false;
this._totalMtv = _Algebra__WEBPACK_IMPORTED_MODULE_0__["Vector"].Zero;
if (!actor && !collider) {
throw new Error('An actor or collider are required to create a body');
}
this.actor = actor;
if (!collider && actor) {
this.collider = this.useBoxCollider(actor.width, actor.height, actor.anchor);
}
else {
this.collider = collider;
}
}
Object.defineProperty(Body.prototype, "id", {
get: function () {
return this.actor ? this.actor.id : -1;
},
enumerable: false,
configurable: true
});
/**
* Returns a clone of this body, not associated with any actor
*/
Body.prototype.clone = function () {
return new Body({
actor: null,
collider: this.collider.clone()
});
};
Object.defineProperty(Body.prototype, "active", {
get: function () {
return this.actor ? !this.actor.isKilled() : false;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Body.prototype, "center", {
get: function () {
return this.pos;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Body.prototype, "collider", {
get: function () {
return this._collider;
},
// TODO allow multiple colliders for a single body
set: function (collider) {
if (collider) {
this._collider = collider;
this._collider.body = this;
this._wireColliderEventsToActor();
}
},
enumerable: false,
configurable: true
});
/**
* Add minimum translation vectors accumulated during the current frame to resolve collisions.
*/
Body.prototype.addMtv = function (mtv) {
this._totalMtv.addEqual(mtv);
};
/**
* Applies the accumulated translation vectors to the actors position
*/
Body.prototype.applyMtv = function () {
this.pos.addEqual(this._totalMtv);
this._totalMtv.setTo(0, 0);
};
/**
* Flags the shape dirty and must be recalculated in world space
*/
Body.prototype.markCollisionShapeDirty = function () {
this._geometryDirty = true;
};
Object.defineProperty(Body.prototype, "isColliderShapeDirty", {
get: function () {
return this._geometryDirty;
},
enumerable: false,
configurable: true
});
/**
* Sets the old versions of pos, vel, acc, and scale.
*/
Body.prototype.captureOldTransform = function () {
// Capture old values before integration step updates them
this.oldVel.setTo(this.vel.x, this.vel.y);
this.oldPos.setTo(this.pos.x, this.pos.y);
this.oldAcc.setTo(this.acc.x, this.acc.y);
this.oldScale.setTo(this.scale.x, this.scale.y);
this.oldRotation = this.rotation;
};
/**
* Perform euler integration at the specified time step
*/
Body.prototype.integrate = function (delta) {
// Update placements based on linear algebra
var seconds = delta / 1000;
var totalAcc = this.acc.clone();
// Only active vanilla actors are affected by global acceleration
if (this.collider.type === _CollisionType__WEBPACK_IMPORTED_MODULE_1__["CollisionType"].Active) {
totalAcc.addEqual(_Physics__WEBPACK_IMPORTED_MODULE_2__["Physics"].acc);
}
this.vel.addEqual(totalAcc.scale(seconds));
this.pos.addEqual(this.vel.scale(seconds)).addEqual(totalAcc.scale(0.5 * seconds * seconds));
this.rx += this.torque * (1.0 / this.collider.inertia) * seconds;
this.rotation += this.rx * seconds;
this.scale.x += (this.sx * delta) / 1000;
this.scale.y += (this.sy * delta) / 1000;
if (!this.scale.equals(this.oldScale)) {
// change in scale effects the geometry
this._geometryDirty = true;
}
// Update colliders
this.collider.update();
this._geometryDirty = false;
};
/**
* Sets up a box geometry based on the current bounds of the associated actor of this physics body.
*
* If no width/height are specified the body will attempt to use the associated actor's width/height.
*
* By default, the box is center is at (0, 0) which means it is centered around the actors anchor.
*/
Body.prototype.useBoxCollider = function (width, height, anchor, center) {
if (anchor === void 0) { anchor = _Algebra__WEBPACK_IMPORTED_MODULE_0__["Vector"].Half; }
if (center === void 0) { center = _Algebra__WEBPACK_IMPORTED_MODULE_0__["Vector"].Zero; }
if (width === null || width === undefined) {
width = this.actor ? this.actor.width : 0;
}
if (height === null || height === undefined) {
height = this.actor ? this.actor.height : 0;
}
this.collider.shape = _Shape__WEBPACK_IMPORTED_MODULE_4__["Shape"].Box(width, height, anchor, center);
return this.collider;
};
/**
* Sets up a [[ConvexPolygon|convex polygon]] collision geometry based on a list of of points relative
* to the anchor of the associated actor
* of this physics body.
*
* Only [convex polygon](https://en.wikipedia.org/wiki/Convex_polygon) definitions are supported.
*
* By default, the box is center is at (0, 0) which means it is centered around the actors anchor.
*/
Body.prototype.usePolygonCollider = function (points, center) {
if (center === void 0) { center = _Algebra__WEBPACK_IMPORTED_MODULE_0__["Vector"].Zero; }
this.collider.shape = _Shape__WEBPACK_IMPORTED_MODULE_4__["Shape"].Polygon(points, false, center);
return this.collider;
};
/**
* Sets up a [[Circle|circle collision geometry]] with a specified radius in pixels.
*
* By default, the box is center is at (0, 0) which means it is centered around the actors anchor.
*/
Body.prototype.useCircleCollider = function (radius, center) {
if (center === void 0) { center = _Algebra__WEBPACK_IMPORTED_MODULE_0__["Vector"].Zero; }
this.collider.shape = _Shape__WEBPACK_IMPORTED_MODULE_4__["Shape"].Circle(radius, center);
return this.collider;
};
/**
* Sets up an [[Edge|edge collision geometry]] with a start point and an end point relative to the anchor of the associated actor
* of this physics body.
*
* By default, the box is center is at (0, 0) which means it is centered around the actors anchor.
*/
Body.prototype.useEdgeCollider = function (begin, end) {
this.collider.shape = _Shape__WEBPACK_IMPORTED_MODULE_4__["Shape"].Edge(begin, end);
return this.collider;
};
// TODO remove this, eventually events will stay local to the thing they are around
Body.prototype._wireColliderEventsToActor = function () {
var _this = this;
this.collider.clear();
this.collider.on('precollision', function (evt) {
if (_this.actor) {
_this.actor.emit('precollision', new _Events__WEBPACK_IMPORTED_MODULE_3__["PreCollisionEvent"](evt.target.body.actor, evt.other.body.actor, evt.side, evt.intersection));
}
});
this.collider.on('postcollision', function (evt) {
if (_this.actor) {
_this.actor.emit('postcollision', new _Events__WEBPACK_IMPORTED_MODULE_3__["PostCollisionEvent"](evt.target.body.actor, evt.other.body.actor, evt.side, evt.intersection));
}
});
this.collider.on('collisionstart', function (evt) {
if (_this.actor) {
_this.actor.emit('collisionstart', new _Events__WEBPACK_IMPORTED_MODULE_3__["CollisionStartEvent"](evt.target.body.actor, evt.other.body.actor, evt.pair));
}
});
this.collider.on('collisionend', function (evt) {
if (_this.actor) {
_this.actor.emit('collisionend', new _Events__WEBPACK_IMPORTED_MODULE_3__["CollisionEndEvent"](evt.target.body.actor, evt.other.body.actor));
}
});
};
return Body;
}());
/***/ }),
/***/ "./Collision/BoundingBox.ts":
/*!**********************************!*\
!*** ./Collision/BoundingBox.ts ***!
\**********************************/
/*! exports provided: BoundingBox */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BoundingBox", function() { return BoundingBox; });
/* harmony import */ var _ConvexPolygon__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ConvexPolygon */ "./Collision/ConvexPolygon.ts");
/* harmony import */ var _Algebra__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Algebra */ "./Algebra.ts");
/* harmony import */ var _Drawing_Color__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Drawing/Color */ "./Drawing/Color.ts");
/* harmony import */ var _Side__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Side */ "./Collision/Side.ts");
/**
* Axis Aligned collision primitive for Excalibur.
*/
var BoundingBox = /** @class */ (function () {
/**
* Constructor allows passing of either an object with all coordinate components,
* or the coordinate components passed separately.
* @param leftOrOptions Either x coordinate of the left edge or an options object
* containing the four coordinate components.
* @param top y coordinate of the top edge
* @param right x coordinate of the right edge
* @param bottom y coordinate of the bottom edge
*/
function BoundingBox(leftOrOptions, top, right, bottom) {
if (leftOrOptions === void 0) { leftOrOptions = 0; }
if (top === void 0) { top = 0; }
if (right === void 0) { right = 0; }
if (bottom === void 0) { bottom = 0; }
if (typeof leftOrOptions === 'object') {
this.left = leftOrOptions.left;
this.top = leftOrOptions.top;
this.right = leftOrOptions.right;
this.bottom = leftOrOptions.bottom;
}
else if (typeof leftOrOptions === 'number') {
this.left = leftOrOptions;
this.top = top;
this.right = right;
this.bottom = bottom;
}
}
/**
* Given bounding box A & B, returns the side relative to A when intersection is performed.
* @param intersection Intersection vector between 2 bounding boxes
*/
BoundingBox.getSideFromIntersection = function (intersection) {
if (!intersection) {
return _Side__WEBPACK_IMPORTED_MODULE_3__["Side"].None;
}
if (intersection) {
if (Math.abs(intersection.x) > Math.abs(intersection.y)) {
if (intersection.x < 0) {
return _Side__WEBPACK_IMPORTED_MODULE_3__["Side"].Right;
}
return _Side__WEBPACK_IMPORTED_MODULE_3__["Side"].Left;
}
else {
if (intersection.y < 0) {
return _Side__WEBPACK_IMPORTED_MODULE_3__["Side"].Bottom;
}
return _Side__WEBPACK_IMPORTED_MODULE_3__["Side"].Top;
}
}
return _Side__WEBPACK_IMPORTED_MODULE_3__["Side"].None;
};
BoundingBox.fromPoints = function (points) {
var minX = Infinity;
var minY = Infinity;
var maxX = -Infinity;
var maxY = -Infinity;
for (var i = 0; i < points.length; i++) {
if (points[i].x < minX) {
minX = points[i].x;
}
if (points[i].x > maxX) {
maxX = points[i].x;
}
if (points[i].y < minY) {
minY = points[i].y;
}
if (points[i].y > maxY) {
maxY = points[i].y;
}
}
return new BoundingBox(minX, minY, maxX, maxY);
};
BoundingBox.fromDimension = function (width, height, anchor, pos) {
if (anchor === void 0) { anchor = _Algebra__WEBPACK_IMPORTED_MODULE_1__["Vector"].Half; }
if (pos === void 0) { pos = _Algebra__WEBPACK_IMPORTED_MODULE_1__["Vector"].Zero; }
return new BoundingBox(-width * anchor.x + pos.x, -height * anchor.y + pos.y, width - width * anchor.x + pos.x, height - height * anchor.y + pos.y);
};
Object.defineProperty(BoundingBox.prototype, "width", {
/**
* Returns the calculated width of the bounding box
*/
get: function () {
return this.right - this.left;
},
enumerable: false,
configurable: true
});
Object.defineProperty(BoundingBox.prototype, "height", {
/**
* Returns the calculated height of the bounding box
*/
get: function () {
return this.bottom - this.top;
},
enumerable: false,
configurable: true
});
Object.defineProperty(BoundingBox.prototype, "center", {
/**
* Returns the center of the bounding box
*/
get: function () {
return new _Algebra__WEBPACK_IMPORTED_MODULE_1__["Vector"]((this.left + this.right) / 2, (this.top + this.bottom) / 2);
},
enumerable: false,
configurable: true
});
BoundingBox.prototype.translate = function (pos) {
return new BoundingBox(this.left + pos.x, this.top + pos.y, this.right + pos.x, this.bottom + pos.y);
};
/**
* Rotates a bounding box by and angle and around a point, if no point is specified (0, 0) is used by default. The resulting bounding
* box is also axis-align. This is useful when a new axis-aligned bounding box is needed for rotated geometry.
*/
BoundingBox.prototype.rotate = function (angle, point) {
if (point === void 0) { point = _Algebra__WEBPACK_IMPORTED_MODULE_1__["Vector"].Zero; }
var points = this.getPoints().map(function (p) { return p.rotate(angle, point); });
return BoundingBox.fromPoints(points);
};
BoundingBox.prototype.scale = function (scale, point) {
if (point === void 0) { point = _Algebra__WEBPACK_IMPORTED_MODULE_1__["Vector"].Zero; }
var shifted = this.translate(point);
return new BoundingBox(shifted.left * scale.x, shifted.top * scale.y, shifted.right * scale.x, shifted.bottom * scale.y);
};
/**
* Returns the perimeter of the bounding box
*/
BoundingBox.prototype.getPerimeter = function () {
var wx = this.width;
var wy = this.height;
return 2 * (wx + wy);
};
BoundingBox.prototype.getPoints = function () {
var results = [];
results.push(new _Algebra__WEBPACK_IMPORTED_MODULE_1__["Vector"](this.left, this.top));
results.push(new _Algebra__WEBPACK_IMPORTED_MODULE_1__["Vector"](this.right, this.top));
results.push(new _Algebra__WEBPACK_IMPORTED_MODULE_1__["Vector"](this.right, this.bottom));
results.push(new _Algebra__WEBPACK_IMPORTED_MODULE_1__["Vector"](this.left, this.bottom));
return results;
};
/**
* Creates a Polygon collision area from the points of the bounding box
*/
BoundingBox.prototype.toPolygon = function (actor) {
var maybeCollider = null;
if (actor && actor.body && actor.body.collider) {
maybeCollider = actor.body.collider;
}
return new _ConvexPolygon__WEBPACK_IMPORTED_MODULE_0__["ConvexPolygon"]({
collider: maybeCollider,
points: this.getPoints(),
offset: _Algebra__WEBPACK_IMPORTED_MODULE_1__["Vector"].Zero
});
};
/**
* Determines whether a ray intersects with a bounding box
*/
BoundingBox.prototype.rayCast = function (ray, farClipDistance) {
if (farClipDistance === void 0) { farClipDistance = Infinity; }
// algorithm from https://tavianator.com/fast-branchless-raybounding-box-intersections/
var tmin = -Infinity;
var tmax = +Infinity;
var xinv = ray.dir.x === 0 ? Number.MAX_VALUE : 1 / ray.dir.x;
var yinv = ray.dir.y === 0 ? Number.MAX_VALUE : 1 / ray.dir.y;
var tx1 = (this.left - ray.pos.x) * xinv;
var tx2 = (this.right - ray.pos.x) * xinv;
tmin = Math.min(tx1, tx2);
tmax = Math.max(tx1, tx2);
var ty1 = (this.top - ray.pos.y) * yinv;
var ty2 = (this.bottom - ray.pos.y) * yinv;
tmin = Math.max(tmin, Math.min(ty1, ty2));
tmax = Math.min(tmax, Math.max(ty1, ty2));
return tmax >= Math.max(0, tmin) && tmin < farClipDistance;
};
BoundingBox.prototype.rayCastTime = function (ray, farClipDistance) {
if (farClipDistance === void 0) { farClipDistance = Infinity; }
// algorithm from https://tavianator.com/fast-branchless-raybounding-box-intersections/
var tmin = -Infinity;
var tmax = +Infinity;
var xinv = ray.dir.x === 0 ? Number.MAX_VALUE : 1 / ray.dir.x;
var yinv = ray.dir.y === 0 ? Number.MAX_VALUE : 1 / ray.dir.y;
var tx1 = (this.left - ray.pos.x) * xinv;
var tx2 = (this.right - ray.pos.x) * xinv;
tmin = Math.min(tx1, tx2);
tmax = Math.max(tx1, tx2);
var ty1 = (this.top - ray.pos.y) * yinv;
var ty2 = (this.bottom - ray.pos.y) * yinv;
tmin = Math.max(tmin, Math.min(ty1, ty2));
tmax = Math.min(tmax, Math.max(ty1, ty2));
if (tmax >= Math.max(0, tmin) && tmin < farClipDistance) {
return tmin;
}
return -1;
};
BoundingBox.prototype.contains = function (val) {
if (val instanceof _Algebra__WEBPACK_IMPORTED_MODULE_1__["Vector"]) {
return this.left <= val.x && this.top <= val.y && this.bottom >= val.y && this.right >= val.x;
}
else if (val instanceof BoundingBox) {
if (this.left < val.left && this.top < val.top && val.bottom < this.bottom && val.right < this.right) {
return true;
}
return false;
}
return false;
};
/**
* Combines this bounding box and another together returning a new bounding box
* @param other The bounding box to combine
*/
BoundingBox.prototype.combine = function (other) {
var compositeBB = new BoundingBox(Math.min(this.left, other.left), Math.min(this.top, other.top), Math.max(this.right, other.right), Math.max(this.bottom, other.bottom));
return compositeBB;
};
Object.defineProperty(BoundingBox.prototype, "dimensions", {
get: function () {
return new _Algebra__WEBPACK_IMPORTED_MODULE_1__["Vector"](this.width, this.height);
},
enumerable: false,
configurable: true
});
/**
* Test wether this bounding box intersects with another returning
* the intersection vector that can be used to resolve the collision. If there
* is no intersection null is returned.
*
* @param other Other [[BoundingBox]] to test intersection with
* @returns A Vector in the direction of the current BoundingBox, this <- other
*/
BoundingBox.prototype.intersect = function (other) {
var totalBoundingBox = this.combine(other);
// If the total bounding box is less than or equal the sum of the 2 bounds then there is collision
if (totalBoundingBox.width < other.width + this.width &&
totalBoundingBox.height < other.height + this.height &&
!totalBoundingBox.dimensions.equals(other.dimensions) &&
!totalBoundingBox.dimensions.equals(this.dimensions)) {
// collision
var overlapX = 0;
// right edge is between the other's left and right edge
/**
* +-this-+
* | |
* | +-other-+
* +----|-+ |
* | |
* +-------+
* <---
* ^ overlap
*/
if (this.right >= other.left && this.right <= other.right) {
overlapX = other.left - this.right;
// right edge is past the other's right edge
/**
* +-other-+
* | |
* | +-this-+
* +----|--+ |
* | |
* +------+
* --->
* ^ overlap
*/
}
else {
overlapX = other.right - this.left;
}
var overlapY = 0;
// top edge is between the other's top and bottom edge
/**
* +-other-+
* | |
* | +-this-+ | <- overlap
* +----|--+ | |
* | | \ /
* +------+ '
*/
if (this.top <= other.bottom && this.top >= other.top) {
overlapY = other.bottom - this.top;
// top edge is above the other top edge
/**
* +-this-+ .
* | | / \
* | +-other-+ | <- overlap
* +----|-+ | |
* | |
* +-------+
*/
}
else {
overlapY = other.top - this.bottom;
}
if (Math.abs(overlapX) < Math.abs(overlapY)) {
return new _Algebra__WEBPACK_IMPORTED_MODULE_1__["Vector"](overlapX, 0);
}
else {
return new _Algebra__WEBPACK_IMPORTED_MODULE_1__["Vector"](0, overlapY);
}
// Case of total containment of one bounding box by another
}
else if (totalBoundingBox.dimensions.equals(other.dimensions) || totalBoundingBox.dimensions.equals(this.dimensions)) {
var overlapX = 0;
// this is wider than the other
if (this.width - other.width >= 0) {
// This right edge is closest to the others right edge
if (this.right - other.right <= other.left - this.left) {
overlapX = other.left - this.right;
// This left edge is closest to the others left edge
}
else {
overlapX = other.right - this.left;
}
// other is wider than this
}
else {
// This right edge is closest to the others right edge
if (other.right - this.right <= this.left - other.left) {
overlapX = this.left - other.right;
// This left edge is closest to the others left edge
}
else {
overlapX = this.right - other.left;
}
}
var overlapY = 0;
// this is taller than other
if (this.height - other.height >= 0) {
// The bottom edge is closest to the others bottom edge
if (this.bottom - other.bottom <= other.top - this.top) {
overlapY = other.top - this.bottom;
}
else {
overlapY = other.bottom - this.top;
}
// other is taller than this
}
else {
// The bottom edge is closest to the others bottom edge
if (other.bottom - this.bottom <= this.top - other.top) {
overlapY = this.top - other.bottom;
}
else {
overlapY = this.bottom - other.top;
}
}
if (Math.abs(overlapX) < Math.abs(overlapY)) {
return new _Algebra__WEBPACK_IMPORTED_MODULE_1__["Vector"](overlapX, 0);
}
else {
return new _Algebra__WEBPACK_IMPORTED_MODULE_1__["Vector"](0, overlapY);
}
}
else {
return null;
}
};
/**
* Test whether the bounding box has intersected with another bounding box, returns the side of the current bb that intersected.
* @param bb The other actor to test
*/
BoundingBox.prototype.intersectWithSide = function (bb) {
var intersect = this.intersect(bb);
return BoundingBox.getSideFromIntersection(intersect);
};
/* istanbul ignore next */
BoundingBox.prototype.debugDraw = function (ctx, color) {
if (color === void 0) { color = _Drawing_Color__WEBPACK_IMPORTED_MODULE_2__["Color"].Yellow; }
ctx.strokeStyle = color.toString();
ctx.strokeRect(this.left, this.top, this.width, this.height);
};
return BoundingBox;
}());
/***/ }),
/***/ "./Collision/Circle.ts":
/*!*****************************!*\
!*** ./Collision/Circle.ts ***!
\*****************************/
/*! exports provided: Circle */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Circle", function() { return Circle; });
/* harmony import */ var _BoundingBox__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./BoundingBox */ "./Collision/BoundingBox.ts");
/* harmony import */ var _CollisionJumpTable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./CollisionJumpTable */ "./Collision/CollisionJumpTable.ts");
/* harmony import */ var _ConvexPolygon__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./ConvexPolygon */ "./Collision/ConvexPolygon.ts");
/* harmony import */ var _Edge__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Edge */ "./Collision/Edge.ts");
/* harmony import */ var _Algebra__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Algebra */ "./Algebra.ts");
/* harmony import */ var _Physics__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Physics */ "./Physics.ts");
/* harmony import */ var _Drawing_Color__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Drawing/Color */ "./Drawing/Color.ts");
/* harmony import */ var _ClosestLineJumpTable__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./ClosestLineJumpTable */ "./Collision/ClosestLineJumpTable.ts");
/**
* This is a circle collision shape for the excalibur rigid body physics simulation
*
* Example:
* [[include:CircleShape.md]]
*/
var Circle = /** @class */ (function () {
function Circle(options) {
/**
* Position of the circle relative to the collider, by default (0, 0) meaning the shape is positioned on top of the collider.
*/
this.offset = _Algebra__WEBPACK_IMPORTED_MODULE_4__["Vector"].Zero;
this.offset = options.offset || _Algebra__WEBPACK_IMPORTED_MODULE_4__["Vector"].Zero;
this.radius = options.radius || 0;
this.collider = options.collider || null;
}
Object.defineProperty(Circle.prototype, "worldPos", {
get: function () {
if (this.collider && this.collider.body) {
return this.collider.body.pos.add(this.offset);
}
return this.offset;
},
enumerable: false,
configurable: true
});
/**
* Returns a clone of this shape, not associated with any collider
*/
Circle.prototype.clone = function () {
return new Circle({
offset: this.offset.clone(),
radius: this.radius,
collider: null
});
};
Object.defineProperty(Circle.prototype, "center", {
/**
* Get the center of the collision shape in world coordinates
*/
get: function () {
if (this.collider && this.collider.body) {
return this.offset.add(this.collider.body.pos);
}
return this.offset;
},
enumerable: false,
configurable: true
});
/**
* Tests if a point is contained in this collision shape
*/
Circle.prototype.contains = function (point) {
var pos = this.offset;
if (this.collider && this.collider.body) {
pos = this.collider.body.pos;
}
var distance = pos.distance(point);
if (distance <= this.radius) {
return true;
}
return false;
};
/**
* Casts a ray at the Circle shape and returns the nearest point of collision
* @param ray
*/
Circle.prototype.rayCast = function (ray, max) {
if (max === void 0) { max = Infinity; }
//https://en.wikipedia.org/wiki/Line%E2%80%93sphere_intersection
var c = this.center;
var dir = ray.dir;
var orig = ray.pos;
var discriminant = Math.sqrt(Math.pow(dir.dot(orig.sub(c)), 2) - Math.pow(orig.sub(c).distance(), 2) + Math.pow(this.radius, 2));
if (discriminant < 0) {
// no intersection
return null;
}
else {
var toi = 0;
if (discriminant === 0) {
toi = -dir.dot(orig.sub(c));
if (toi > 0 && toi < max) {
return ray.getPoint(toi);
}
return null;
}
else {
var toi1 = -dir.dot(orig.sub(c)) + discriminant;
var toi2 = -dir.dot(orig.sub(c)) - discriminant;
var positiveToi = [];
if (toi1 >= 0) {
positiveToi.push(toi1);
}
if (toi2 >= 0) {
positiveToi.push(toi2);
}
var mintoi = Math.min.apply(Math, positiveToi);
if (mintoi <= max) {
return ray.getPoint(mintoi);
}
return null;
}
}
};
Circle.prototype.getClosestLineBetween = function (shape) {
if (shape instanceof Circle) {
return _ClosestLineJumpTable__WEBPACK_IMPORTED_MODULE_7__["ClosestLineJumpTable"].CircleCircleClosestLine(this, shape);
}
else if (shape instanceof _ConvexPolygon__WEBPACK_IMPORTED_MODULE_2__["ConvexPolygon"]) {
return _ClosestLineJumpTable__WEBPACK_IMPORTED_MODULE_7__["ClosestLineJumpTable"].PolygonCircleClosestLine(shape, this).flip();
}
else if (shape instanceof _Edge__WEBPACK_IMPORTED_MODULE_3__["Edge"]) {
return _ClosestLineJumpTable__WEBPACK_IMPORTED_MODULE_7__["ClosestLineJumpTable"].CircleEdgeClosestLine(this, shape).flip();
}
else {
throw new Error("Polygon could not collide with unknown CollisionShape " + typeof shape);
}
};
/**
* @inheritdoc
*/
Circle.prototype.collide = function (shape) {
if (shape instanceof Circle) {
return _CollisionJumpTable__WEBPACK_IMPORTED_MODULE_1__["CollisionJumpTable"].CollideCircleCircle(this, shape);
}
else if (shape instanceof _ConvexPolygon__WEBPACK_IMPORTED_MODULE_2__["ConvexPolygon"]) {
return _CollisionJumpTable__WEBPACK_IMPORTED_MODULE_1__["CollisionJumpTable"].CollideCirclePolygon(this, shape);
}
else if (shape instanceof _Edge__WEBPACK_IMPORTED_MODULE_3__["Edge"]) {
return _CollisionJumpTable__WEBPACK_IMPORTED_MODULE_1__["CollisionJumpTable"].CollideCircleEdge(this, shape);
}
else {
throw new Error("Circle could not collide with unknown CollisionShape " + typeof shape);
}
};
/**
* Find the point on the shape furthest in the direction specified
*/
Circle.prototype.getFurthestPoint = function (direction) {
return this.center.add(direction.normalize().scale(this.radius));
};
Object.defineProperty(Circle.prototype, "bounds", {
/**
* Get the axis aligned bounding box for the circle shape in world coordinates
*/
get: function () {
var bodyPos = _Algebra__WEBPACK_IMPORTED_MODULE_4__["Vector"].Zero;
if (this.collider && this.collider.body) {
bodyPos = this.collider.body.pos;
}
return new _BoundingBox__WEBPACK_IMPORTED_MODULE_0__["BoundingBox"](this.offset.x + bodyPos.x - this.radius, this.offset.y + bodyPos.y - this.radius, this.offset.x + bodyPos.x + this.radius, this.offset.y + bodyPos.y + this.radius);
},
enumerable: false,
configurable: true
});
Object.defineProperty(Circle.prototype, "localBounds", {
/**
* Get the axis aligned bounding box for the circle shape in local coordinates
*/
get: function () {
return new _BoundingBox__WEBPACK_IMPORTED_MODULE_0__["BoundingBox"](this.offset.x - this.radius, this.offset.y - this.radius, this.offset.x + this.radius, this.offset.y + this.radius);
},
enumerable: false,
configurable: true
});
Object.defineProperty(Circle.prototype, "axes", {
/**
* Get axis not implemented on circles, since there are infinite axis in a circle
*/
get: function () {
return null;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Circle.prototype, "inertia", {
/**
* Returns the moment of inertia of a circle given it's mass
* https://en.wikipedia.org/wiki/List_of_moments_of_inertia
*/
get: function () {
var mass = this.collider ? this.collider.mass : _Physics__WEBPACK_IMPORTED_MODULE_5__["Physics"].defaultMass;
return (mass * this.radius * this.radius) / 2;
},
enumerable: false,
configurable: true
});
/**
* Tests the separating axis theorem for circles against polygons
*/
Circle.prototype.testSeparatingAxisTheorem = function (polygon) {
var axes = polygon.axes;
var pc = polygon.center;
// Special SAT with circles
var closestPointOnPoly = polygon.getFurthestPoint(this.offset.sub(pc));
axes.push(this.offset.sub(closestPointOnPoly).normalize());
var minOverlap = Number.MAX_VALUE;
var minAxis = null;
var minIndex = -1;
for (var i = 0; i < axes.length; i++) {
var proj1 = polygon.project(axes[i]);
var proj2 = this.project(axes[i]);
var overlap = proj1.getOverlap(proj2);
if (overlap <= 0) {
return null;
}
else {
if (overlap < minOverlap) {
minOverlap = overlap;
minAxis = axes[i];
minIndex = i;
}
}
}
if (minIndex < 0) {
return null;
}
return minAxis.normalize().scale(minOverlap);
};
/* istanbul ignore next */
Circle.prototype.recalc = function () {
// circles don't cache
};
/**
* Project the circle along a specified axis
*/
Circle.prototype.project = function (axis) {
var scalars = [];
var point = this.center;
var dotProduct = point.dot(axis);
scalars.push(dotProduct);
scalars.push(dotProduct + this.radius);
scalars.push(dotProduct - this.radius);
return new _Algebra__WEBPACK_IMPORTED_MODULE_4__["Projection"](Math.min.apply(Math, scalars), Math.max.apply(Math, scalars));
};
Circle.prototype.draw = function (ctx, color, pos) {
if (color === void 0) { color = _Drawing_Color__WEBPACK_IMPORTED_MODULE_6__["Color"].Green; }
if (pos === void 0) { pos = _Algebra__WEBPACK_IMPORTED_MODULE_4__["Vector"].Zero; }
var newPos = pos.add(this.offset);
ctx.beginPath();
ctx.fillStyle = color.toString();
ctx.arc(newPos.x, newPos.y, this.radius, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
};
/* istanbul ignore next */
Circle.prototype.debugDraw = function (ctx, color) {
if (color === void 0) { color = _Drawing_Color__WEBPACK_IMPORTED_MODULE_6__["Color"].Green; }
var body = this.collider.body;
var pos = body ? body.pos.add(this.offset) : this.offset;
var rotation = body ? body.rotation : 0;
ctx.beginPath();
ctx.strokeStyle = color.toString();
ctx.arc(pos.x, pos.y, this.radius, 0, Math.PI * 2);
ctx.closePath();
ctx.stroke();
ctx.beginPath();
ctx.moveTo(pos.x, pos.y);
ctx.lineTo(Math.cos(rotation) * this.radius + pos.x, Math.sin(rotation) * this.radius + pos.y);
ctx.closePath();
ctx.stroke();
};
return Circle;
}());
/***/ }),
/***/ "./Collision/ClosestLineJumpTable.ts":
/*!*******************************************!*\
!*** ./Collision/ClosestLineJumpTable.ts ***!
\*******************************************/
/*! exports provided: ClosestLine, ClosestLineJumpTable */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ClosestLine", function() { return ClosestLine; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ClosestLineJumpTable", function() { return ClosestLineJumpTable; });
/* harmony import */ var _Algebra__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Algebra */ "./Algebra.ts");
/**
* Finds the closes line between 2 line segments, were the magnitude of u, v are the lengths of each segment
* L1 = P(s) = p0 + s * u, where s is time and p0 is the start of the line
* L2 = Q(t) = q0 + t * v, where t is time and q0 is the start of the line
* @param p0 Point where L1 begins
* @param u Direction and length of L1
* @param q0 Point were L2 begins
* @param v Direction and length of L2
*/
function ClosestLine(p0, u, q0, v) {
// Distance between 2 lines http://geomalgorithms.com/a07-_distance.html
// w(s, t) = P(s) - Q(t)
// The w(s, t) that has the minimum distance we will say is w(sClosest, tClosest) = wClosest
//
// wClosest is the vector that is uniquely perpendicular to the 2 line directions u & v.
// wClosest = w0 + sClosest * u - tClosest * v, where w0 is p0 - q0
//
// The closest point between 2 lines then satisfies this pair of equations
// 1: u * wClosest = 0
// 2: v * wClosest = 0
//
// Substituting wClosest into the equations we get
//
// 1: (u * u) * sClosest - (u * v) tClosest = -u * w0
// 2: (v * u) * sClosest - (v * v) tClosest = -v * w0
// simplify w0
var w0 = p0.sub(q0);
// simplify (u * u);
var a = u.dot(u);
// simplify (u * v);
var b = u.dot(v);
// simplify (v * v)
var c = v.dot(v);
// simplify (u * w0)
var d = u.dot(w0);
// simplify (v * w0)
var e = v.dot(w0);
// denominator ac - b^2
var denom = a * c - b * b;
var sDenom = denom;
var tDenom = denom;
// if denom is 0 they are parallel, use any point from either as the start in this case p0
if (denom === 0 || denom <= 0.01) {
var tClosestParallel = d / b;
return new _Algebra__WEBPACK_IMPORTED_MODULE_0__["Line"](p0, q0.add(v.scale(tClosestParallel)));
}
// Solve for sClosest for infinite line
var sClosest = b * e - c * d; // / denom;
// Solve for tClosest for infinite line
var tClosest = a * e - b * d; // / denom;
// Solve for segments candidate edges, if sClosest and tClosest are outside their segments
if (sClosest < 0) {
sClosest = 0;
tClosest = e;
tDenom = c;
}
else if (sClosest > sDenom) {
sClosest = sDenom;
tClosest = e + b;
tDenom = c;
}
if (tClosest < 0) {
tClosest = 0;
if (-d < 0) {
sClosest = 0;
}
else if (-d > a) {
sClosest = sDenom;
}
else {
sClosest = -d;
sDenom = a;
}
}
else if (tClosest > tDenom) {
tClosest = tDenom;
if (-d + b < 0) {
sClosest = 0;
}
else if (-d + b > a) {
sClosest = sDenom;
}
else {
sClosest = -d + b;
sDenom = a;
}
}
sClosest = Math.abs(sClosest) < 0.001 ? 0 : sClosest / sDenom;
tClosest = Math.abs(tClosest) < 0.001 ? 0 : tClosest / tDenom;
return new _Algebra__WEBPACK_IMPORTED_MODULE_0__["Line"](p0.add(u.scale(sClosest)), q0.add(v.scale(tClosest)));
}
var ClosestLineJumpTable = {
PolygonPolygonClosestLine: function (polygonA, polygonB) {
// Find the 2 closest faces on each polygon
var otherWorldPos = polygonB.worldPos;
var otherDirection = otherWorldPos.sub(polygonA.worldPos);
var thisDirection = otherDirection.negate();
var rayTowardsOther = new _Algebra__WEBPACK_IMPORTED_MODULE_0__["Ray"](polygonA.worldPos, otherDirection);
var rayTowardsThis = new _Algebra__WEBPACK_IMPORTED_MODULE_0__["Ray"](otherWorldPos, thisDirection);
var thisPoint = polygonA.rayCast(rayTowardsOther).add(rayTowardsOther.dir.scale(0.1));
var otherPoint = polygonB.rayCast(rayTowardsThis).add(rayTowardsThis.dir.scale(0.1));
var thisFace = polygonA.getClosestFace(thisPoint);
var otherFace = polygonB.getClosestFace(otherPoint);
// L1 = P(s) = p0 + s * u, where s is time and p0 is the start of the line
var p0 = thisFace.face.begin;
var u = thisFace.face.getEdge();
// L2 = Q(t) = q0 + t * v, where t is time and q0 is the start of the line
var q0 = otherFace.face.begin;
var v = otherFace.face.getEdge();
return ClosestLine(p0, u, q0, v);
},
PolygonEdgeClosestLine: function (polygon, edge) {
// Find the 2 closest faces on each polygon
var otherWorldPos = edge.worldPos;
var otherDirection = otherWorldPos.sub(polygon.worldPos);
var rayTowardsOther = new _Algebra__WEBPACK_IMPORTED_MODULE_0__["Ray"](polygon.worldPos, otherDirection);
var thisPoint = polygon.rayCast(rayTowardsOther).add(rayTowardsOther.dir.scale(0.1));
var thisFace = polygon.getClosestFace(thisPoint);
// L1 = P(s) = p0 + s * u, where s is time and p0 is the start of the line
var p0 = thisFace.face.begin;
var u = thisFace.face.getEdge();
// L2 = Q(t) = q0 + t * v, where t is time and q0 is the start of the line
var edgeLine = edge.asLine();
var edgeStart = edgeLine.begin;
var edgeVector = edgeLine.getEdge();
var q0 = edgeStart;
var v = edgeVector;
return ClosestLine(p0, u, q0, v);
},
PolygonCircleClosestLine: function (polygon, circle) {
// https://math.stackexchange.com/questions/1919177/how-to-find-point-on-line-closest-to-sphere
// Find the 2 closest faces on each polygon
var otherWorldPos = circle.worldPos;
var otherDirection = otherWorldPos.sub(polygon.worldPos);
var rayTowardsOther = new _Algebra__WEBPACK_IMPORTED_MODULE_0__["Ray"](polygon.worldPos, otherDirection.normalize());
var thisPoint = polygon.rayCast(rayTowardsOther).add(rayTowardsOther.dir.scale(0.1));
var thisFace = polygon.getClosestFace(thisPoint);
// L1 = P(s) = p0 + s * u, where s is time and p0 is the start of the line
var p0 = thisFace.face.begin;
var u = thisFace.face.getEdge();
// Time of minimum distance
var t = (u.x * (otherWorldPos.x - p0.x) + u.y * (otherWorldPos.y - p0.y)) / (u.x * u.x + u.y * u.y);
// If time of minimum is past the edge clamp
if (t > 1) {
t = 1;
}
else if (t < 0) {
t = 0;
}
// Minimum distance
var d = Math.sqrt(Math.pow(p0.x + u.x * t - otherWorldPos.x, 2) + Math.pow(p0.y + u.y * t - otherWorldPos.y, 2)) - circle.radius;
var circlex = ((p0.x + u.x * t - otherWorldPos.x) * circle.radius) / (circle.radius + d);
var circley = ((p0.y + u.y * t - otherWorldPos.y) * circle.radius) / (circle.radius + d);
return new _Algebra__WEBPACK_IMPORTED_MODULE_0__["Line"](u.scale(t).add(p0), new _Algebra__WEBPACK_IMPORTED_MODULE_0__["Vector"](otherWorldPos.x + circlex, otherWorldPos.y + circley));
},
CircleCircleClosestLine: function (circleA, circleB) {
// Find the 2 closest faces on each polygon
var otherWorldPos = circleB.worldPos;
var otherDirection = otherWorldPos.sub(circleA.worldPos);
var thisWorldPos = circleA.worldPos;
var thisDirection = thisWorldPos.sub(circleB.worldPos);
var rayTowardsOther = new _Algebra__WEBPACK_IMPORTED_MODULE_0__["Ray"](circleA.worldPos, otherDirection);
var rayTowardsThis = new _Algebra__WEBPACK_IMPORTED_MODULE_0__["Ray"](circleB.worldPos, thisDirection);
var thisPoint = circleA.rayCast(rayTowardsOther);
var otherPoint = circleB.rayCast(rayTowardsThis);
return new _Algebra__WEBPACK_IMPORTED_MODULE_0__["Line"](thisPoint, otherPoint);
},
CircleEdgeClosestLine: function (circle, edge) {
// https://math.stackexchange.com/questions/1919177/how-to-find-point-on-line-closest-to-sphere
var circleWorlPos = circle.worldPos;
// L1 = P(s) = p0 + s * u, where s is time and p0 is the start of the line
var edgeLine = edge.asLine();
var edgeStart = edgeLine.begin;
var edgeVector = edgeLine.getEdge();
var p0 = edgeStart;
var u = edgeVector;
// Time of minimum distance
var t = (u.x * (circleWorlPos.x - p0.x) + u.y * (circleWorlPos.y - p0.y)) / (u.x * u.x + u.y * u.y);
// If time of minimum is past the edge clamp to edge
if (t > 1) {
t = 1;
}
else if (t < 0) {
t = 0;
}
// Minimum distance
var d = Math.sqrt(Math.pow(p0.x + u.x * t - circleWorlPos.x, 2) + Math.pow(p0.y + u.y * t - circleWorlPos.y, 2)) - circle.radius;
var circlex = ((p0.x + u.x * t - circleWorlPos.x) * circle.radius) / (circle.radius + d);
var circley = ((p0.y + u.y * t - circleWorlPos.y) * circle.radius) / (circle.radius + d);
return new _Algebra__WEBPACK_IMPORTED_MODULE_0__["Line"](u.scale(t).add(p0), new _Algebra__WEBPACK_IMPORTED_MODULE_0__["Vector"](circleWorlPos.x + circlex, circleWorlPos.y + circley));
},
EdgeEdgeClosestLine: function (edgeA, edgeB) {
// L1 = P(s) = p0 + s * u, where s is time and p0 is the start of the line
var edgeLineA = edgeA.asLine();
var edgeStartA = edgeLineA.begin;
var edgeVectorA = edgeLineA.getEdge();
var p0 = edgeStartA;
var u = edgeVectorA;
// L2 = Q(t) = q0 + t * v, where t is time and q0 is the start of the line
var edgeLineB = edgeB.asLine();
var edgeStartB = edgeLineB.begin;
var edgeVectorB = edgeLineB.getEdge();
var q0 = edgeStartB;
var v = edgeVectorB;
return ClosestLine(p0, u, q0, v);
}
};
/***/ }),
/***/ "./Collision/Collider.ts":
/*!*******************************!*\
!*** ./Collision/Collider.ts ***!
\*******************************/
/*! exports provided: isCollider, Collider */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isCollider", function() { return isCollider; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Collider", function() { return Collider; });
/* harmony import */ var _Drawing_Color__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Drawing/Color */ "./Drawing/Color.ts");
/* harmony import */ var _Util_DrawUtil__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Util/DrawUtil */ "./Util/DrawUtil.ts");
/* harmony import */ var _Algebra__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Algebra */ "./Algebra.ts");
/* harmony import */ var _Physics__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Physics */ "./Physics.ts");
/* harmony import */ var _BoundingBox__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./BoundingBox */ "./Collision/BoundingBox.ts");
/* harmony import */ var _CollisionType__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./CollisionType */ "./Collision/CollisionType.ts");
/* harmony import */ var _CollisionGroup__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./CollisionGroup */ "./Collision/CollisionGroup.ts");
/* harmony import */ var _EventDispatcher__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../EventDispatcher */ "./EventDispatcher.ts");
/* harmony import */ var _Pair__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Pair */ "./Collision/Pair.ts");
/**
* Type guard function to determine whether something is a Collider
*/
function isCollider(x) {
return x instanceof Collider;
}
/**
* Collider describes material properties like shape,
* bounds, friction of the physics object. Only **one** collider can be associated with a body at a time
*/
var Collider = /** @class */ (function () {
function Collider(_a) {
var body = _a.body, type = _a.type, group = _a.group, shape = _a.shape, offset = _a.offset, _b = _a.useShapeInertia, useShapeInertia = _b === void 0 ? true : _b;
this._events = new _EventDispatcher__WEBPACK_IMPORTED_MODULE_7__["EventDispatcher"](this);
/**
* Gets or sets the current collision type of this collider. By
* default it is ([[CollisionType.PreventCollision]]).
*/
this.type = _CollisionType__WEBPACK_IMPORTED_MODULE_5__["CollisionType"].PreventCollision;
/**
* Gets or sets the current [[CollisionGroup|collision group]] for the collider, colliders with like collision groups do not collide.
* By default, the collider will collide with [[CollisionGroup|all groups]].
*/
this.group = _CollisionGroup__WEBPACK_IMPORTED_MODULE_6__["CollisionGroup"].All;
/**
* The current mass of the actor, mass can be thought of as the resistance to acceleration.
*/
this.mass = 1.0;
/**
* The current moment of inertia, moment of inertia can be thought of as the resistance to rotation.
*/
this.inertia = 1000;
/**
* The coefficient of friction on this actor
*/
this.friction = 0.99;
/**
* The also known as coefficient of restitution of this actor, represents the amount of energy preserved after collision or the
* bounciness. If 1, it is 100% bouncy, 0 it completely absorbs.
*/
this.bounciness = 0.2;
// If shape is not supplied see if the body has an existing collider with a shape
if (body && body.collider && !shape) {
this._shape = body.collider.shape;
}
else {
this._shape = shape;
this.body = body;
}
this.useShapeInertia = useShapeInertia;
this._shape.collider = this;
this.type = type || this.type;
this.group = group || this.group;
this.offset = offset || _Algebra__WEBPACK_IMPORTED_MODULE_2__["Vector"].Zero;
}
/**
* Returns a clone of the current collider, not associated with any body
*/
Collider.prototype.clone = function () {
return new Collider({
body: null,
type: this.type,
shape: this._shape.clone(),
group: this.group,
offset: this.offset
});
};
Object.defineProperty(Collider.prototype, "id", {
/**
* Get the unique id of the collider
*/
get: function () {
return this.body ? this.body.id : -1;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Collider.prototype, "shape", {
/*
* Get the shape of the collider as a [[CollisionShape]]
*/
get: function () {
return this._shape;
},
/**
* Set the shape of the collider as a [[CollisionShape]], if useShapeInertia is set the collider will use inertia from the shape.
*/
set: function (shape) {
this._shape = shape;
this._shape.collider = this;
if (this.useShapeInertia) {
this.inertia = isNaN(this._shape.inertia) ? this.inertia : this._shape.inertia;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(Collider.prototype, "center", {
/**
* The center of the collider in world space
*/
get: function () {
return this.bounds.center;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Collider.prototype, "active", {
/**
* Is this collider active, if false it wont collide
*/
get: function () {
return this.body.active;
},
enumerable: false,
configurable: true
});
/**
* Collide 2 colliders and product a collision contact if there is a collision, null if none
*
* Collision vector is in the direction of the other collider. Away from this collider, this -> other.
* @param other
*/
Collider.prototype.collide = function (other) {
return this.shape.collide(other.shape);
};
/**
* Find the closest line between 2 colliders
*
* Line is in the direction of the other collider. Away from this collider, this -> other.
* @param other Other collider
*/
Collider.prototype.getClosestLineBetween = function (other) {
return this.shape.getClosestLineBetween(other.shape);
};
Object.defineProperty(Collider.prototype, "offset", {
/**
* Gets the current pixel offset of the collider
*/
get: function () {
return this.shape.offset.clone();
},
/**
* Sets the pixel offset of the collider
*/
set: function (offset) {
this.shape.offset = offset.clone();
},
enumerable: false,
configurable: true
});
/**
* Returns a boolean indicating whether this body collided with
* or was in stationary contact with
* the body of the other [[Collider]]
*/
Collider.prototype.touching = function (other) {
var pair = new _Pair__WEBPACK_IMPORTED_MODULE_8__["Pair"](this, other);
pair.collide();
if (pair.collision) {
return true;
}
return false;
};
Object.defineProperty(Collider.prototype, "bounds", {
/**
* Returns the collider's [[BoundingBox]] calculated for this instant in world space.
* If there is no shape, a point bounding box is returned
*/
get: function () {
if (this.shape) {
return this.shape.bounds;
}
if (this.body) {
return new _BoundingBox__WEBPACK_IMPORTED_MODULE_4__["BoundingBox"]().translate(this.body.pos);
}
return new _BoundingBox__WEBPACK_IMPORTED_MODULE_4__["BoundingBox"]();
},
enumerable: false,
configurable: true
});
Object.defineProperty(Collider.prototype, "localBounds", {
/**
* Returns the collider's [[BoundingBox]] relative to the body's position.
* If there is no shape, a point bounding box is returned
*/
get: function () {
if (this.shape) {
return this.shape.localBounds;
}
return new _BoundingBox__WEBPACK_IMPORTED_MODULE_4__["BoundingBox"]();
},
enumerable: false,
configurable: true
});
/**
* Updates the collision shapes geometry and internal caches if needed
*/
Collider.prototype.update = function () {
if (this.shape) {
this.shape.recalc();
}
};
Collider.prototype.emit = function (eventName, event) {
this._events.emit(eventName, event);
};
Collider.prototype.on = function (eventName, handler) {
this._events.on(eventName, handler);
};
Collider.prototype.off = function (eventName, handler) {
this._events.off(eventName, handler);
};
Collider.prototype.once = function (eventName, handler) {
this._events.once(eventName, handler);
};
Collider.prototype.clear = function () {
this._events.clear();
};
/* istanbul ignore next */
Collider.prototype.debugDraw = function (ctx) {
// Draw motion vectors
if (_Physics__WEBPACK_IMPORTED_MODULE_3__["Physics"].showMotionVectors) {
_Util_DrawUtil__WEBPACK_IMPORTED_MODULE_1__["vector"](ctx, _Drawing_Color__WEBPACK_IMPORTED_MODULE_0__["Color"].Yellow, this.body.pos, this.body.acc.add(_Physics__WEBPACK_IMPORTED_MODULE_3__["Physics"].acc));
_Util_DrawUtil__WEBPACK_IMPORTED_MODULE_1__["vector"](ctx, _Drawing_Color__WEBPACK_IMPORTED_MODULE_0__["Color"].Red, this.body.pos, this.body.vel);
_Util_DrawUtil__WEBPACK_IMPORTED_MODULE_1__["point"](ctx, _Drawing_Color__WEBPACK_IMPORTED_MODULE_0__["Color"].Red, this.body.pos);
}
if (_Physics__WEBPACK_IMPORTED_MODULE_3__["Physics"].showBounds) {
this.bounds.debugDraw(ctx, _Drawing_Color__WEBPACK_IMPORTED_MODULE_0__["Color"].Yellow);
}
if (_Physics__WEBPACK_IMPORTED_MODULE_3__["Physics"].showArea) {
this.shape.debugDraw(ctx, _Drawing_Color__WEBPACK_IMPORTED_MODULE_0__["Color"].Green);
}
};
return Collider;
}());
/***/ }),
/***/ "./Collision/CollisionContact.ts":
/*!***************************************!*\
!*** ./Collision/CollisionContact.ts ***!
\***************************************/
/*! exports provided: CollisionContact */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CollisionContact", function() { return CollisionContact; });
/* harmony import */ var _Algebra__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Algebra */ "./Algebra.ts");
/* harmony import */ var _Physics__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Physics */ "./Physics.ts");
/* harmony import */ var _Events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Events */ "./Events.ts");
/* harmony import */ var _Util_Util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Util/Util */ "./Util/Util.ts");
/* harmony import */ var _CollisionType__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./CollisionType */ "./Collision/CollisionType.ts");
/**
* Collision contacts are used internally by Excalibur to resolve collision between colliders. This
* Pair prevents collisions from being evaluated more than one time
*/
var CollisionContact = /** @class */ (function () {
function CollisionContact(colliderA, colliderB, mtv, point, normal) {
this.colliderA = colliderA;
this.colliderB = colliderB;
this.mtv = mtv;
this.point = point;
this.normal = normal;
}
CollisionContact.prototype.resolve = function (strategy) {
if (strategy === _Physics__WEBPACK_IMPORTED_MODULE_1__["CollisionResolutionStrategy"].RigidBody) {
this._resolveRigidBodyCollision();
}
else if (strategy === _Physics__WEBPACK_IMPORTED_MODULE_1__["CollisionResolutionStrategy"].Box) {
this._resolveBoxCollision();
}
else {
throw new Error('Unknown collision resolution strategy');
}
};
CollisionContact.prototype._applyBoxImpulse = function (colliderA, colliderB, mtv) {
if (colliderA.type === _CollisionType__WEBPACK_IMPORTED_MODULE_4__["CollisionType"].Active && colliderB.type !== _CollisionType__WEBPACK_IMPORTED_MODULE_4__["CollisionType"].Passive) {
// Resolve overlaps
if (colliderA.type === _CollisionType__WEBPACK_IMPORTED_MODULE_4__["CollisionType"].Active && colliderB.type === _CollisionType__WEBPACK_IMPORTED_MODULE_4__["CollisionType"].Active) {
// split overlaps if both are Active
mtv = mtv.scale(0.5);
}
// Apply mtv
colliderA.body.pos.y += mtv.y;
colliderA.body.pos.x += mtv.x;
var mtvDir = mtv.normalize();
// only adjust if velocity is opposite
if (mtvDir.dot(colliderA.body.vel) < 0) {
// Cancel out velocity in direction of mtv
var velAdj = mtvDir.scale(mtvDir.dot(colliderA.body.vel.negate()));
colliderA.body.vel = colliderA.body.vel.add(velAdj);
}
colliderA.emit('postcollision', new _Events__WEBPACK_IMPORTED_MODULE_2__["PostCollisionEvent"](colliderA, colliderB, _Util_Util__WEBPACK_IMPORTED_MODULE_3__["getSideFromDirection"](mtv), mtv));
}
};
CollisionContact.prototype._resolveBoxCollision = function () {
var side = _Util_Util__WEBPACK_IMPORTED_MODULE_3__["getSideFromDirection"](this.mtv);
var mtv = this.mtv.negate();
// Publish collision events on both participants
this.colliderA.emit('precollision', new _Events__WEBPACK_IMPORTED_MODULE_2__["PreCollisionEvent"](this.colliderA, this.colliderB, side, mtv));
this.colliderB.emit('precollision', new _Events__WEBPACK_IMPORTED_MODULE_2__["PreCollisionEvent"](this.colliderB, this.colliderA, _Util_Util__WEBPACK_IMPORTED_MODULE_3__["getOppositeSide"](side), mtv.negate()));
this._applyBoxImpulse(this.colliderA, this.colliderB, mtv);
this._applyBoxImpulse(this.colliderB, this.colliderA, mtv.negate());
};
CollisionContact.prototype._resolveRigidBodyCollision = function () {
// perform collision on bounding areas
var bodyA = this.colliderA.body;
var bodyB = this.colliderB.body;
var mtv = this.mtv; // normal pointing away from colliderA
var normal = this.normal; // normal pointing away from colliderA
if (bodyA === bodyB) {
// sanity check for existing pairs
return;
}
// Publish collision events on both participants
var side = _Util_Util__WEBPACK_IMPORTED_MODULE_3__["getSideFromDirection"](this.mtv);
this.colliderA.emit('precollision', new _Events__WEBPACK_IMPORTED_MODULE_2__["PreCollisionEvent"](this.colliderA, this.colliderB, side, this.mtv));
this.colliderB.emit('precollision', new _Events__WEBPACK_IMPORTED_MODULE_2__["PreCollisionEvent"](this.colliderB, this.colliderA, _Util_Util__WEBPACK_IMPORTED_MODULE_3__["getOppositeSide"](side), this.mtv.negate()));
// If any of the participants are passive then short circuit
if (this.colliderA.type === _CollisionType__WEBPACK_IMPORTED_MODULE_4__["CollisionType"].Passive || this.colliderB.type === _CollisionType__WEBPACK_IMPORTED_MODULE_4__["CollisionType"].Passive) {
return;
}
var invMassA = this.colliderA.type === _CollisionType__WEBPACK_IMPORTED_MODULE_4__["CollisionType"].Fixed ? 0 : 1 / this.colliderA.mass;
var invMassB = this.colliderB.type === _CollisionType__WEBPACK_IMPORTED_MODULE_4__["CollisionType"].Fixed ? 0 : 1 / this.colliderB.mass;
var invMoiA = this.colliderA.type === _CollisionType__WEBPACK_IMPORTED_MODULE_4__["CollisionType"].Fixed ? 0 : 1 / this.colliderA.inertia;
var invMoiB = this.colliderB.type === _CollisionType__WEBPACK_IMPORTED_MODULE_4__["CollisionType"].Fixed ? 0 : 1 / this.colliderB.inertia;
// average restitution more realistic
var coefRestitution = Math.min(this.colliderA.bounciness, this.colliderB.bounciness);
var coefFriction = Math.min(this.colliderA.friction, this.colliderB.friction);
normal = normal.normalize();
var tangent = normal.normal().normalize();
var ra = this.point.sub(this.colliderA.center); // point relative to colliderA position
var rb = this.point.sub(this.colliderB.center); /// point relative to colliderB
// Relative velocity in linear terms
// Angular to linear velocity formula -> omega = v/r
var rv = bodyB.vel.add(rb.cross(-bodyB.rx)).sub(bodyA.vel.sub(ra.cross(bodyA.rx)));
var rvNormal = rv.dot(normal);
var rvTangent = rv.dot(tangent);
var raTangent = ra.dot(tangent);
var raNormal = ra.dot(normal);
var rbTangent = rb.dot(tangent);
var rbNormal = rb.dot(normal);
// If objects are moving away ignore
if (rvNormal > 0) {
return;
}
// Collision impulse formula from Chris Hecker
// https://en.wikipedia.org/wiki/Collision_response
var impulse = -((1 + coefRestitution) * rvNormal) / (invMassA + invMassB + invMoiA * raTangent * raTangent + invMoiB * rbTangent * rbTangent);
if (this.colliderA.type === _CollisionType__WEBPACK_IMPORTED_MODULE_4__["CollisionType"].Fixed) {
bodyB.vel = bodyB.vel.add(normal.scale(impulse * invMassB));
if (_Physics__WEBPACK_IMPORTED_MODULE_1__["Physics"].allowRigidBodyRotation) {
bodyB.rx -= impulse * invMoiB * -rb.cross(normal);
}
bodyB.addMtv(mtv);
}
else if (this.colliderB.type === _CollisionType__WEBPACK_IMPORTED_MODULE_4__["CollisionType"].Fixed) {
bodyA.vel = bodyA.vel.sub(normal.scale(impulse * invMassA));
if (_Physics__WEBPACK_IMPORTED_MODULE_1__["Physics"].allowRigidBodyRotation) {
bodyA.rx += impulse * invMoiA * -ra.cross(normal);
}
bodyA.addMtv(mtv.negate());
}
else {
bodyB.vel = bodyB.vel.add(normal.scale(impulse * invMassB));
bodyA.vel = bodyA.vel.sub(normal.scale(impulse * invMassA));
if (_Physics__WEBPACK_IMPORTED_MODULE_1__["Physics"].allowRigidBodyRotation) {
bodyB.rx -= impulse * invMoiB * -rb.cross(normal);
bodyA.rx += impulse * invMoiA * -ra.cross(normal);
}
// Split the mtv in half for the two bodies, potentially we could do something smarter here
bodyB.addMtv(mtv.scale(0.5));
bodyA.addMtv(mtv.scale(-0.5));
}
// Friction portion of impulse
if (coefFriction && rvTangent) {
// Columb model of friction, formula for impulse due to friction from
// https://en.wikipedia.org/wiki/Collision_response
// tangent force exerted by body on another in contact
var t = rv.sub(normal.scale(rv.dot(normal))).normalize();
// impulse in the direction of tangent force
var jt = rv.dot(t) / (invMassA + invMassB + raNormal * raNormal * invMoiA + rbNormal * rbNormal * invMoiB);
var frictionImpulse = new _Algebra__WEBPACK_IMPORTED_MODULE_0__["Vector"](0, 0);
if (Math.abs(jt) <= impulse * coefFriction) {
frictionImpulse = t.scale(jt).negate();
}
else {
frictionImpulse = t.scale(-impulse * coefFriction);
}
if (this.colliderA.type === _CollisionType__WEBPACK_IMPORTED_MODULE_4__["CollisionType"].Fixed) {
// apply frictional impulse
bodyB.vel = bodyB.vel.add(frictionImpulse.scale(invMassB));
if (_Physics__WEBPACK_IMPORTED_MODULE_1__["Physics"].allowRigidBodyRotation) {
bodyB.rx += frictionImpulse.dot(t) * invMoiB * rb.cross(t);
}
}
else if (this.colliderB.type === _CollisionType__WEBPACK_IMPORTED_MODULE_4__["CollisionType"].Fixed) {
// apply frictional impulse
bodyA.vel = bodyA.vel.sub(frictionImpulse.scale(invMassA));
if (_Physics__WEBPACK_IMPORTED_MODULE_1__["Physics"].allowRigidBodyRotation) {
bodyA.rx -= frictionImpulse.dot(t) * invMoiA * ra.cross(t);
}
}
else {
// apply frictional impulse
bodyB.vel = bodyB.vel.add(frictionImpulse.scale(invMassB));
bodyA.vel = bodyA.vel.sub(frictionImpulse.scale(invMassA));
// apply frictional impulse
if (_Physics__WEBPACK_IMPORTED_MODULE_1__["Physics"].allowRigidBodyRotation) {
bodyB.rx += frictionImpulse.dot(t) * invMoiB * rb.cross(t);
bodyA.rx -= frictionImpulse.dot(t) * invMoiA * ra.cross(t);
}
}
}
this.colliderA.emit('postcollision', new _Events__WEBPACK_IMPORTED_MODULE_2__["PostCollisionEvent"](this.colliderA, this.colliderB, side, this.mtv));
this.colliderB.emit('postcollision', new _Events__WEBPACK_IMPORTED_MODULE_2__["PostCollisionEvent"](this.colliderB, this.colliderA, _Util_Util__WEBPACK_IMPORTED_MODULE_3__["getOppositeSide"](side), this.mtv.negate()));
};
return CollisionContact;
}());
/***/ }),
/***/ "./Collision/CollisionGroup.ts":
/*!*************************************!*\
!*** ./Collision/CollisionGroup.ts ***!
\*************************************/
/*! exports provided: CollisionGroup */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CollisionGroup", function() { return CollisionGroup; });
/**
* CollisionGroups indicate like members that do not collide with each other. Use [[CollisionGroupManager]] to create [[CollisionGroup]]s
*
* For example:
*
* Players have collision group "player"
*
* ![Player Collision Group](/assets/images/docs/CollisionGroupsPlayer.png)
*
* Enemies have collision group "enemy"
*
* ![Enemy Collision Group](/assets/images/docs/CollisionGroupsEnemy.png)
*
* Blocks have collision group "ground"
*
* ![Ground collision group](/assets/images/docs/CollisionGroupsGround.png)
*
* Players don't collide with each other, but enemies and blocks. Likewise, enemies don't collide with each other but collide
* with players and blocks.
*
* This is done with bitmasking, see the following pseudo-code
*
* PlayerGroup = `0b001`
* PlayerGroupMask = `0b110`
*
* EnemyGroup = `0b010`
* EnemyGroupMask = `0b101`
*
* BlockGroup = `0b100`
* BlockGroupMask = `0b011`
*
* Should Players collide? No because the bitwise mask evaluates to 0
* `(player1.group & player2.mask) === 0`
* `(0b001 & 0b110) === 0`
*
* Should Players and Enemies collide? Yes because the bitwise mask is non-zero
* `(player1.group & enemy1.mask) === 1`
* `(0b001 & 0b101) === 1`
*
* Should Players and Blocks collide? Yes because the bitwise mask is non-zero
* `(player1.group & blocks1.mask) === 1`
* `(0b001 & 0b011) === 1`
*/
var CollisionGroup = /** @class */ (function () {
/**
* **STOP!!** It is preferred that [[CollisionGroupManager.create]] is used to create collision groups
* unless you know how to construct the proper bitmasks. See https://github.com/excaliburjs/Excalibur/issues/1091 for more info.
* @param name Name of the collision group
* @param category 32 bit category for the group, should be a unique power of 2. For example `0b001` or `0b010`
* @param mask 32 bit mask of category, or `~category` generally. For a category of `0b001`, the mask would be `0b110`
*/
function CollisionGroup(name, category, mask) {
this._name = name;
this._category = category;
this._mask = mask;
}
Object.defineProperty(CollisionGroup.prototype, "name", {
/**
* Get the name of the collision group
*/
get: function () {
return this._name;
},
enumerable: false,
configurable: true
});
Object.defineProperty(CollisionGroup.prototype, "category", {
/**
* Get the category of the collision group, a 32 bit number which should be a unique power of 2
*/
get: function () {
return this._category;
},
enumerable: false,
configurable: true
});
Object.defineProperty(CollisionGroup.prototype, "mask", {
/**
* Get the mask for this collision group
*/
get: function () {
return this._mask;
},
enumerable: false,
configurable: true
});
/**
* Evaluates whether 2 collision groups can collide
* @param other CollisionGroup
*/
CollisionGroup.prototype.canCollide = function (other) {
return (this.category & other.mask) !== 0 && (other.category & this.mask) !== 0;
};
/**
* The `All` [[CollisionGroup]] is a special group that collides with all other groups including itself,
* it is the default collision group on colliders.
*/
CollisionGroup.All = new CollisionGroup('Collide with all groups', -1, -1);
return CollisionGroup;
}());
/***/ }),
/***/ "./Collision/CollisionGroupManager.ts":
/*!********************************************!*\
!*** ./Collision/CollisionGroupManager.ts ***!
\********************************************/
/*! exports provided: CollisionGroupManager */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CollisionGroupManager", function() { return CollisionGroupManager; });
/* harmony import */ var _CollisionGroup__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./CollisionGroup */ "./Collision/CollisionGroup.ts");
/**
* Static class for managing collision groups in excalibur, there is a maximum of 32 collision groups possible in excalibur
*/
var CollisionGroupManager = /** @class */ (function () {
function CollisionGroupManager() {
}
/**
* Create a new named collision group up to a max of 32.
* @param name Name for the collision group
* @param mask Optionally provide your own 32-bit mask, if none is provide the manager will generate one
*/
CollisionGroupManager.create = function (name, mask) {
if (this._currentGroup > this._MAX_GROUPS) {
throw new Error("Cannot have more than " + this._MAX_GROUPS + " collision groups");
}
if (this._groups.get(name)) {
throw new Error("Collision group " + name + " already exists");
}
var group = new _CollisionGroup__WEBPACK_IMPORTED_MODULE_0__["CollisionGroup"](name, this._currentBit, mask !== undefined ? mask : ~this._currentBit);
this._currentBit = (this._currentBit << 1) | 0;
this._currentGroup++;
this._groups.set(name, group);
return group;
};
Object.defineProperty(CollisionGroupManager, "groups", {
/**
* Get all collision groups currently tracked by excalibur
*/
get: function () {
return Array.from(this._groups.values());
},
enumerable: false,
configurable: true
});
/**
* Get a collision group by it's name
* @param name
*/
CollisionGroupManager.groupByName = function (name) {
return this._groups.get(name);
};
/**
* Resets the managers internal group management state
*/
CollisionGroupManager.reset = function () {
this._groups = new Map();
this._currentBit = this._STARTING_BIT;
this._currentGroup = 1;
};
// using bitmasking the maximum number of groups is 32, because that is the highest 32bit integer that JS can present.
CollisionGroupManager._STARTING_BIT = 1 | 0;
CollisionGroupManager._MAX_GROUPS = 32;
CollisionGroupManager._currentGroup = 1;
CollisionGroupManager._currentBit = CollisionGroupManager._STARTING_BIT;
CollisionGroupManager._groups = new Map();
return CollisionGroupManager;
}());
/***/ }),
/***/ "./Collision/CollisionJumpTable.ts":
/*!*****************************************!*\
!*** ./Collision/CollisionJumpTable.ts ***!
\*****************************************/
/*! exports provided: CollisionJumpTable */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CollisionJumpTable", function() { return CollisionJumpTable; });
/* harmony import */ var _CollisionContact__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./CollisionContact */ "./Collision/CollisionContact.ts");
/* harmony import */ var _ConvexPolygon__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./ConvexPolygon */ "./Collision/ConvexPolygon.ts");
var CollisionJumpTable = {
CollideCircleCircle: function (circleA, circleB) {
var radius = circleA.radius + circleB.radius;
var circleAPos = circleA.worldPos;
var circleBPos = circleB.worldPos;
if (circleAPos.distance(circleBPos) > radius) {
return null;
}
var axisOfCollision = circleBPos.sub(circleAPos).normalize();
var mvt = axisOfCollision.scale(radius - circleBPos.distance(circleAPos));
var pointOfCollision = circleA.getFurthestPoint(axisOfCollision);
return new _CollisionContact__WEBPACK_IMPORTED_MODULE_0__["CollisionContact"](circleA.collider, circleB.collider, mvt, pointOfCollision, axisOfCollision);
},
CollideCirclePolygon: function (circle, polygon) {
var minAxis = circle.testSeparatingAxisTheorem(polygon);
if (!minAxis) {
return null;
}
// make sure that the minAxis is pointing away from circle
var samedir = minAxis.dot(polygon.center.sub(circle.center));
minAxis = samedir < 0 ? minAxis.negate() : minAxis;
var verts = [];
var point1 = polygon.getFurthestPoint(minAxis.negate());
var point2 = circle.getFurthestPoint(minAxis); //.add(cc);
if (circle.contains(point1)) {
verts.push(point1);
}
if (polygon.contains(point2)) {
verts.push(point2);
}
if (verts.length === 0) {
return null;
}
return new _CollisionContact__WEBPACK_IMPORTED_MODULE_0__["CollisionContact"](circle.collider, polygon.collider, minAxis, verts.length === 2 ? verts[0].average(verts[1]) : verts[0], minAxis.normalize());
},
CollideCircleEdge: function (circle, edge) {
// center of the circle
var cc = circle.center;
// vector in the direction of the edge
var e = edge.end.sub(edge.begin);
// amount of overlap with the circle's center along the edge direction
var u = e.dot(edge.end.sub(cc));
var v = e.dot(cc.sub(edge.begin));
// Potential region A collision (circle is on the left side of the edge, before the beginning)
if (v <= 0) {
var da = edge.begin.sub(cc);
var dda = da.dot(da); // quick and dirty way of calc'n distance in r^2 terms saves some sqrts
// save some sqrts
if (dda > circle.radius * circle.radius) {
return null; // no collision
}
return new _CollisionContact__WEBPACK_IMPORTED_MODULE_0__["CollisionContact"](circle.collider, edge.collider, da.normalize().scale(circle.radius - Math.sqrt(dda)), edge.begin, da.normalize());
}
// Potential region B collision (circle is on the right side of the edge, after the end)
if (u <= 0) {
var db = edge.end.sub(cc);
var ddb = db.dot(db);
if (ddb > circle.radius * circle.radius) {
return null;
}
return new _CollisionContact__WEBPACK_IMPORTED_MODULE_0__["CollisionContact"](circle.collider, edge.collider, db.normalize().scale(circle.radius - Math.sqrt(ddb)), edge.end, db.normalize());
}
// Otherwise potential region AB collision (circle is in the middle of the edge between the beginning and end)
var den = e.dot(e);
var pointOnEdge = edge.begin
.scale(u)
.add(edge.end.scale(v))
.scale(1 / den);
var d = cc.sub(pointOnEdge);
var dd = d.dot(d);
if (dd > circle.radius * circle.radius) {
return null; // no collision
}
var n = e.perpendicular();
// flip correct direction
if (n.dot(cc.sub(edge.begin)) < 0) {
n.x = -n.x;
n.y = -n.y;
}
n = n.normalize();
var mvt = n.scale(Math.abs(circle.radius - Math.sqrt(dd)));
return new _CollisionContact__WEBPACK_IMPORTED_MODULE_0__["CollisionContact"](circle.collider, edge.collider, mvt.negate(), pointOnEdge, n.negate());
},
CollideEdgeEdge: function () {
// Edge-edge collision doesn't make sense
return null;
},
CollidePolygonEdge: function (polygon, edge) {
// 3 cases:
// (1) Polygon lands on the full face
// (2) Polygon lands on the right point
// (3) Polygon lands on the left point
var e = edge.end.sub(edge.begin);
var edgeNormal = e.normal();
if (polygon.contains(edge.begin)) {
var _a = polygon.getClosestFace(edge.begin), mtv = _a.distance, face = _a.face;
if (mtv) {
return new _CollisionContact__WEBPACK_IMPORTED_MODULE_0__["CollisionContact"](polygon.collider, edge.collider, mtv.negate(), edge.begin.add(mtv.negate()), face.normal().negate());
}
}
if (polygon.contains(edge.end)) {
var _b = polygon.getClosestFace(edge.end), mtv = _b.distance, face = _b.face;
if (mtv) {
return new _CollisionContact__WEBPACK_IMPORTED_MODULE_0__["CollisionContact"](polygon.collider, edge.collider, mtv.negate(), edge.end.add(mtv.negate()), face.normal().negate());
}
}
var pc = polygon.center;
var ec = edge.center;
var dir = ec.sub(pc).normalize();
// build a temporary polygon from the edge to use SAT
var linePoly = new _ConvexPolygon__WEBPACK_IMPORTED_MODULE_1__["ConvexPolygon"]({
collider: edge.collider,
points: [edge.begin, edge.end, edge.end.add(dir.scale(30)), edge.begin.add(dir.scale(30))]
});
var minAxis = polygon.testSeparatingAxisTheorem(linePoly);
// no minAxis, no overlap, no collision
if (!minAxis) {
return null;
}
// flip the normal and axis to always have positive collisions
edgeNormal = edgeNormal.dot(dir) < 0 ? edgeNormal.negate() : edgeNormal;
minAxis = minAxis.dot(dir) < 0 ? minAxis.negate() : minAxis;
return new _CollisionContact__WEBPACK_IMPORTED_MODULE_0__["CollisionContact"](polygon.collider, edge.collider, minAxis, polygon.getFurthestPoint(edgeNormal), edgeNormal);
},
CollidePolygonPolygon: function (polyA, polyB) {
// do a SAT test to find a min axis if it exists
var minAxis = polyA.testSeparatingAxisTheorem(polyB);
// no overlap, no collision return null
if (!minAxis) {
return null;
}
// make sure that minAxis is pointing from A -> B
var sameDir = minAxis.dot(polyB.center.sub(polyA.center));
minAxis = sameDir < 0 ? minAxis.negate() : minAxis;
// find rough point of collision
// todo this could be better
var verts = [];
var pointA = polyA.getFurthestPoint(minAxis);
var pointB = polyB.getFurthestPoint(minAxis.negate());
if (polyB.contains(pointA)) {
verts.push(pointA);
}
if (polyA.contains(pointB)) {
verts.push(pointB);
}
// no candidates, pick something
if (verts.length === 0) {
verts.push(pointB);
}
var contact = verts.length === 2 ? verts[0].add(verts[1]).scale(0.5) : verts[0];
return new _CollisionContact__WEBPACK_IMPORTED_MODULE_0__["CollisionContact"](polyA.collider, polyB.collider, minAxis, contact, minAxis.normalize());
}
};
/***/ }),
/***/ "./Collision/CollisionResolver.ts":
/*!****************************************!*\
!*** ./Collision/CollisionResolver.ts ***!
\****************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/***/ }),
/***/ "./Collision/CollisionShape.ts":
/*!*************************************!*\
!*** ./Collision/CollisionShape.ts ***!
\*************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/***/ }),
/***/ "./Collision/CollisionType.ts":
/*!************************************!*\
!*** ./Collision/CollisionType.ts ***!
\************************************/
/*! exports provided: CollisionType */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CollisionType", function() { return CollisionType; });
/**
* An enum that describes the types of collisions actors can participate in
*/
var CollisionType;
(function (CollisionType) {
/**
* Actors with the `PreventCollision` setting do not participate in any
* collisions and do not raise collision events.
*/
CollisionType["PreventCollision"] = "PreventCollision";
/**
* Actors with the `Passive` setting only raise collision events, but are not
* influenced or moved by other actors and do not influence or move other actors.
*/
CollisionType["Passive"] = "Passive";
/**
* Actors with the `Active` setting raise collision events and participate
* in collisions with other actors and will be push or moved by actors sharing
* the `Active` or `Fixed` setting.
*/
CollisionType["Active"] = "Active";
/**
* Actors with the `Fixed` setting raise collision events and participate in
* collisions with other actors. Actors with the `Fixed` setting will not be
* pushed or moved by other actors sharing the `Fixed`. Think of Fixed
* actors as "immovable/unstoppable" objects. If two `Fixed` actors meet they will
* not be pushed or moved by each other, they will not interact except to throw
* collision events.
*/
CollisionType["Fixed"] = "Fixed";
})(CollisionType || (CollisionType = {}));
/***/ }),
/***/ "./Collision/ConvexPolygon.ts":
/*!************************************!*\
!*** ./Collision/ConvexPolygon.ts ***!
\************************************/
/*! exports provided: ConvexPolygon */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ConvexPolygon", function() { return ConvexPolygon; });
/* harmony import */ var _Drawing_Color__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Drawing/Color */ "./Drawing/Color.ts");
/* harmony import */ var _Physics__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Physics */ "./Physics.ts");
/* harmony import */ var _BoundingBox__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./BoundingBox */ "./Collision/BoundingBox.ts");
/* harmony import */ var _Edge__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Edge */ "./Collision/Edge.ts");
/* harmony import */ var _CollisionJumpTable__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./CollisionJumpTable */ "./Collision/CollisionJumpTable.ts");
/* harmony import */ var _Circle__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Circle */ "./Collision/Circle.ts");
/* harmony import */ var _Algebra__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Algebra */ "./Algebra.ts");
/* harmony import */ var _ClosestLineJumpTable__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./ClosestLineJumpTable */ "./Collision/ClosestLineJumpTable.ts");
/**
* Polygon collision shape for detecting collisions
*
* Example:
* [[include:BoxAndPolygonShape.md]]
*/
var ConvexPolygon = /** @class */ (function () {
function ConvexPolygon(options) {
this._transformedPoints = [];
this._axes = [];
this._sides = [];
this.offset = options.offset || _Algebra__WEBPACK_IMPORTED_MODULE_6__["Vector"].Zero;
var winding = !!options.clockwiseWinding;
this.points = (winding ? options.points.reverse() : options.points) || [];
this.collider = this.collider = options.collider || null;
// calculate initial transformation
this._calculateTransformation();
}
/**
* Returns a clone of this ConvexPolygon, not associated with any collider
*/
ConvexPolygon.prototype.clone = function () {
return new ConvexPolygon({
offset: this.offset.clone(),
points: this.points.map(function (p) { return p.clone(); }),
collider: null
});
};
Object.defineProperty(ConvexPolygon.prototype, "worldPos", {
get: function () {
if (this.collider && this.collider.body) {
return this.collider.body.pos.add(this.offset);
}
return this.offset;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ConvexPolygon.prototype, "center", {
/**
* Get the center of the collision shape in world coordinates
*/
get: function () {
var body = this.collider ? this.collider.body : null;
if (body) {
return body.pos.add(this.offset);
}
return this.offset;
},
enumerable: false,
configurable: true
});
/**
* Calculates the underlying transformation from the body relative space to world space
*/
ConvexPolygon.prototype._calculateTransformation = function () {
var body = this.collider ? this.collider.body : null;
var pos = body ? body.pos.add(this.offset) : this.offset;
var angle = body ? body.rotation : 0;
var scale = body ? body.scale : _Algebra__WEBPACK_IMPORTED_MODULE_6__["Vector"].One;
var len = this.points.length;
this._transformedPoints.length = 0; // clear out old transform
for (var i = 0; i < len; i++) {
this._transformedPoints[i] = this.points[i]
.scale(scale)
.rotate(angle)
.add(pos);
}
};
/**
* Gets the points that make up the polygon in world space, from actor relative space (if specified)
*/
ConvexPolygon.prototype.getTransformedPoints = function () {
// only recalculate geometry if, hasn't been calculated
if (!this._transformedPoints.length ||
// or the position or rotation has changed in world space
(this.collider &&
this.collider.body &&
(!this.collider.body.oldPos.equals(this.collider.body.pos) ||
this.collider.body.oldRotation !== this.collider.body.rotation ||
this.collider.body.oldScale !== this.collider.body.scale))) {
this._calculateTransformation();
}
return this._transformedPoints;
};
/**
* Gets the sides of the polygon in world space
*/
ConvexPolygon.prototype.getSides = function () {
if (this._sides.length) {
return this._sides;
}
var lines = [];
var points = this.getTransformedPoints();
var len = points.length;
for (var i = 0; i < len; i++) {
lines.push(new _Algebra__WEBPACK_IMPORTED_MODULE_6__["Line"](points[i], points[(i - 1 + len) % len]));
}
this._sides = lines;
return this._sides;
};
ConvexPolygon.prototype.recalc = function () {
this._sides.length = 0;
this._axes.length = 0;
this._transformedPoints.length = 0;
this.getTransformedPoints();
this.getSides();
};
/**
* Tests if a point is contained in this collision shape in world space
*/
ConvexPolygon.prototype.contains = function (point) {
// Always cast to the right, as long as we cast in a consistent fixed direction we
// will be fine
var testRay = new _Algebra__WEBPACK_IMPORTED_MODULE_6__["Ray"](point, new _Algebra__WEBPACK_IMPORTED_MODULE_6__["Vector"](1, 0));
var intersectCount = this.getSides().reduce(function (accum, side) {
if (testRay.intersect(side) >= 0) {
return accum + 1;
}
return accum;
}, 0);
if (intersectCount % 2 === 0) {
return false;
}
return true;
};
ConvexPolygon.prototype.getClosestLineBetween = function (shape) {
if (shape instanceof _Circle__WEBPACK_IMPORTED_MODULE_5__["Circle"]) {
return _ClosestLineJumpTable__WEBPACK_IMPORTED_MODULE_7__["ClosestLineJumpTable"].PolygonCircleClosestLine(this, shape);
}
else if (shape instanceof ConvexPolygon) {
return _ClosestLineJumpTable__WEBPACK_IMPORTED_MODULE_7__["ClosestLineJumpTable"].PolygonPolygonClosestLine(this, shape);
}
else if (shape instanceof _Edge__WEBPACK_IMPORTED_MODULE_3__["Edge"]) {
return _ClosestLineJumpTable__WEBPACK_IMPORTED_MODULE_7__["ClosestLineJumpTable"].PolygonEdgeClosestLine(this, shape);
}
else {
throw new Error("Polygon could not collide with unknown CollisionShape " + typeof shape);
}
};
/**
* Returns a collision contact if the 2 collision shapes collide, otherwise collide will
* return null.
* @param shape
*/
ConvexPolygon.prototype.collide = function (shape) {
if (shape instanceof _Circle__WEBPACK_IMPORTED_MODULE_5__["Circle"]) {
return _CollisionJumpTable__WEBPACK_IMPORTED_MODULE_4__["CollisionJumpTable"].CollideCirclePolygon(shape, this);
}
else if (shape instanceof ConvexPolygon) {
return _CollisionJumpTable__WEBPACK_IMPORTED_MODULE_4__["CollisionJumpTable"].CollidePolygonPolygon(this, shape);
}
else if (shape instanceof _Edge__WEBPACK_IMPORTED_MODULE_3__["Edge"]) {
return _CollisionJumpTable__WEBPACK_IMPORTED_MODULE_4__["CollisionJumpTable"].CollidePolygonEdge(this, shape);
}
else {
throw new Error("Polygon could not collide with unknown CollisionShape " + typeof shape);
}
};
/**
* Find the point on the shape furthest in the direction specified
*/
ConvexPolygon.prototype.getFurthestPoint = function (direction) {
var pts = this.getTransformedPoints();
var furthestPoint = null;
var maxDistance = -Number.MAX_VALUE;
for (var i = 0; i < pts.length; i++) {
var distance = direction.dot(pts[i]);
if (distance > maxDistance) {
maxDistance = distance;
furthestPoint = pts[i];
}
}
return furthestPoint;
};
/**
* Finds the closes face to the point using perpendicular distance
* @param point point to test against polygon
*/
ConvexPolygon.prototype.getClosestFace = function (point) {
var sides = this.getSides();
var min = Number.POSITIVE_INFINITY;
var faceIndex = -1;
var distance = -1;
for (var i = 0; i < sides.length; i++) {
var dist = sides[i].distanceToPoint(point);
if (dist < min) {
min = dist;
faceIndex = i;
distance = dist;
}
}
if (faceIndex !== -1) {
return {
distance: sides[faceIndex].normal().scale(distance),
face: sides[faceIndex]
};
}
return null;
};
Object.defineProperty(ConvexPolygon.prototype, "bounds", {
/**
* Get the axis aligned bounding box for the polygon shape in world coordinates
*/
get: function () {
var points = this.getTransformedPoints();
return _BoundingBox__WEBPACK_IMPORTED_MODULE_2__["BoundingBox"].fromPoints(points);
},
enumerable: false,
configurable: true
});
Object.defineProperty(ConvexPolygon.prototype, "localBounds", {
/**
* Get the axis aligned bounding box for the polygon shape in local coordinates
*/
get: function () {
return _BoundingBox__WEBPACK_IMPORTED_MODULE_2__["BoundingBox"].fromPoints(this.points);
},
enumerable: false,
configurable: true
});
Object.defineProperty(ConvexPolygon.prototype, "inertia", {
/**
* Get the moment of inertia for an arbitrary polygon
* https://en.wikipedia.org/wiki/List_of_moments_of_inertia
*/
get: function () {
var mass = this.collider ? this.collider.mass : _Physics__WEBPACK_IMPORTED_MODULE_1__["Physics"].defaultMass;
var numerator = 0;
var denominator = 0;
for (var i = 0; i < this.points.length; i++) {
var iplusone = (i + 1) % this.points.length;
var crossTerm = this.points[iplusone].cross(this.points[i]);
numerator +=
crossTerm *
(this.points[i].dot(this.points[i]) + this.points[i].dot(this.points[iplusone]) + this.points[iplusone].dot(this.points[iplusone]));
denominator += crossTerm;
}
return (mass / 6) * (numerator / denominator);
},
enumerable: false,
configurable: true
});
/**
* Casts a ray into the polygon and returns a vector representing the point of contact (in world space) or null if no collision.
*/
ConvexPolygon.prototype.rayCast = function (ray, max) {
if (max === void 0) { max = Infinity; }
// find the minimum contact time greater than 0
// contact times less than 0 are behind the ray and we don't want those
var sides = this.getSides();
var len = sides.length;
var minContactTime = Number.MAX_VALUE;
var contactIndex = -1;
for (var i = 0; i < len; i++) {
var contactTime = ray.intersect(sides[i]);
if (contactTime >= 0 && contactTime < minContactTime && contactTime <= max) {
minContactTime = contactTime;
contactIndex = i;
}
}
// contact was found
if (contactIndex >= 0) {
return ray.getPoint(minContactTime);
}
// no contact found
return null;
};
Object.defineProperty(ConvexPolygon.prototype, "axes", {
/**
* Get the axis associated with the convex polygon
*/
get: function () {
if (this._axes.length) {
return this._axes;
}
var axes = [];
var points = this.getTransformedPoints();
var len = points.length;
for (var i = 0; i < len; i++) {
axes.push(points[i].sub(points[(i + 1) % len]).normal());
}
this._axes = axes;
return this._axes;
},
enumerable: false,
configurable: true
});
/**
* Perform Separating Axis test against another polygon, returns null if no overlap in polys
* Reference http://www.dyn4j.org/2010/01/sat/
*/
ConvexPolygon.prototype.testSeparatingAxisTheorem = function (other) {
var poly1 = this;
var poly2 = other;
var axes = poly1.axes.concat(poly2.axes);
var minOverlap = Number.MAX_VALUE;
var minAxis = null;
var minIndex = -1;
for (var i = 0; i < axes.length; i++) {
var proj1 = poly1.project(axes[i]);
var proj2 = poly2.project(axes[i]);
var overlap = proj1.getOverlap(proj2);
if (overlap <= 0) {
return null;
}
else {
if (overlap < minOverlap) {
minOverlap = overlap;
minAxis = axes[i];
minIndex = i;
}
}
}
// Sanity check
if (minIndex === -1) {
return null;
}
return minAxis.normalize().scale(minOverlap);
};
/**
* Project the edges of the polygon along a specified axis
*/
ConvexPolygon.prototype.project = function (axis) {
var points = this.getTransformedPoints();
var len = points.length;
var min = Number.MAX_VALUE;
var max = -Number.MAX_VALUE;
for (var i = 0; i < len; i++) {
var scalar = points[i].dot(axis);
min = Math.min(min, scalar);
max = Math.max(max, scalar);
}
return new _Algebra__WEBPACK_IMPORTED_MODULE_6__["Projection"](min, max);
};
ConvexPolygon.prototype.draw = function (ctx, color, pos) {
if (color === void 0) { color = _Drawing_Color__WEBPACK_IMPORTED_MODULE_0__["Color"].Green; }
if (pos === void 0) { pos = _Algebra__WEBPACK_IMPORTED_MODULE_6__["Vector"].Zero; }
ctx.beginPath();
ctx.fillStyle = color.toString();
var newPos = pos.add(this.offset);
// Iterate through the supplied points and construct a 'polygon'
var firstPoint = this.points[0].add(newPos);
ctx.moveTo(firstPoint.x, firstPoint.y);
this.points
.map(function (p) { return p.add(newPos); })
.forEach(function (point) {
ctx.lineTo(point.x, point.y);
});
ctx.lineTo(firstPoint.x, firstPoint.y);
ctx.closePath();
ctx.fill();
};
/* istanbul ignore next */
ConvexPolygon.prototype.debugDraw = function (ctx, color) {
if (color === void 0) { color = _Drawing_Color__WEBPACK_IMPORTED_MODULE_0__["Color"].Red; }
ctx.beginPath();
ctx.strokeStyle = color.toString();
// Iterate through the supplied points and construct a 'polygon'
var firstPoint = this.getTransformedPoints()[0];
ctx.moveTo(firstPoint.x, firstPoint.y);
this.getTransformedPoints().forEach(function (point) {
ctx.lineTo(point.x, point.y);
});
ctx.lineTo(firstPoint.x, firstPoint.y);
ctx.closePath();
ctx.stroke();
};
return ConvexPolygon;
}());
/***/ }),
/***/ "./Collision/DynamicTree.ts":
/*!**********************************!*\
!*** ./Collision/DynamicTree.ts ***!
\**********************************/
/*! exports provided: TreeNode, DynamicTree */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TreeNode", function() { return TreeNode; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DynamicTree", function() { return DynamicTree; });
/* harmony import */ var _Physics__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./../Physics */ "./Physics.ts");
/* harmony import */ var _BoundingBox__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./BoundingBox */ "./Collision/BoundingBox.ts");
/* harmony import */ var _Util_Log__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Util/Log */ "./Util/Log.ts");
/**
* Dynamic Tree Node used for tracking bounds within the tree
*/
var TreeNode = /** @class */ (function () {
function TreeNode(parent) {
this.parent = parent;
this.parent = parent || null;
this.body = null;
this.bounds = new _BoundingBox__WEBPACK_IMPORTED_MODULE_1__["BoundingBox"]();
this.left = null;
this.right = null;
this.height = 0;
}
TreeNode.prototype.isLeaf = function () {
return !this.left && !this.right;
};
return TreeNode;
}());
/**
* The DynamicTrees provides a spatial partitioning data structure for quickly querying for overlapping bounding boxes for
* all tracked bodies. The worst case performance of this is O(n*log(n)) where n is the number of bodies in the tree.
*
* Internally the bounding boxes are organized as a balanced binary tree of bounding boxes, where the leaf nodes are tracked bodies.
* Every non-leaf node is a bounding box that contains child bounding boxes.
*/
var DynamicTree = /** @class */ (function () {
function DynamicTree(worldBounds) {
if (worldBounds === void 0) { worldBounds = new _BoundingBox__WEBPACK_IMPORTED_MODULE_1__["BoundingBox"](-Number.MAX_VALUE, -Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); }
this.worldBounds = worldBounds;
this.root = null;
this.nodes = {};
}
/**
* Inserts a node into the dynamic tree
*/
DynamicTree.prototype._insert = function (leaf) {
// If there are no nodes in the tree, make this the root leaf
if (this.root === null) {
this.root = leaf;
this.root.parent = null;
return;
}
// Search the tree for a node that is not a leaf and find the best place to insert
var leafAABB = leaf.bounds;
var currentRoot = this.root;
while (!currentRoot.isLeaf()) {
var left = currentRoot.left;
var right = currentRoot.right;
var area = currentRoot.bounds.getPerimeter();
var combinedAABB = currentRoot.bounds.combine(leafAABB);
var combinedArea = combinedAABB.getPerimeter();
// Calculate cost heuristic for creating a new parent and leaf
var cost = 2 * combinedArea;
// Minimum cost of pushing the leaf down the tree
var inheritanceCost = 2 * (combinedArea - area);
// Cost of descending
var leftCost = 0;
var leftCombined = leafAABB.combine(left.bounds);
var newArea = void 0;
var oldArea = void 0;
if (left.isLeaf()) {
leftCost = leftCombined.getPerimeter() + inheritanceCost;
}
else {
oldArea = left.bounds.getPerimeter();
newArea = leftCombined.getPerimeter();
leftCost = newArea - oldArea + inheritanceCost;
}
var rightCost = 0;
var rightCombined = leafAABB.combine(right.bounds);
if (right.isLeaf()) {
rightCost = rightCombined.getPerimeter() + inheritanceCost;
}
else {
oldArea = right.bounds.getPerimeter();
newArea = rightCombined.getPerimeter();
rightCost = newArea - oldArea + inheritanceCost;
}
// cost is acceptable
if (cost < leftCost && cost < rightCost) {
break;
}
// Descend to the depths
if (leftCost < rightCost) {
currentRoot = left;
}
else {
currentRoot = right;
}
}
// Create the new parent node and insert into the tree
var oldParent = currentRoot.parent;
var newParent = new TreeNode(oldParent);
newParent.bounds = leafAABB.combine(currentRoot.bounds);
newParent.height = currentRoot.height + 1;
if (oldParent !== null) {
// The sibling node was not the root
if (oldParent.left === currentRoot) {
oldParent.left = newParent;
}
else {
oldParent.right = newParent;
}
newParent.left = currentRoot;
newParent.right = leaf;
currentRoot.parent = newParent;
leaf.parent = newParent;
}
else {
// The sibling node was the root
newParent.left = currentRoot;
newParent.right = leaf;
currentRoot.parent = newParent;
leaf.parent = newParent;
this.root = newParent;
}
// Walk up the tree fixing heights and AABBs
var currentNode = leaf.parent;
while (currentNode) {
currentNode = this._balance(currentNode);
if (!currentNode.left) {
throw new Error('Parent of current leaf cannot have a null left child' + currentNode);
}
if (!currentNode.right) {
throw new Error('Parent of current leaf cannot have a null right child' + currentNode);
}
currentNode.height = 1 + Math.max(currentNode.left.height, currentNode.right.height);
currentNode.bounds = currentNode.left.bounds.combine(currentNode.right.bounds);
currentNode = currentNode.parent;
}
};
/**
* Removes a node from the dynamic tree
*/
DynamicTree.prototype._remove = function (leaf) {
if (leaf === this.root) {
this.root = null;
return;
}
var parent = leaf.parent;
var grandParent = parent.parent;
var sibling;
if (parent.left === leaf) {
sibling = parent.right;
}
else {
sibling = parent.left;
}
if (grandParent) {
if (grandParent.left === parent) {
grandParent.left = sibling;
}
else {
grandParent.right = sibling;
}
sibling.parent = grandParent;
var currentNode = grandParent;
while (currentNode) {
currentNode = this._balance(currentNode);
currentNode.bounds = currentNode.left.bounds.combine(currentNode.right.bounds);
currentNode.height = 1 + Math.max(currentNode.left.height, currentNode.right.height);
currentNode = currentNode.parent;
}
}
else {
this.root = sibling;
sibling.parent = null;
}
};
/**
* Tracks a body in the dynamic tree
*/
DynamicTree.prototype.trackBody = function (body) {
var node = new TreeNode();
node.body = body;
node.bounds = body.collider.bounds;
node.bounds.left -= 2;
node.bounds.top -= 2;
node.bounds.right += 2;
node.bounds.bottom += 2;
this.nodes[body.id] = node;
this._insert(node);
};
/**
* Updates the dynamic tree given the current bounds of each body being tracked
*/
DynamicTree.prototype.updateBody = function (body) {
var node = this.nodes[body.id];
if (!node) {
return false;
}
var b = body.collider.bounds;
// if the body is outside the world no longer update it
if (!this.worldBounds.contains(b)) {
_Util_Log__WEBPACK_IMPORTED_MODULE_2__["Logger"].getInstance().warn('Collider with id ' + body.id + ' is outside the world bounds and will no longer be tracked for physics');
this.untrackBody(body);
return false;
}
if (node.bounds.contains(b)) {
return false;
}
this._remove(node);
b.left -= _Physics__WEBPACK_IMPORTED_MODULE_0__["Physics"].boundsPadding;
b.top -= _Physics__WEBPACK_IMPORTED_MODULE_0__["Physics"].boundsPadding;
b.right += _Physics__WEBPACK_IMPORTED_MODULE_0__["Physics"].boundsPadding;
b.bottom += _Physics__WEBPACK_IMPORTED_MODULE_0__["Physics"].boundsPadding;
var multdx = body.vel.x * _Physics__WEBPACK_IMPORTED_MODULE_0__["Physics"].dynamicTreeVelocityMultiplier;
var multdy = body.vel.y * _Physics__WEBPACK_IMPORTED_MODULE_0__["Physics"].dynamicTreeVelocityMultiplier;
if (multdx < 0) {
b.left += multdx;
}
else {
b.right += multdx;
}
if (multdy < 0) {
b.top += multdy;
}
else {
b.bottom += multdy;
}
node.bounds = b;
this._insert(node);
return true;
};
/**
* Untracks a body from the dynamic tree
*/
DynamicTree.prototype.untrackBody = function (body) {
var node = this.nodes[body.collider.id];
if (!node) {
return;
}
this._remove(node);
this.nodes[body.collider.id] = null;
delete this.nodes[body.collider.id];
};
/**
* Balances the tree about a node
*/
DynamicTree.prototype._balance = function (node) {
if (node === null) {
throw new Error('Cannot balance at null node');
}
if (node.isLeaf() || node.height < 2) {
return node;
}
var left = node.left;
var right = node.right;
var a = node;
var b = left;
var c = right;
var d = left.left;
var e = left.right;
var f = right.left;
var g = right.right;
var balance = c.height - b.height;
// Rotate c node up
if (balance > 1) {
// Swap the right node with it's parent
c.left = a;
c.parent = a.parent;
a.parent = c;
// The original node's old parent should point to the right node
// this is mega confusing
if (c.parent) {
if (c.parent.left === a) {
c.parent.left = c;
}
else {
c.parent.right = c;
}
}
else {
this.root = c;
}
// Rotate
if (f.height > g.height) {
c.right = f;
a.right = g;
g.parent = a;
a.bounds = b.bounds.combine(g.bounds);
c.bounds = a.bounds.combine(f.bounds);
a.height = 1 + Math.max(b.height, g.height);
c.height = 1 + Math.max(a.height, f.height);
}
else {
c.right = g;
a.right = f;
f.parent = a;
a.bounds = b.bounds.combine(f.bounds);
c.bounds = a.bounds.combine(g.bounds);
a.height = 1 + Math.max(b.height, f.height);
c.height = 1 + Math.max(a.height, g.height);
}
return c;
}
// Rotate left node up
if (balance < -1) {
// swap
b.left = a;
b.parent = a.parent;
a.parent = b;
// node's old parent should point to b
if (b.parent) {
if (b.parent.left === a) {
b.parent.left = b;
}
else {
if (b.parent.right !== a) {
throw 'Error rotating Dynamic Tree';
}
b.parent.right = b;
}
}
else {
this.root = b;
}
// rotate
if (d.height > e.height) {
b.right = d;
a.left = e;
e.parent = a;
a.bounds = c.bounds.combine(e.bounds);
b.bounds = a.bounds.combine(d.bounds);
a.height = 1 + Math.max(c.height, e.height);
b.height = 1 + Math.max(a.height, d.height);
}
else {
b.right = e;
a.left = d;
d.parent = a;
a.bounds = c.bounds.combine(d.bounds);
b.bounds = a.bounds.combine(e.bounds);
a.height = 1 + Math.max(c.height, d.height);
b.height = 1 + Math.max(a.height, e.height);
}
return b;
}
return node;
};
/**
* Returns the internal height of the tree, shorter trees are better. Performance drops as the tree grows
*/
DynamicTree.prototype.getHeight = function () {
if (this.root === null) {
return 0;
}
return this.root.height;
};
/**
* Queries the Dynamic Axis Aligned Tree for bodies that could be colliding with the provided body.
*
* In the query callback, it will be passed a potential collider. Returning true from this callback indicates
* that you are complete with your query and you do not want to continue. Returning false will continue searching
* the tree until all possible colliders have been returned.
*/
DynamicTree.prototype.query = function (body, callback) {
var bounds = body.collider.bounds;
var helper = function (currentNode) {
if (currentNode && currentNode.bounds.intersect(bounds)) {
if (currentNode.isLeaf() && currentNode.body !== body) {
if (callback.call(body, currentNode.body)) {
return true;
}
}
else {
return helper(currentNode.left) || helper(currentNode.right);
}
}
return false;
};
helper(this.root);
};
/**
* Queries the Dynamic Axis Aligned Tree for bodies that could be intersecting. By default the raycast query uses an infinitely
* long ray to test the tree specified by `max`.
*
* In the query callback, it will be passed a potential body that intersects with the raycast. Returning true from this
* callback indicates that your are complete with your query and do not want to continue. Return false will continue searching
* the tree until all possible bodies that would intersect with the ray have been returned.
*/
DynamicTree.prototype.rayCastQuery = function (ray, max, callback) {
if (max === void 0) { max = Infinity; }
var helper = function (currentNode) {
if (currentNode && currentNode.bounds.rayCast(ray, max)) {
if (currentNode.isLeaf()) {
if (callback.call(ray, currentNode.body)) {
// ray hit a leaf! return the body
return true;
}
}
else {
// ray hit but not at a leaf, recurse deeper
return helper(currentNode.left) || helper(currentNode.right);
}
}
return false; // ray missed
};
helper(this.root);
};
DynamicTree.prototype.getNodes = function () {
var helper = function (currentNode) {
if (currentNode) {
return [currentNode].concat(helper(currentNode.left), helper(currentNode.right));
}
else {
return [];
}
};
return helper(this.root);
};
DynamicTree.prototype.debugDraw = function (ctx) {
// draw all the nodes in the Dynamic Tree
var helper = function (currentNode) {
if (currentNode) {
if (currentNode.isLeaf()) {
ctx.lineWidth = 1;
ctx.strokeStyle = 'green';
}
else {
ctx.lineWidth = 1;
ctx.strokeStyle = 'white';
}
currentNode.bounds.debugDraw(ctx);
if (currentNode.left) {
helper(currentNode.left);
}
if (currentNode.right) {
helper(currentNode.right);
}
}
};
helper(this.root);
};
return DynamicTree;
}());
/***/ }),
/***/ "./Collision/DynamicTreeCollisionBroadphase.ts":
/*!*****************************************************!*\
!*** ./Collision/DynamicTreeCollisionBroadphase.ts ***!
\*****************************************************/
/*! exports provided: DynamicTreeCollisionBroadphase */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DynamicTreeCollisionBroadphase", function() { return DynamicTreeCollisionBroadphase; });
/* harmony import */ var _Physics__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./../Physics */ "./Physics.ts");
/* harmony import */ var _DynamicTree__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./DynamicTree */ "./Collision/DynamicTree.ts");
/* harmony import */ var _Pair__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Pair */ "./Collision/Pair.ts");
/* harmony import */ var _Algebra__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Algebra */ "./Algebra.ts");
/* harmony import */ var _Util_Log__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Util/Log */ "./Util/Log.ts");
/* harmony import */ var _Events__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Events */ "./Events.ts");
/* harmony import */ var _CollisionType__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./CollisionType */ "./Collision/CollisionType.ts");
var DynamicTreeCollisionBroadphase = /** @class */ (function () {
function DynamicTreeCollisionBroadphase() {
this._dynamicCollisionTree = new _DynamicTree__WEBPACK_IMPORTED_MODULE_1__["DynamicTree"]();
this._collisionHash = {};
this._collisionPairCache = [];
this._lastFramePairs = [];
this._lastFramePairsHash = {};
}
/**
* Tracks a physics body for collisions
*/
DynamicTreeCollisionBroadphase.prototype.track = function (target) {
if (!target) {
_Util_Log__WEBPACK_IMPORTED_MODULE_4__["Logger"].getInstance().warn('Cannot track null physics body');
return;
}
this._dynamicCollisionTree.trackBody(target);
};
/**
* Untracks a physics body
*/
DynamicTreeCollisionBroadphase.prototype.untrack = function (target) {
if (!target) {
_Util_Log__WEBPACK_IMPORTED_MODULE_4__["Logger"].getInstance().warn('Cannot untrack a null physics body');
return;
}
this._dynamicCollisionTree.untrackBody(target);
};
DynamicTreeCollisionBroadphase.prototype._shouldGenerateCollisionPair = function (colliderA, colliderB) {
// if the collision pair has been calculated already short circuit
var hash = _Pair__WEBPACK_IMPORTED_MODULE_2__["Pair"].calculatePairHash(colliderA, colliderB);
if (this._collisionHash[hash]) {
return false; // pair exists easy exit return false
}
return _Pair__WEBPACK_IMPORTED_MODULE_2__["Pair"].canCollide(colliderA, colliderB);
};
/**
* Detects potential collision pairs in a broadphase approach with the dynamic aabb tree strategy
*/
DynamicTreeCollisionBroadphase.prototype.broadphase = function (targets, delta, stats) {
var _this = this;
var seconds = delta / 1000;
// Retrieve the list of potential colliders, exclude killed, prevented, and self
var potentialColliders = targets
.map(function (t) { return t.collider; })
.filter(function (other) {
return other.active && other.type !== _CollisionType__WEBPACK_IMPORTED_MODULE_6__["CollisionType"].PreventCollision;
});
// clear old list of collision pairs
this._collisionPairCache = [];
this._collisionHash = {};
// check for normal collision pairs
var collider;
for (var j = 0, l = potentialColliders.length; j < l; j++) {
collider = potentialColliders[j];
// Query the collision tree for potential colliders
this._dynamicCollisionTree.query(collider.body, function (other) {
if (_this._shouldGenerateCollisionPair(collider, other.collider)) {
var pair = new _Pair__WEBPACK_IMPORTED_MODULE_2__["Pair"](collider, other.collider);
_this._collisionHash[pair.id] = true;
_this._collisionPairCache.push(pair);
}
// Always return false, to query whole tree. Returning true in the query method stops searching
return false;
});
}
if (stats) {
stats.physics.pairs = this._collisionPairCache.length;
}
// Check dynamic tree for fast moving objects
// Fast moving objects are those moving at least there smallest bound per frame
if (_Physics__WEBPACK_IMPORTED_MODULE_0__["Physics"].checkForFastBodies) {
var _loop_1 = function (collider_1) {
// Skip non-active objects. Does not make sense on other collision types
if (collider_1.type !== _CollisionType__WEBPACK_IMPORTED_MODULE_6__["CollisionType"].Active) {
return "continue";
}
// Maximum travel distance next frame
var updateDistance = collider_1.body.vel.size * seconds + // velocity term
collider_1.body.acc.size * 0.5 * seconds * seconds; // acc term
// Find the minimum dimension
var minDimension = Math.min(collider_1.bounds.height, collider_1.bounds.width);
if (_Physics__WEBPACK_IMPORTED_MODULE_0__["Physics"].disableMinimumSpeedForFastBody || updateDistance > minDimension / 2) {
if (stats) {
stats.physics.fastBodies++;
}
// start with the oldPos because the integration for actors has already happened
// objects resting on a surface may be slightly penetrating in the current position
var updateVec = collider_1.body.pos.sub(collider_1.body.oldPos);
var centerPoint = collider_1.shape.center;
var furthestPoint = collider_1.shape.getFurthestPoint(collider_1.body.vel);
var origin_1 = furthestPoint.sub(updateVec);
var ray_1 = new _Algebra__WEBPACK_IMPORTED_MODULE_3__["Ray"](origin_1, collider_1.body.vel);
// back the ray up by -2x surfaceEpsilon to account for fast moving objects starting on the surface
ray_1.pos = ray_1.pos.add(ray_1.dir.scale(-2 * _Physics__WEBPACK_IMPORTED_MODULE_0__["Physics"].surfaceEpsilon));
var minBody_1;
var minTranslate_1 = new _Algebra__WEBPACK_IMPORTED_MODULE_3__["Vector"](Infinity, Infinity);
this_1._dynamicCollisionTree.rayCastQuery(ray_1, updateDistance + _Physics__WEBPACK_IMPORTED_MODULE_0__["Physics"].surfaceEpsilon * 2, function (other) {
if (collider_1.body !== other && other.collider.shape && _Pair__WEBPACK_IMPORTED_MODULE_2__["Pair"].canCollide(collider_1, other.collider)) {
var hitPoint = other.collider.shape.rayCast(ray_1, updateDistance + _Physics__WEBPACK_IMPORTED_MODULE_0__["Physics"].surfaceEpsilon * 10);
if (hitPoint) {
var translate = hitPoint.sub(origin_1);
if (translate.size < minTranslate_1.size) {
minTranslate_1 = translate;
minBody_1 = other;
}
}
}
return false;
});
if (minBody_1 && _Algebra__WEBPACK_IMPORTED_MODULE_3__["Vector"].isValid(minTranslate_1)) {
var pair = new _Pair__WEBPACK_IMPORTED_MODULE_2__["Pair"](collider_1, minBody_1.collider);
if (!this_1._collisionHash[pair.id]) {
this_1._collisionHash[pair.id] = true;
this_1._collisionPairCache.push(pair);
}
// move the fast moving object to the other body
// need to push into the surface by ex.Physics.surfaceEpsilon
var shift = centerPoint.sub(furthestPoint);
collider_1.body.pos = origin_1
.add(shift)
.add(minTranslate_1)
.add(ray_1.dir.scale(2 * _Physics__WEBPACK_IMPORTED_MODULE_0__["Physics"].surfaceEpsilon));
collider_1.shape.recalc();
if (stats) {
stats.physics.fastBodyCollisions++;
}
}
}
};
var this_1 = this;
for (var _i = 0, potentialColliders_1 = potentialColliders; _i < potentialColliders_1.length; _i++) {
var collider_1 = potentialColliders_1[_i];
_loop_1(collider_1);
}
}
// return cache
return this._collisionPairCache;
};
/**
* Applies narrow phase on collision pairs to find actual area intersections
* Adds actual colliding pairs to stats' Frame data
*/
DynamicTreeCollisionBroadphase.prototype.narrowphase = function (pairs, stats, delta, strategy) {
for (var i = 0; i < pairs.length; i++) {
pairs[i].collide();
pairs[i].resolve(strategy);
if (pairs[i].collision) {
pairs[i].colliderA.body.applyMtv();
pairs[i].colliderB.body.applyMtv();
// todo still don't like this, this is a small integration step to resolve narrowphase collisions
pairs[i].colliderA.body.integrate(delta * _Physics__WEBPACK_IMPORTED_MODULE_0__["Physics"].collisionShift);
pairs[i].colliderB.body.integrate(delta * _Physics__WEBPACK_IMPORTED_MODULE_0__["Physics"].collisionShift);
}
if (stats && pairs[i].collision) {
stats.physics.collisions++;
stats.physics.collidersHash[pairs[i].id] = pairs[i];
}
}
return pairs.filter(function (p) { return p.canCollide; });
};
/**
* Perform collision resolution given a strategy (rigid body or box) and move objects out of intersect.
*/
DynamicTreeCollisionBroadphase.prototype.resolve = function (pairs, delta, strategy) {
for (var _i = 0, pairs_1 = pairs; _i < pairs_1.length; _i++) {
var pair = pairs_1[_i];
pair.resolve(strategy);
if (pair.collision) {
pair.colliderA.body.applyMtv();
pair.colliderB.body.applyMtv();
// todo still don't like this, this is a small integration step to resolve narrowphase collisions
pair.colliderA.body.integrate(delta * _Physics__WEBPACK_IMPORTED_MODULE_0__["Physics"].collisionShift);
pair.colliderB.body.integrate(delta * _Physics__WEBPACK_IMPORTED_MODULE_0__["Physics"].collisionShift);
}
}
return pairs.filter(function (p) { return p.canCollide; });
};
DynamicTreeCollisionBroadphase.prototype.runCollisionStartEnd = function (pairs) {
var currentFrameHash = {};
for (var _i = 0, pairs_2 = pairs; _i < pairs_2.length; _i++) {
var p = pairs_2[_i];
// load currentFrameHash
currentFrameHash[p.id] = p;
// find all new collisions
if (!this._lastFramePairsHash[p.id]) {
var actor1 = p.colliderA;
var actor2 = p.colliderB;
actor1.emit('collisionstart', new _Events__WEBPACK_IMPORTED_MODULE_5__["CollisionStartEvent"](actor1, actor2, p));
actor2.emit('collisionstart', new _Events__WEBPACK_IMPORTED_MODULE_5__["CollisionStartEvent"](actor2, actor1, p));
}
}
// find all old collisions
for (var _a = 0, _b = this._lastFramePairs; _a < _b.length; _a++) {
var p = _b[_a];
if (!currentFrameHash[p.id]) {
var actor1 = p.colliderA;
var actor2 = p.colliderB;
actor1.emit('collisionend', new _Events__WEBPACK_IMPORTED_MODULE_5__["CollisionEndEvent"](actor1, actor2));
actor2.emit('collisionend', new _Events__WEBPACK_IMPORTED_MODULE_5__["CollisionEndEvent"](actor2, actor1));
}
}
// reset the last frame cache
this._lastFramePairs = pairs;
this._lastFramePairsHash = currentFrameHash;
};
/**
* Update the dynamic tree positions
*/
DynamicTreeCollisionBroadphase.prototype.update = function (targets) {
var updated = 0;
var len = targets.length;
for (var i = 0; i < len; i++) {
if (this._dynamicCollisionTree.updateBody(targets[i])) {
updated++;
}
}
return updated;
};
/* istanbul ignore next */
DynamicTreeCollisionBroadphase.prototype.debugDraw = function (ctx) {
if (_Physics__WEBPACK_IMPORTED_MODULE_0__["Physics"].broadphaseDebug) {
this._dynamicCollisionTree.debugDraw(ctx);
}
if (_Physics__WEBPACK_IMPORTED_MODULE_0__["Physics"].showContacts || _Physics__WEBPACK_IMPORTED_MODULE_0__["Physics"].showCollisionNormals) {
for (var _i = 0, _a = this._collisionPairCache; _i < _a.length; _i++) {
var pair = _a[_i];
pair.debugDraw(ctx);
}
}
};
return DynamicTreeCollisionBroadphase;
}());
/***/ }),
/***/ "./Collision/Edge.ts":
/*!***************************!*\
!*** ./Collision/Edge.ts ***!
\***************************/
/*! exports provided: Edge */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Edge", function() { return Edge; });
/* harmony import */ var _BoundingBox__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./BoundingBox */ "./Collision/BoundingBox.ts");
/* harmony import */ var _CollisionJumpTable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./CollisionJumpTable */ "./Collision/CollisionJumpTable.ts");
/* harmony import */ var _Circle__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Circle */ "./Collision/Circle.ts");
/* harmony import */ var _ConvexPolygon__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./ConvexPolygon */ "./Collision/ConvexPolygon.ts");
/* harmony import */ var _Algebra__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Algebra */ "./Algebra.ts");
/* harmony import */ var _Physics__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Physics */ "./Physics.ts");
/* harmony import */ var _Drawing_Color__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Drawing/Color */ "./Drawing/Color.ts");
/* harmony import */ var _ClosestLineJumpTable__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./ClosestLineJumpTable */ "./Collision/ClosestLineJumpTable.ts");
/**
* Edge is a single line collision shape to create collisions with a single line.
*
* Example:
* [[include:EdgeShape.md]]
*/
var Edge = /** @class */ (function () {
function Edge(options) {
this.begin = options.begin || _Algebra__WEBPACK_IMPORTED_MODULE_4__["Vector"].Zero;
this.end = options.end || _Algebra__WEBPACK_IMPORTED_MODULE_4__["Vector"].Zero;
this.collider = options.collider || null;
this.offset = this.center;
}
/**
* Returns a clone of this Edge, not associated with any collider
*/
Edge.prototype.clone = function () {
return new Edge({
begin: this.begin.clone(),
end: this.end.clone(),
collider: null
});
};
Object.defineProperty(Edge.prototype, "worldPos", {
get: function () {
if (this.collider && this.collider.body) {
return this.collider.body.pos.add(this.offset);
}
return this.offset;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Edge.prototype, "center", {
/**
* Get the center of the collision area in world coordinates
*/
get: function () {
var pos = this.begin.average(this.end).add(this._getBodyPos());
return pos;
},
enumerable: false,
configurable: true
});
Edge.prototype._getBodyPos = function () {
var bodyPos = _Algebra__WEBPACK_IMPORTED_MODULE_4__["Vector"].Zero;
if (this.collider && this.collider.body) {
bodyPos = this.collider.body.pos;
}
return bodyPos;
};
Edge.prototype._getTransformedBegin = function () {
var body = this.collider ? this.collider.body : null;
var angle = body ? body.rotation : 0;
return this.begin.rotate(angle).add(this._getBodyPos());
};
Edge.prototype._getTransformedEnd = function () {
var body = this.collider ? this.collider.body : null;
var angle = body ? body.rotation : 0;
return this.end.rotate(angle).add(this._getBodyPos());
};
/**
* Returns the slope of the line in the form of a vector
*/
Edge.prototype.getSlope = function () {
var begin = this._getTransformedBegin();
var end = this._getTransformedEnd();
var distance = begin.distance(end);
return end.sub(begin).scale(1 / distance);
};
/**
* Returns the length of the line segment in pixels
*/
Edge.prototype.getLength = function () {
var begin = this._getTransformedBegin();
var end = this._getTransformedEnd();
var distance = begin.distance(end);
return distance;
};
/**
* Tests if a point is contained in this collision area
*/
Edge.prototype.contains = function () {
return false;
};
/**
* @inheritdoc
*/
Edge.prototype.rayCast = function (ray, max) {
if (max === void 0) { max = Infinity; }
var numerator = this._getTransformedBegin().sub(ray.pos);
// Test is line and ray are parallel and non intersecting
if (ray.dir.cross(this.getSlope()) === 0 && numerator.cross(ray.dir) !== 0) {
return null;
}
// Lines are parallel
var divisor = ray.dir.cross(this.getSlope());
if (divisor === 0) {
return null;
}
var t = numerator.cross(this.getSlope()) / divisor;
if (t >= 0 && t <= max) {
var u = numerator.cross(ray.dir) / divisor / this.getLength();
if (u >= 0 && u <= 1) {
return ray.getPoint(t);
}
}
return null;
};
/**
* Returns the closes line between this and another shape, from this -> shape
* @param shape
*/
Edge.prototype.getClosestLineBetween = function (shape) {
if (shape instanceof _Circle__WEBPACK_IMPORTED_MODULE_2__["Circle"]) {
return _ClosestLineJumpTable__WEBPACK_IMPORTED_MODULE_7__["ClosestLineJumpTable"].CircleEdgeClosestLine(shape, this);
}
else if (shape instanceof _ConvexPolygon__WEBPACK_IMPORTED_MODULE_3__["ConvexPolygon"]) {
return _ClosestLineJumpTable__WEBPACK_IMPORTED_MODULE_7__["ClosestLineJumpTable"].PolygonEdgeClosestLine(shape, this).flip();
}
else if (shape instanceof Edge) {
return _ClosestLineJumpTable__WEBPACK_IMPORTED_MODULE_7__["ClosestLineJumpTable"].EdgeEdgeClosestLine(this, shape);
}
else {
throw new Error("Polygon could not collide with unknown CollisionShape " + typeof shape);
}
};
/**
* @inheritdoc
*/
Edge.prototype.collide = function (shape) {
if (shape instanceof _Circle__WEBPACK_IMPORTED_MODULE_2__["Circle"]) {
return _CollisionJumpTable__WEBPACK_IMPORTED_MODULE_1__["CollisionJumpTable"].CollideCircleEdge(shape, this);
}
else if (shape instanceof _ConvexPolygon__WEBPACK_IMPORTED_MODULE_3__["ConvexPolygon"]) {
return _CollisionJumpTable__WEBPACK_IMPORTED_MODULE_1__["CollisionJumpTable"].CollidePolygonEdge(shape, this);
}
else if (shape instanceof Edge) {
return _CollisionJumpTable__WEBPACK_IMPORTED_MODULE_1__["CollisionJumpTable"].CollideEdgeEdge();
}
else {
throw new Error("Edge could not collide with unknown CollisionShape " + typeof shape);
}
};
/**
* Find the point on the shape furthest in the direction specified
*/
Edge.prototype.getFurthestPoint = function (direction) {
var transformedBegin = this._getTransformedBegin();
var transformedEnd = this._getTransformedEnd();
if (direction.dot(transformedBegin) > 0) {
return transformedBegin;
}
else {
return transformedEnd;
}
};
Edge.prototype._boundsFromBeginEnd = function (begin, end) {
return new _BoundingBox__WEBPACK_IMPORTED_MODULE_0__["BoundingBox"](Math.min(begin.x, end.x), Math.min(begin.y, end.y), Math.max(begin.x, end.x), Math.max(begin.y, end.y));
};
Object.defineProperty(Edge.prototype, "bounds", {
/**
* Get the axis aligned bounding box for the edge shape in world space
*/
get: function () {
var transformedBegin = this._getTransformedBegin();
var transformedEnd = this._getTransformedEnd();
return this._boundsFromBeginEnd(transformedBegin, transformedEnd);
},
enumerable: false,
configurable: true
});
Object.defineProperty(Edge.prototype, "localBounds", {
/**
* Get the axis aligned bounding box for the edge shape in local space
*/
get: function () {
return this._boundsFromBeginEnd(this.begin, this.end);
},
enumerable: false,
configurable: true
});
/**
* Returns this edge represented as a line in world coordinates
*/
Edge.prototype.asLine = function () {
return new _Algebra__WEBPACK_IMPORTED_MODULE_4__["Line"](this._getTransformedBegin(), this._getTransformedEnd());
};
Edge.prototype.asLocalLine = function () {
return new _Algebra__WEBPACK_IMPORTED_MODULE_4__["Line"](this.begin, this.end);
};
Object.defineProperty(Edge.prototype, "axes", {
/**
* Get the axis associated with the edge
*/
get: function () {
var e = this._getTransformedEnd().sub(this._getTransformedBegin());
var edgeNormal = e.normal();
var axes = [];
axes.push(edgeNormal);
axes.push(edgeNormal.negate());
axes.push(edgeNormal.normal());
axes.push(edgeNormal.normal().negate());
return axes;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Edge.prototype, "inertia", {
/**
* Get the moment of inertia for an edge
* https://en.wikipedia.org/wiki/List_of_moments_of_inertia
*/
get: function () {
var mass = this.collider ? this.collider.mass : _Physics__WEBPACK_IMPORTED_MODULE_5__["Physics"].defaultMass;
var length = this.end.sub(this.begin).distance() / 2;
return mass * length * length;
},
enumerable: false,
configurable: true
});
/**
* @inheritdoc
*/
Edge.prototype.recalc = function () {
// edges don't have any cached data
};
/**
* Project the edge along a specified axis
*/
Edge.prototype.project = function (axis) {
var scalars = [];
var points = [this._getTransformedBegin(), this._getTransformedEnd()];
var len = points.length;
for (var i = 0; i < len; i++) {
scalars.push(points[i].dot(axis));
}
return new _Algebra__WEBPACK_IMPORTED_MODULE_4__["Projection"](Math.min.apply(Math, scalars), Math.max.apply(Math, scalars));
};
Edge.prototype.draw = function (ctx, color, pos) {
if (color === void 0) { color = _Drawing_Color__WEBPACK_IMPORTED_MODULE_6__["Color"].Green; }
if (pos === void 0) { pos = _Algebra__WEBPACK_IMPORTED_MODULE_4__["Vector"].Zero; }
var begin = this.begin.add(pos);
var end = this.end.add(pos);
ctx.strokeStyle = color.toString();
ctx.beginPath();
ctx.moveTo(begin.x, begin.y);
ctx.lineTo(end.x, end.y);
ctx.closePath();
ctx.stroke();
};
/* istanbul ignore next */
Edge.prototype.debugDraw = function (ctx, color) {
if (color === void 0) { color = _Drawing_Color__WEBPACK_IMPORTED_MODULE_6__["Color"].Red; }
var begin = this._getTransformedBegin();
var end = this._getTransformedEnd();
ctx.strokeStyle = color.toString();
ctx.beginPath();
ctx.moveTo(begin.x, begin.y);
ctx.lineTo(end.x, end.y);
ctx.closePath();
ctx.stroke();
};
return Edge;
}());
/***/ }),
/***/ "./Collision/Index.ts":
/*!****************************!*\
!*** ./Collision/Index.ts ***!
\****************************/
/*! exports provided: Body, isCollider, Collider, BoundingBox, Circle, CollisionContact, CollisionJumpTable, ClosestLine, ClosestLineJumpTable, CollisionGroup, CollisionGroupManager, TreeNode, DynamicTree, DynamicTreeCollisionBroadphase, Edge, Pair, ConvexPolygon, Side, Shape */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _Body__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Body */ "./Collision/Body.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Body", function() { return _Body__WEBPACK_IMPORTED_MODULE_0__["Body"]; });
/* harmony import */ var _Collider__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Collider */ "./Collision/Collider.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isCollider", function() { return _Collider__WEBPACK_IMPORTED_MODULE_1__["isCollider"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Collider", function() { return _Collider__WEBPACK_IMPORTED_MODULE_1__["Collider"]; });
/* harmony import */ var _BoundingBox__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./BoundingBox */ "./Collision/BoundingBox.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoundingBox", function() { return _BoundingBox__WEBPACK_IMPORTED_MODULE_2__["BoundingBox"]; });
/* harmony import */ var _Circle__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Circle */ "./Collision/Circle.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Circle", function() { return _Circle__WEBPACK_IMPORTED_MODULE_3__["Circle"]; });
/* harmony import */ var _CollisionContact__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./CollisionContact */ "./Collision/CollisionContact.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CollisionContact", function() { return _CollisionContact__WEBPACK_IMPORTED_MODULE_4__["CollisionContact"]; });
/* harmony import */ var _CollisionJumpTable__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./CollisionJumpTable */ "./Collision/CollisionJumpTable.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CollisionJumpTable", function() { return _CollisionJumpTable__WEBPACK_IMPORTED_MODULE_5__["CollisionJumpTable"]; });
/* harmony import */ var _ClosestLineJumpTable__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./ClosestLineJumpTable */ "./Collision/ClosestLineJumpTable.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ClosestLine", function() { return _ClosestLineJumpTable__WEBPACK_IMPORTED_MODULE_6__["ClosestLine"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ClosestLineJumpTable", function() { return _ClosestLineJumpTable__WEBPACK_IMPORTED_MODULE_6__["ClosestLineJumpTable"]; });
/* harmony import */ var _CollisionGroup__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./CollisionGroup */ "./Collision/CollisionGroup.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CollisionGroup", function() { return _CollisionGroup__WEBPACK_IMPORTED_MODULE_7__["CollisionGroup"]; });
/* harmony import */ var _CollisionGroupManager__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./CollisionGroupManager */ "./Collision/CollisionGroupManager.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CollisionGroupManager", function() { return _CollisionGroupManager__WEBPACK_IMPORTED_MODULE_8__["CollisionGroupManager"]; });
/* harmony import */ var _DynamicTree__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./DynamicTree */ "./Collision/DynamicTree.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TreeNode", function() { return _DynamicTree__WEBPACK_IMPORTED_MODULE_9__["TreeNode"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DynamicTree", function() { return _DynamicTree__WEBPACK_IMPORTED_MODULE_9__["DynamicTree"]; });
/* harmony import */ var _DynamicTreeCollisionBroadphase__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./DynamicTreeCollisionBroadphase */ "./Collision/DynamicTreeCollisionBroadphase.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DynamicTreeCollisionBroadphase", function() { return _DynamicTreeCollisionBroadphase__WEBPACK_IMPORTED_MODULE_10__["DynamicTreeCollisionBroadphase"]; });
/* harmony import */ var _Edge__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./Edge */ "./Collision/Edge.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Edge", function() { return _Edge__WEBPACK_IMPORTED_MODULE_11__["Edge"]; });
/* harmony import */ var _CollisionShape__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./CollisionShape */ "./Collision/CollisionShape.ts");
/* empty/unused harmony star reexport *//* harmony import */ var _CollisionResolver__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./CollisionResolver */ "./Collision/CollisionResolver.ts");
/* empty/unused harmony star reexport *//* harmony import */ var _Physics__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./Physics */ "./Collision/Physics.ts");
/* empty/unused harmony star reexport *//* harmony import */ var _Pair__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./Pair */ "./Collision/Pair.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Pair", function() { return _Pair__WEBPACK_IMPORTED_MODULE_15__["Pair"]; });
/* harmony import */ var _ConvexPolygon__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./ConvexPolygon */ "./Collision/ConvexPolygon.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ConvexPolygon", function() { return _ConvexPolygon__WEBPACK_IMPORTED_MODULE_16__["ConvexPolygon"]; });
/* harmony import */ var _Side__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./Side */ "./Collision/Side.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Side", function() { return _Side__WEBPACK_IMPORTED_MODULE_17__["Side"]; });
/* harmony import */ var _Shape__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./Shape */ "./Collision/Shape.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Shape", function() { return _Shape__WEBPACK_IMPORTED_MODULE_18__["Shape"]; });
/***/ }),
/***/ "./Collision/Pair.ts":
/*!***************************!*\
!*** ./Collision/Pair.ts ***!
\***************************/
/*! exports provided: Pair */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Pair", function() { return Pair; });
/* harmony import */ var _Physics__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./../Physics */ "./Physics.ts");
/* harmony import */ var _Drawing_Color__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./../Drawing/Color */ "./Drawing/Color.ts");
/* harmony import */ var _Util_DrawUtil__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Util/DrawUtil */ "./Util/DrawUtil.ts");
/* harmony import */ var _CollisionType__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./CollisionType */ "./Collision/CollisionType.ts");
/**
* Models a potential collision between 2 bodies
*/
var Pair = /** @class */ (function () {
function Pair(colliderA, colliderB) {
this.colliderA = colliderA;
this.colliderB = colliderB;
this.id = null;
this.collision = null;
this.id = Pair.calculatePairHash(colliderA, colliderB);
}
Pair.canCollide = function (colliderA, colliderB) {
// If both are in the same collision group short circuit
if (!colliderA.group.canCollide(colliderB.group)) {
return false;
}
// if both are fixed short circuit
if (colliderA.type === _CollisionType__WEBPACK_IMPORTED_MODULE_3__["CollisionType"].Fixed && colliderB.type === _CollisionType__WEBPACK_IMPORTED_MODULE_3__["CollisionType"].Fixed) {
return false;
}
// if the either is prevent collision short circuit
if (colliderB.type === _CollisionType__WEBPACK_IMPORTED_MODULE_3__["CollisionType"].PreventCollision || colliderA.type === _CollisionType__WEBPACK_IMPORTED_MODULE_3__["CollisionType"].PreventCollision) {
return false;
}
// if either is dead short circuit
if (!colliderA.active || !colliderB.active) {
return false;
}
return true;
};
Object.defineProperty(Pair.prototype, "canCollide", {
/**
* Returns whether or not it is possible for the pairs to collide
*/
get: function () {
var actorA = this.colliderA;
var actorB = this.colliderB;
return Pair.canCollide(actorA, actorB);
},
enumerable: false,
configurable: true
});
/**
* Runs the collision intersection logic on the members of this pair
*/
Pair.prototype.collide = function () {
this.collision = this.colliderA.collide(this.colliderB);
};
/**
* Resolves the collision body position and velocity if a collision occurred
*/
Pair.prototype.resolve = function (strategy) {
if (this.collision) {
this.collision.resolve(strategy);
}
};
/**
* Calculates the unique pair hash id for this collision pair
*/
Pair.calculatePairHash = function (colliderA, colliderB) {
if (colliderA.id < colliderB.id) {
return "#" + colliderA.id + "+" + colliderB.id;
}
else {
return "#" + colliderB.id + "+" + colliderA.id;
}
};
/* istanbul ignore next */
Pair.prototype.debugDraw = function (ctx) {
if (this.collision) {
if (_Physics__WEBPACK_IMPORTED_MODULE_0__["Physics"].showContacts) {
_Util_DrawUtil__WEBPACK_IMPORTED_MODULE_2__["point"](ctx, _Drawing_Color__WEBPACK_IMPORTED_MODULE_1__["Color"].Red, this.collision.point);
}
if (_Physics__WEBPACK_IMPORTED_MODULE_0__["Physics"].showCollisionNormals) {
_Util_DrawUtil__WEBPACK_IMPORTED_MODULE_2__["vector"](ctx, _Drawing_Color__WEBPACK_IMPORTED_MODULE_1__["Color"].Cyan, this.collision.point, this.collision.normal, 30);
}
}
};
return Pair;
}());
/***/ }),
/***/ "./Collision/Physics.ts":
/*!******************************!*\
!*** ./Collision/Physics.ts ***!
\******************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/***/ }),
/***/ "./Collision/Shape.ts":
/*!****************************!*\
!*** ./Collision/Shape.ts ***!
\****************************/
/*! exports provided: Shape */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Shape", function() { return Shape; });
/* harmony import */ var _ConvexPolygon__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ConvexPolygon */ "./Collision/ConvexPolygon.ts");
/* harmony import */ var _Circle__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Circle */ "./Collision/Circle.ts");
/* harmony import */ var _Edge__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Edge */ "./Collision/Edge.ts");
/* harmony import */ var _BoundingBox__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./BoundingBox */ "./Collision/BoundingBox.ts");
/* harmony import */ var _Algebra__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Algebra */ "./Algebra.ts");
/**
* Excalibur shape helper for defining collision shapes quickly
*/
var Shape = /** @class */ (function () {
function Shape() {
}
/**
* Creates a box collision shape, under the hood defines a [[ConvexPolygon]] collision shape
* @param width Width of the box
* @param height Height of the box
* @param anchor Anchor of the box (default (.5, .5)) which positions the box relative to the center of the collider's position
* @param offset Optional offset relative to the collider in local coordinates
*/
Shape.Box = function (width, height, anchor, offset) {
if (anchor === void 0) { anchor = _Algebra__WEBPACK_IMPORTED_MODULE_4__["Vector"].Half; }
if (offset === void 0) { offset = _Algebra__WEBPACK_IMPORTED_MODULE_4__["Vector"].Zero; }
return new _ConvexPolygon__WEBPACK_IMPORTED_MODULE_0__["ConvexPolygon"]({
points: new _BoundingBox__WEBPACK_IMPORTED_MODULE_3__["BoundingBox"](-width * anchor.x, -height * anchor.y, width - width * anchor.x, height - height * anchor.y).getPoints(),
offset: offset
});
};
/**
* Creates a new [[ConvexPolygon|arbitrary polygon]] collision shape
* @param points Points specified in counter clockwise
* @param clockwiseWinding Optionally changed the winding of points, by default false meaning counter-clockwise winding.
* @param offset Optional offset relative to the collider in local coordinates
*/
Shape.Polygon = function (points, clockwiseWinding, offset) {
if (clockwiseWinding === void 0) { clockwiseWinding = false; }
if (offset === void 0) { offset = _Algebra__WEBPACK_IMPORTED_MODULE_4__["Vector"].Zero; }
return new _ConvexPolygon__WEBPACK_IMPORTED_MODULE_0__["ConvexPolygon"]({
points: points,
offset: offset,
clockwiseWinding: clockwiseWinding
});
};
/**
* Creates a new [[circle|Circle]] collision shape
* @param radius Radius of the circle shape
* @param offset Optional offset relative to the collider in local coordinates
*/
Shape.Circle = function (radius, offset) {
if (offset === void 0) { offset = _Algebra__WEBPACK_IMPORTED_MODULE_4__["Vector"].Zero; }
return new _Circle__WEBPACK_IMPORTED_MODULE_1__["Circle"]({
radius: radius,
offset: offset
});
};
/**
* Creates a new [[Edge|edge]] collision shape
* @param begin Beginning of the edge in local coordinates to the collider
* @param end Ending of the edge in local coordinates to the collider
*/
Shape.Edge = function (begin, end) {
return new _Edge__WEBPACK_IMPORTED_MODULE_2__["Edge"]({
begin: begin,
end: end
});
};
return Shape;
}());
/***/ }),
/***/ "./Collision/Side.ts":
/*!***************************!*\
!*** ./Collision/Side.ts ***!
\***************************/
/*! exports provided: Side */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Side", function() { return Side; });
/**
* An enum that describes the sides of an Actor for collision
*/
var Side;
(function (Side) {
Side["None"] = "None";
Side["Top"] = "Top";
Side["Bottom"] = "Bottom";
Side["Left"] = "Left";
Side["Right"] = "Right";
})(Side || (Side = {}));
/***/ }),
/***/ "./Configurable.ts":
/*!*************************!*\
!*** ./Configurable.ts ***!
\*************************/
/*! exports provided: Configurable */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Configurable", function() { return Configurable; });
var __extends = (undefined && undefined.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
function Configurable(base) {
return /** @class */ (function (_super) {
__extends(class_1, _super);
function class_1() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var _this = _super.apply(this, args) || this;
//get the number of arguments that aren't undefined. TS passes a value to all parameters
//of whatever ctor is the implementation, so args.length doesn't work here.
var size = args.filter(function (value) {
return value !== undefined;
}).length;
if (size === 1 && args[0] && typeof args[0] === 'object' && !(args[0] instanceof Array)) {
_this.assign(args[0]);
}
return _this;
}
class_1.prototype.assign = function (props) {
//set the value of every property that was passed in,
//if the constructor previously set this value, it will be overridden here
for (var k in props) {
// eslint-disable-next-line
if (typeof this[k] !== 'function') {
// eslint-disable-next-line
this[k] = props[k];
}
}
};
return class_1;
}(base));
}
/***/ }),
/***/ "./Debug.ts":
/*!******************!*\
!*** ./Debug.ts ***!
\******************/
/*! exports provided: Debug, FrameStats, PhysicsStats */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Debug", function() { return Debug; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FrameStats", function() { return FrameStats; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PhysicsStats", function() { return PhysicsStats; });
/* harmony import */ var _DebugFlags__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./DebugFlags */ "./DebugFlags.ts");
/**
* Debug statistics and flags for Excalibur. If polling these values, it would be
* best to do so on the `postupdate` event for [[Engine]], after all values have been
* updated during a frame.
*/
var Debug = /** @class */ (function () {
function Debug(engine) {
/**
* Performance statistics
*/
this.stats = {
/**
* Current frame statistics. Engine reuses this instance, use [[FrameStats.clone]] to copy frame stats.
* Best accessed on [[postframe]] event. See [[FrameStats]]
*/
currFrame: new FrameStats(),
/**
* Previous frame statistics. Engine reuses this instance, use [[FrameStats.clone]] to copy frame stats.
* Best accessed on [[preframe]] event. Best inspected on engine event `preframe`. See [[FrameStats]]
*/
prevFrame: new FrameStats()
};
this._engine = engine;
this.colorBlindMode = new _DebugFlags__WEBPACK_IMPORTED_MODULE_0__["ColorBlindFlags"](this._engine);
}
return Debug;
}());
/**
* Implementation of a frame's stats. Meant to have values copied via [[FrameStats.reset]], avoid
* creating instances of this every frame.
*/
var FrameStats = /** @class */ (function () {
function FrameStats() {
this._id = 0;
this._delta = 0;
this._fps = 0;
this._actorStats = {
alive: 0,
killed: 0,
ui: 0,
get remaining() {
return this.alive - this.killed;
},
get total() {
return this.remaining + this.ui;
}
};
this._durationStats = {
update: 0,
draw: 0,
get total() {
return this.update + this.draw;
}
};
this._physicsStats = new PhysicsStats();
}
/**
* Zero out values or clone other IFrameStat stats. Allows instance reuse.
*
* @param [otherStats] Optional stats to clone
*/
FrameStats.prototype.reset = function (otherStats) {
if (otherStats) {
this.id = otherStats.id;
this.delta = otherStats.delta;
this.fps = otherStats.fps;
this.actors.alive = otherStats.actors.alive;
this.actors.killed = otherStats.actors.killed;
this.actors.ui = otherStats.actors.ui;
this.duration.update = otherStats.duration.update;
this.duration.draw = otherStats.duration.draw;
this._physicsStats.reset(otherStats.physics);
}
else {
this.id = this.delta = this.fps = 0;
this.actors.alive = this.actors.killed = this.actors.ui = 0;
this.duration.update = this.duration.draw = 0;
this._physicsStats.reset();
}
};
/**
* Provides a clone of this instance.
*/
FrameStats.prototype.clone = function () {
var fs = new FrameStats();
fs.reset(this);
return fs;
};
Object.defineProperty(FrameStats.prototype, "id", {
/**
* Gets the frame's id
*/
get: function () {
return this._id;
},
/**
* Sets the frame's id
*/
set: function (value) {
this._id = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(FrameStats.prototype, "delta", {
/**
* Gets the frame's delta (time since last frame)
*/
get: function () {
return this._delta;
},
/**
* Sets the frame's delta (time since last frame). Internal use only.
* @internal
*/
set: function (value) {
this._delta = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(FrameStats.prototype, "fps", {
/**
* Gets the frame's frames-per-second (FPS)
*/
get: function () {
return this._fps;
},
/**
* Sets the frame's frames-per-second (FPS). Internal use only.
* @internal
*/
set: function (value) {
this._fps = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(FrameStats.prototype, "actors", {
/**
* Gets the frame's actor statistics
*/
get: function () {
return this._actorStats;
},
enumerable: false,
configurable: true
});
Object.defineProperty(FrameStats.prototype, "duration", {
/**
* Gets the frame's duration statistics
*/
get: function () {
return this._durationStats;
},
enumerable: false,
configurable: true
});
Object.defineProperty(FrameStats.prototype, "physics", {
/**
* Gets the frame's physics statistics
*/
get: function () {
return this._physicsStats;
},
enumerable: false,
configurable: true
});
return FrameStats;
}());
var PhysicsStats = /** @class */ (function () {
function PhysicsStats() {
this._pairs = 0;
this._collisions = 0;
this._collidersHash = {};
this._fastBodies = 0;
this._fastBodyCollisions = 0;
this._broadphase = 0;
this._narrowphase = 0;
}
/**
* Zero out values or clone other IPhysicsStats stats. Allows instance reuse.
*
* @param [otherStats] Optional stats to clone
*/
PhysicsStats.prototype.reset = function (otherStats) {
if (otherStats) {
this.pairs = otherStats.pairs;
this.collisions = otherStats.collisions;
this.collidersHash = otherStats.collidersHash;
this.fastBodies = otherStats.fastBodies;
this.fastBodyCollisions = otherStats.fastBodyCollisions;
this.broadphase = otherStats.broadphase;
this.narrowphase = otherStats.narrowphase;
}
else {
this.pairs = this.collisions = this.fastBodies = 0;
this.fastBodyCollisions = this.broadphase = this.narrowphase = 0;
this.collidersHash = {};
}
};
/**
* Provides a clone of this instance.
*/
PhysicsStats.prototype.clone = function () {
var ps = new PhysicsStats();
ps.reset(this);
return ps;
};
Object.defineProperty(PhysicsStats.prototype, "pairs", {
get: function () {
return this._pairs;
},
set: function (value) {
this._pairs = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PhysicsStats.prototype, "collisions", {
get: function () {
return this._collisions;
},
set: function (value) {
this._collisions = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PhysicsStats.prototype, "collidersHash", {
get: function () {
return this._collidersHash;
},
set: function (colliders) {
this._collidersHash = colliders;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PhysicsStats.prototype, "fastBodies", {
get: function () {
return this._fastBodies;
},
set: function (value) {
this._fastBodies = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PhysicsStats.prototype, "fastBodyCollisions", {
get: function () {
return this._fastBodyCollisions;
},
set: function (value) {
this._fastBodyCollisions = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PhysicsStats.prototype, "broadphase", {
get: function () {
return this._broadphase;
},
set: function (value) {
this._broadphase = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PhysicsStats.prototype, "narrowphase", {
get: function () {
return this._narrowphase;
},
set: function (value) {
this._narrowphase = value;
},
enumerable: false,
configurable: true
});
return PhysicsStats;
}());
/***/ }),
/***/ "./DebugFlags.ts":
/*!***********************!*\
!*** ./DebugFlags.ts ***!
\***********************/
/*! exports provided: ColorBlindFlags */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorBlindFlags", function() { return ColorBlindFlags; });
/* harmony import */ var _PostProcessing_Index__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./PostProcessing/Index */ "./PostProcessing/Index.ts");
var ColorBlindFlags = /** @class */ (function () {
function ColorBlindFlags(engine) {
this._engine = engine;
}
ColorBlindFlags.prototype.correct = function (colorBlindness) {
this._engine.postProcessors.push(new _PostProcessing_Index__WEBPACK_IMPORTED_MODULE_0__["ColorBlindCorrector"](this._engine, false, colorBlindness));
};
ColorBlindFlags.prototype.simulate = function (colorBlindness) {
this._engine.postProcessors.push(new _PostProcessing_Index__WEBPACK_IMPORTED_MODULE_0__["ColorBlindCorrector"](this._engine, true, colorBlindness));
};
return ColorBlindFlags;
}());
/***/ }),
/***/ "./Drawing/Animation.ts":
/*!******************************!*\
!*** ./Drawing/Animation.ts ***!
\******************************/
/*! exports provided: AnimationImpl, Animation */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnimationImpl", function() { return AnimationImpl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Animation", function() { return Animation; });
/* harmony import */ var _SpriteEffects__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./SpriteEffects */ "./Drawing/SpriteEffects.ts");
/* harmony import */ var _Algebra__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Algebra */ "./Algebra.ts");
/* harmony import */ var _Engine__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Engine */ "./Engine.ts");
/* harmony import */ var _Util_Util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Util/Util */ "./Util/Util.ts");
/* harmony import */ var _Configurable__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Configurable */ "./Configurable.ts");
var __extends = (undefined && undefined.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __assign = (undefined && undefined.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
/**
* @hidden
*/
var AnimationImpl = /** @class */ (function () {
/**
* Typically you will use a [[SpriteSheet]] to generate an [[Animation]].
*
* @param engine Reference to the current game engine
* @param images An array of sprites to create the frames for the animation
* @param speed The number in milliseconds to display each frame in the animation
* @param loop Indicates whether the animation should loop after it is completed
*/
function AnimationImpl(engineOrConfig, sprites, speed, loop) {
/**
* The sprite frames to play, in order. See [[SpriteSheet.getAnimationForAll]] to quickly
* generate an [[Animation]].
*/
this.sprites = [];
/**
* Current frame index being shown
*/
this.currentFrame = 0;
this._timeLeftInFrame = 0;
this._idempotencyToken = -1;
this.anchor = _Algebra__WEBPACK_IMPORTED_MODULE_1__["Vector"].Zero;
this.rotation = 0.0;
this.scale = _Algebra__WEBPACK_IMPORTED_MODULE_1__["Vector"].One;
/**
* Indicates whether the animation should loop after it is completed
*/
this.loop = true;
/**
* Indicates the frame index the animation should freeze on for a non-looping
* animation. By default it is the last frame.
*/
this.freezeFrame = -1;
/**
* Flip each frame vertically. Sets [[Sprite.flipVertical]].
*/
this.flipVertical = false;
/**
* Flip each frame horizontally. Sets [[Sprite.flipHorizontal]].
*/
this.flipHorizontal = false;
this.drawWidth = 0;
this.drawHeight = 0;
this.width = 0;
this.height = 0;
this._opacity = 1;
var engine = engineOrConfig;
if (engineOrConfig && !(engineOrConfig instanceof _Engine__WEBPACK_IMPORTED_MODULE_2__["Engine"])) {
var config = engineOrConfig;
engine = config.engine;
sprites = config.sprites;
speed = config.speed;
loop = config.loop;
}
this.sprites = sprites;
this.speed = speed;
this._engine = engine;
this._timeLeftInFrame = this.speed;
if (loop != null) {
this.loop = loop;
}
if (sprites && sprites[0]) {
this.drawHeight = sprites[0] ? sprites[0].drawHeight : 0;
this.drawWidth = sprites[0] ? sprites[0].drawWidth : 0;
this.width = sprites[0] ? sprites[0].width : 0;
this.height = sprites[0] ? sprites[0].height : 0;
this.freezeFrame = sprites.length - 1;
}
}
/**
* Applies the opacity effect to a sprite, setting the alpha of all pixels to a given value
*/
AnimationImpl.prototype.opacity = function (value) {
this._opacity = value;
};
/**
* Applies the grayscale effect to a sprite, removing color information.
*/
AnimationImpl.prototype.grayscale = function () {
this.addEffect(new _SpriteEffects__WEBPACK_IMPORTED_MODULE_0__["Grayscale"]());
};
/**
* Applies the invert effect to a sprite, inverting the pixel colors.
*/
AnimationImpl.prototype.invert = function () {
this.addEffect(new _SpriteEffects__WEBPACK_IMPORTED_MODULE_0__["Invert"]());
};
/**
* Applies the fill effect to a sprite, changing the color channels of all non-transparent pixels to match a given color
*/
AnimationImpl.prototype.fill = function (color) {
this.addEffect(new _SpriteEffects__WEBPACK_IMPORTED_MODULE_0__["Fill"](color));
};
/**
* Applies the colorize effect to a sprite, changing the color channels of all pixels to be the average of the original color and the
* provided color.
*/
AnimationImpl.prototype.colorize = function (color) {
this.addEffect(new _SpriteEffects__WEBPACK_IMPORTED_MODULE_0__["Colorize"](color));
};
/**
* Applies the lighten effect to a sprite, changes the lightness of the color according to hsl
*/
AnimationImpl.prototype.lighten = function (factor) {
if (factor === void 0) { factor = 0.1; }
this.addEffect(new _SpriteEffects__WEBPACK_IMPORTED_MODULE_0__["Lighten"](factor));
};
/**
* Applies the darken effect to a sprite, changes the darkness of the color according to hsl
*/
AnimationImpl.prototype.darken = function (factor) {
if (factor === void 0) { factor = 0.1; }
this.addEffect(new _SpriteEffects__WEBPACK_IMPORTED_MODULE_0__["Darken"](factor));
};
/**
* Applies the saturate effect to a sprite, saturates the color according to hsl
*/
AnimationImpl.prototype.saturate = function (factor) {
if (factor === void 0) { factor = 0.1; }
this.addEffect(new _SpriteEffects__WEBPACK_IMPORTED_MODULE_0__["Saturate"](factor));
};
/**
* Applies the desaturate effect to a sprite, desaturates the color according to hsl
*/
AnimationImpl.prototype.desaturate = function (factor) {
if (factor === void 0) { factor = 0.1; }
this.addEffect(new _SpriteEffects__WEBPACK_IMPORTED_MODULE_0__["Desaturate"](factor));
};
/**
* Add a [[SpriteEffect]] manually
*/
AnimationImpl.prototype.addEffect = function (effect) {
for (var i in this.sprites) {
this.sprites[i].addEffect(effect);
}
};
AnimationImpl.prototype.removeEffect = function (param) {
for (var i in this.sprites) {
this.sprites[i].removeEffect(param);
}
};
/**
* Clear all sprite effects
*/
AnimationImpl.prototype.clearEffects = function () {
for (var i in this.sprites) {
this.sprites[i].clearEffects();
}
};
AnimationImpl.prototype._setAnchor = function (point) {
//if (!this.anchor.equals(point)) {
for (var i in this.sprites) {
this.sprites[i].anchor.setTo(point.x, point.y);
}
//}
};
AnimationImpl.prototype._setRotation = function (radians) {
//if (this.rotation !== radians) {
for (var i in this.sprites) {
this.sprites[i].rotation = radians;
}
//}
};
AnimationImpl.prototype._setScale = function (scale) {
//if (!this.scale.equals(scale)) {
for (var i in this.sprites) {
this.sprites[i].scale = scale;
}
//}
};
/**
* Resets the animation to first frame.
*/
AnimationImpl.prototype.reset = function () {
this.currentFrame = 0;
};
/**
* Indicates whether the animation is complete, animations that loop are never complete.
*/
AnimationImpl.prototype.isDone = function () {
return !this.loop && this.currentFrame >= this.sprites.length;
};
/**
* Not meant to be called by game developers. Ticks the animation forward internally and
* calculates whether to change to the frame.
* @internal
*/
AnimationImpl.prototype.tick = function (elapsed, idempotencyToken) {
if (this._idempotencyToken === idempotencyToken) {
return;
}
this._idempotencyToken = idempotencyToken;
this._timeLeftInFrame -= elapsed;
if (this._timeLeftInFrame <= 0) {
this.currentFrame = this.loop ? (this.currentFrame + 1) % this.sprites.length : this.currentFrame + 1;
this._timeLeftInFrame = this.speed;
}
this._updateValues();
var current = this.sprites[this.currentFrame];
if (current) {
this.width = current.width;
this.height = current.height;
this.drawWidth = current.drawWidth;
this.drawHeight = current.drawHeight;
}
};
AnimationImpl.prototype._updateValues = function () {
this._setAnchor(this.anchor);
this._setRotation(this.rotation);
this._setScale(this.scale);
};
/**
* Skips ahead a specified number of frames in the animation
* @param frames Frames to skip ahead
*/
AnimationImpl.prototype.skip = function (frames) {
this.currentFrame = (this.currentFrame + frames) % this.sprites.length;
};
AnimationImpl.prototype.draw = function (ctxOrOptions, x, y) {
if (ctxOrOptions instanceof CanvasRenderingContext2D) {
this._drawWithOptions({ ctx: ctxOrOptions, x: x, y: y });
}
else {
this._drawWithOptions(ctxOrOptions);
}
};
AnimationImpl.prototype._drawWithOptions = function (options) {
var _a, _b, _c, _d, _e, _f, _g;
var animOptions = __assign(__assign({}, options), { rotation: (_a = options.rotation) !== null && _a !== void 0 ? _a : this.rotation, drawWidth: (_b = options.drawWidth) !== null && _b !== void 0 ? _b : this.drawWidth, drawHeight: (_c = options.drawHeight) !== null && _c !== void 0 ? _c : this.drawHeight, flipHorizontal: (_d = options.flipHorizontal) !== null && _d !== void 0 ? _d : this.flipHorizontal, flipVertical: (_e = options.flipVertical) !== null && _e !== void 0 ? _e : this.flipVertical, anchor: (_f = options.anchor) !== null && _f !== void 0 ? _f : this.anchor, opacity: (_g = options.opacity) !== null && _g !== void 0 ? _g : this._opacity });
this._updateValues();
var currSprite;
if (this.currentFrame < this.sprites.length) {
currSprite = this.sprites[this.currentFrame];
currSprite.draw(animOptions);
}
if (this.freezeFrame !== -1 && this.currentFrame >= this.sprites.length) {
currSprite = this.sprites[_Util_Util__WEBPACK_IMPORTED_MODULE_3__["clamp"](this.freezeFrame, 0, this.sprites.length - 1)];
currSprite.draw(animOptions);
}
// add the calculated width
if (currSprite) {
this.drawWidth = currSprite.drawWidth;
this.drawHeight = currSprite.drawHeight;
}
};
/**
* Plays an animation at an arbitrary location in the game.
* @param x The x position in the game to play
* @param y The y position in the game to play
*/
AnimationImpl.prototype.play = function (x, y) {
this.reset();
this._engine.playAnimation(this, x, y);
};
return AnimationImpl;
}());
/**
* Animations allow you to display a series of images one after another,
* creating the illusion of change. Generally these images will come from a [[SpriteSheet]] source.
*
* [[include:Animations.md]]
*/
var Animation = /** @class */ (function (_super) {
__extends(Animation, _super);
function Animation(engineOrConfig, images, speed, loop) {
return _super.call(this, engineOrConfig, images, speed, loop) || this;
}
return Animation;
}(Object(_Configurable__WEBPACK_IMPORTED_MODULE_4__["Configurable"])(AnimationImpl)));
/***/ }),
/***/ "./Drawing/Color.ts":
/*!**************************!*\
!*** ./Drawing/Color.ts ***!
\**************************/
/*! exports provided: Color */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Color", function() { return Color; });
/* harmony import */ var _Util_Decorators__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Util/Decorators */ "./Util/Decorators.ts");
var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
/**
* Provides standard colors (e.g. [[Color.Black]])
* but you can also create custom colors using RGB, HSL, or Hex. Also provides
* useful color operations like [[Color.lighten]], [[Color.darken]], and more.
*
* [[include:Colors.md]]
*/
var Color = /** @class */ (function () {
/**
* Creates a new instance of Color from an r, g, b, a
*
* @param r The red component of color (0-255)
* @param g The green component of color (0-255)
* @param b The blue component of color (0-255)
* @param a The alpha component of color (0-1.0)
*/
function Color(r, g, b, a) {
this.r = r;
this.g = g;
this.b = b;
this.a = a != null ? a : 1;
}
/**
* Creates a new instance of Color from an r, g, b, a
*
* @param r The red component of color (0-255)
* @param g The green component of color (0-255)
* @param b The blue component of color (0-255)
* @param a The alpha component of color (0-1.0)
*/
Color.fromRGB = function (r, g, b, a) {
return new Color(r, g, b, a);
};
/**
* Creates a new instance of Color from a hex string
*
* @param hex CSS color string of the form #ffffff, the alpha component is optional
*/
Color.fromHex = function (hex) {
var hexRegEx = /^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})?$/i;
var match = null;
if ((match = hex.match(hexRegEx))) {
var r = parseInt(match[1], 16);
var g = parseInt(match[2], 16);
var b = parseInt(match[3], 16);
var a = 1;
if (match[4]) {
a = parseInt(match[4], 16) / 255;
}
return new Color(r, g, b, a);
}
else {
throw new Error('Invalid hex string: ' + hex);
}
};
/**
* Creates a new instance of Color from hsla values
*
* @param h Hue is represented [0-1]
* @param s Saturation is represented [0-1]
* @param l Luminance is represented [0-1]
* @param a Alpha is represented [0-1]
*/
Color.fromHSL = function (h, s, l, a) {
if (a === void 0) { a = 1.0; }
var temp = new HSLColor(h, s, l, a);
return temp.toRGBA();
};
/**
* Lightens the current color by a specified amount
*
* @param factor The amount to lighten by [0-1]
*/
Color.prototype.lighten = function (factor) {
if (factor === void 0) { factor = 0.1; }
var temp = HSLColor.fromRGBA(this.r, this.g, this.b, this.a);
temp.l += (1 - temp.l) * factor;
return temp.toRGBA();
};
/**
* Darkens the current color by a specified amount
*
* @param factor The amount to darken by [0-1]
*/
Color.prototype.darken = function (factor) {
if (factor === void 0) { factor = 0.1; }
var temp = HSLColor.fromRGBA(this.r, this.g, this.b, this.a);
temp.l -= temp.l * factor;
return temp.toRGBA();
};
/**
* Saturates the current color by a specified amount
*
* @param factor The amount to saturate by [0-1]
*/
Color.prototype.saturate = function (factor) {
if (factor === void 0) { factor = 0.1; }
var temp = HSLColor.fromRGBA(this.r, this.g, this.b, this.a);
temp.s += temp.s * factor;
return temp.toRGBA();
};
/**
* Desaturates the current color by a specified amount
*
* @param factor The amount to desaturate by [0-1]
*/
Color.prototype.desaturate = function (factor) {
if (factor === void 0) { factor = 0.1; }
var temp = HSLColor.fromRGBA(this.r, this.g, this.b, this.a);
temp.s -= temp.s * factor;
return temp.toRGBA();
};
/**
* Multiplies a color by another, results in a darker color
*
* @param color The other color
*/
Color.prototype.multiply = function (color) {
var newR = (((color.r / 255) * this.r) / 255) * 255;
var newG = (((color.g / 255) * this.g) / 255) * 255;
var newB = (((color.b / 255) * this.b) / 255) * 255;
var newA = color.a * this.a;
return new Color(newR, newG, newB, newA);
};
/**
* Multiplies a color by another, results in a darker color
* @param color
* @obsolete Alias for incorrect spelling used in older versions, use multiply instead, will be removed in v0.25.0
*/
Color.prototype.mulitiply = function (color) {
return this.multiply(color);
};
/**
* Screens a color by another, results in a lighter color
*
* @param color The other color
*/
Color.prototype.screen = function (color) {
var color1 = color.invert();
var color2 = color.invert();
return color1.multiply(color2).invert();
};
/**
* Inverts the current color
*/
Color.prototype.invert = function () {
return new Color(255 - this.r, 255 - this.g, 255 - this.b, 1.0 - this.a);
};
/**
* Averages the current color with another
*
* @param color The other color
*/
Color.prototype.average = function (color) {
var newR = (color.r + this.r) / 2;
var newG = (color.g + this.g) / 2;
var newB = (color.b + this.b) / 2;
var newA = (color.a + this.a) / 2;
return new Color(newR, newG, newB, newA);
};
/**
* Returns a CSS string representation of a color.
*
* @param format Color representation, accepts: rgb, hsl, or hex
*/
Color.prototype.toString = function (format) {
if (format === void 0) { format = 'rgb'; }
switch (format) {
case 'rgb':
return this.toRGBA();
case 'hsl':
return this.toHSLA();
case 'hex':
return this.toHex();
default:
throw new Error('Invalid Color format');
}
};
/**
* Returns Hex Value of a color component
* @param c color component
* @see https://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
*/
Color.prototype._componentToHex = function (c) {
var hex = c.toString(16);
return hex.length === 1 ? '0' + hex : hex;
};
/**
* Return Hex representation of a color.
*/
Color.prototype.toHex = function () {
return '#' + this._componentToHex(this.r) + this._componentToHex(this.g) + this._componentToHex(this.b);
};
/**
* Return RGBA representation of a color.
*/
Color.prototype.toRGBA = function () {
var result = String(this.r.toFixed(0)) + ', ' + String(this.g.toFixed(0)) + ', ' + String(this.b.toFixed(0));
if (this.a !== undefined || this.a !== null) {
return 'rgba(' + result + ', ' + String(this.a) + ')';
}
return 'rgb(' + result + ')';
};
/**
* Return HSLA representation of a color.
*/
Color.prototype.toHSLA = function () {
return HSLColor.fromRGBA(this.r, this.g, this.b, this.a).toString();
};
/**
* Returns a CSS string representation of a color.
*/
Color.prototype.fillStyle = function () {
return this.toString();
};
/**
* Returns a clone of the current color.
*/
Color.prototype.clone = function () {
return new Color(this.r, this.g, this.b, this.a);
};
Object.defineProperty(Color, "Black", {
/**
* Black (#000000)
*/
get: function () {
return Color.fromHex('#000000');
},
enumerable: false,
configurable: true
});
Object.defineProperty(Color, "White", {
/**
* White (#FFFFFF)
*/
get: function () {
return Color.fromHex('#FFFFFF');
},
enumerable: false,
configurable: true
});
Object.defineProperty(Color, "Gray", {
/**
* Gray (#808080)
*/
get: function () {
return Color.fromHex('#808080');
},
enumerable: false,
configurable: true
});
Object.defineProperty(Color, "LightGray", {
/**
* Light gray (#D3D3D3)
*/
get: function () {
return Color.fromHex('#D3D3D3');
},
enumerable: false,
configurable: true
});
Object.defineProperty(Color, "DarkGray", {
/**
* Dark gray (#A9A9A9)
*/
get: function () {
return Color.fromHex('#A9A9A9');
},
enumerable: false,
configurable: true
});
Object.defineProperty(Color, "Yellow", {
/**
* Yellow (#FFFF00)
*/
get: function () {
return Color.fromHex('#FFFF00');
},
enumerable: false,
configurable: true
});
Object.defineProperty(Color, "Orange", {
/**
* Orange (#FFA500)
*/
get: function () {
return Color.fromHex('#FFA500');
},
enumerable: false,
configurable: true
});
Object.defineProperty(Color, "Red", {
/**
* Red (#FF0000)
*/
get: function () {
return Color.fromHex('#FF0000');
},
enumerable: false,
configurable: true
});
Object.defineProperty(Color, "Vermilion", {
/**
* Vermilion (#FF5B31)
*/
get: function () {
return Color.fromHex('#FF5B31');
},
enumerable: false,
configurable: true
});
Object.defineProperty(Color, "Vermillion", {
/**
* Vermilion (#FF5B31)
* @obsolete Alias for incorrect spelling used in older versions, use multiply instead, will be removed in v0.25.0
*/
get: function () {
return Color.Vermilion;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Color, "Rose", {
/**
* Rose (#FF007F)
*/
get: function () {
return Color.fromHex('#FF007F');
},
enumerable: false,
configurable: true
});
Object.defineProperty(Color, "Magenta", {
/**
* Magenta (#FF00FF)
*/
get: function () {
return Color.fromHex('#FF00FF');
},
enumerable: false,
configurable: true
});
Object.defineProperty(Color, "Violet", {
/**
* Violet (#7F00FF)
*/
get: function () {
return Color.fromHex('#7F00FF');
},
enumerable: false,
configurable: true
});
Object.defineProperty(Color, "Blue", {
/**
* Blue (#0000FF)
*/
get: function () {
return Color.fromHex('#0000FF');
},
enumerable: false,
configurable: true
});
Object.defineProperty(Color, "Azure", {
/**
* Azure (#007FFF)
*/
get: function () {
return Color.fromHex('#007FFF');
},
enumerable: false,
configurable: true
});
Object.defineProperty(Color, "Cyan", {
/**
* Cyan (#00FFFF)
*/
get: function () {
return Color.fromHex('#00FFFF');
},
enumerable: false,
configurable: true
});
Object.defineProperty(Color, "Viridian", {
/**
* Viridian (#59978F)
*/
get: function () {
return Color.fromHex('#59978F');
},
enumerable: false,
configurable: true
});
Object.defineProperty(Color, "Green", {
/**
* Green (#00FF00)
*/
get: function () {
return Color.fromHex('#00FF00');
},
enumerable: false,
configurable: true
});
Object.defineProperty(Color, "Chartreuse", {
/**
* Chartreuse (#7FFF00)
*/
get: function () {
return Color.fromHex('#7FFF00');
},
enumerable: false,
configurable: true
});
Object.defineProperty(Color, "Transparent", {
/**
* Transparent (#FFFFFF00)
*/
get: function () {
return Color.fromHex('#FFFFFF00');
},
enumerable: false,
configurable: true
});
__decorate([
Object(_Util_Decorators__WEBPACK_IMPORTED_MODULE_0__["obsolete"])({ message: 'Alias for incorrect spelling used in older versions, use multiply instead, will be removed in v0.25.0' })
], Color.prototype, "mulitiply", null);
__decorate([
Object(_Util_Decorators__WEBPACK_IMPORTED_MODULE_0__["obsolete"])({
message: 'Alias for incorrect spelling used in older versions',
alternateMethod: 'Vermilion'
})
], Color, "Vermillion", null);
return Color;
}());
/**
* Internal HSL Color representation
*
* http://en.wikipedia.org/wiki/HSL_and_HSV
* http://axonflux.com/handy-rgb-to-hsl-and-rgb-to-hsv-color-model-c
*/
var HSLColor = /** @class */ (function () {
function HSLColor(h, s, l, a) {
this.h = h;
this.s = s;
this.l = l;
this.a = a;
}
HSLColor.hue2rgb = 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;
};
HSLColor.fromRGBA = function (r, g, b, a) {
r /= 255;
g /= 255;
b /= 255;
var max = Math.max(r, g, b), min = Math.min(r, g, b);
var h, s;
var l = (max + min) / 2;
if (max === min) {
h = s = 0; // achromatic
}
else {
var d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch (max) {
case r:
h = (g - b) / d + (g < b ? 6 : 0);
break;
case g:
h = (b - r) / d + 2;
break;
case b:
h = (r - g) / d + 4;
break;
}
h /= 6;
}
return new HSLColor(h, s, l, a);
};
HSLColor.prototype.toRGBA = function () {
var r, g, b;
if (this.s === 0) {
r = g = b = this.l; // achromatic
}
else {
var q = this.l < 0.5 ? this.l * (1 + this.s) : this.l + this.s - this.l * this.s;
var p = 2 * this.l - q;
r = HSLColor.hue2rgb(p, q, this.h + 1 / 3);
g = HSLColor.hue2rgb(p, q, this.h);
b = HSLColor.hue2rgb(p, q, this.h - 1 / 3);
}
return new Color(r * 255, g * 255, b * 255, this.a);
};
HSLColor.prototype.toString = function () {
var h = this.h.toFixed(0), s = this.s.toFixed(0), l = this.l.toFixed(0), a = this.a.toFixed(0);
return "hsla(" + h + ", " + s + ", " + l + ", " + a + ")";
};
return HSLColor;
}());
/***/ }),
/***/ "./Drawing/Index.ts":
/*!**************************!*\
!*** ./Drawing/Index.ts ***!
\**************************/
/*! exports provided: Animation, Color, Polygon, Sprite, SpriteSheet, SpriteFont, Effects */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _Animation__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Animation */ "./Drawing/Animation.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Animation", function() { return _Animation__WEBPACK_IMPORTED_MODULE_0__["Animation"]; });
/* harmony import */ var _Color__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Color */ "./Drawing/Color.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Color", function() { return _Color__WEBPACK_IMPORTED_MODULE_1__["Color"]; });
/* harmony import */ var _Polygon__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Polygon */ "./Drawing/Polygon.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Polygon", function() { return _Polygon__WEBPACK_IMPORTED_MODULE_2__["Polygon"]; });
/* harmony import */ var _Sprite__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Sprite */ "./Drawing/Sprite.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Sprite", function() { return _Sprite__WEBPACK_IMPORTED_MODULE_3__["Sprite"]; });
/* harmony import */ var _SpriteSheet__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./SpriteSheet */ "./Drawing/SpriteSheet.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SpriteSheet", function() { return _SpriteSheet__WEBPACK_IMPORTED_MODULE_4__["SpriteSheet"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SpriteFont", function() { return _SpriteSheet__WEBPACK_IMPORTED_MODULE_4__["SpriteFont"]; });
/* harmony import */ var _SpriteEffects__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./SpriteEffects */ "./Drawing/SpriteEffects.ts");
/* harmony reexport (module object) */ __webpack_require__.d(__webpack_exports__, "Effects", function() { return _SpriteEffects__WEBPACK_IMPORTED_MODULE_5__; });
/***/ }),
/***/ "./Drawing/Polygon.ts":
/*!****************************!*\
!*** ./Drawing/Polygon.ts ***!
\****************************/
/*! exports provided: Polygon */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Polygon", function() { return Polygon; });
/* harmony import */ var _Algebra__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Algebra */ "./Algebra.ts");
var __assign = (undefined && undefined.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
/**
* Creates a closed polygon drawing given a list of [[Vector]]s.
*
* @warning Use sparingly as Polygons are performance intensive
*/
var Polygon = /** @class */ (function () {
/**
* @param points The vectors to use to build the polygon in order
*/
function Polygon(points) {
/**
* The width of the lines of the polygon
*/
this.lineWidth = 5;
/**
* Indicates whether the polygon is filled or not.
*/
this.filled = false;
this._points = [];
this.anchor = _Algebra__WEBPACK_IMPORTED_MODULE_0__["Vector"].Zero;
this.offset = _Algebra__WEBPACK_IMPORTED_MODULE_0__["Vector"].Zero;
this.rotation = 0;
this.scale = _Algebra__WEBPACK_IMPORTED_MODULE_0__["Vector"].One;
this.opacity = 1;
this._points = points;
var minX = this._points.reduce(function (prev, curr) {
return Math.min(prev, curr.x);
}, 0);
var maxX = this._points.reduce(function (prev, curr) {
return Math.max(prev, curr.x);
}, 0);
this.drawWidth = maxX - minX;
var minY = this._points.reduce(function (prev, curr) {
return Math.min(prev, curr.y);
}, 0);
var maxY = this._points.reduce(function (prev, curr) {
return Math.max(prev, curr.y);
}, 0);
this.drawHeight = maxY - minY;
this.height = this.drawHeight;
this.width = this.drawWidth;
}
/**
* @notimplemented Effects are not supported on `Polygon`
*/
Polygon.prototype.addEffect = function () {
// not supported on polygons
};
/**
* @notimplemented Effects are not supported on `Polygon`
*/
Polygon.prototype.removeEffect = function () {
// not supported on polygons
};
/**
* @notimplemented Effects are not supported on `Polygon`
*/
Polygon.prototype.clearEffects = function () {
// not supported on polygons
};
Polygon.prototype.reset = function () {
//pass
};
Polygon.prototype.draw = function (ctxOrOptions, x, y) {
if (ctxOrOptions instanceof CanvasRenderingContext2D) {
this._drawWithOptions({ ctx: ctxOrOptions, x: x, y: y });
}
else {
this._drawWithOptions(ctxOrOptions);
}
};
Polygon.prototype._drawWithOptions = function (options) {
var _a, _b, _c, _d, _e, _f, _g, _h;
var _j = __assign(__assign({}, options), { rotation: (_a = options.rotation) !== null && _a !== void 0 ? _a : this.rotation, drawWidth: (_b = options.drawWidth) !== null && _b !== void 0 ? _b : this.drawWidth, drawHeight: (_c = options.drawHeight) !== null && _c !== void 0 ? _c : this.drawHeight, flipHorizontal: (_d = options.flipHorizontal) !== null && _d !== void 0 ? _d : this.flipHorizontal, flipVertical: (_e = options.flipVertical) !== null && _e !== void 0 ? _e : this.flipVertical, anchor: (_f = options.anchor) !== null && _f !== void 0 ? _f : this.anchor, offset: (_g = options.offset) !== null && _g !== void 0 ? _g : this.offset, opacity: (_h = options.opacity) !== null && _h !== void 0 ? _h : this.opacity }), ctx = _j.ctx, x = _j.x, y = _j.y, rotation = _j.rotation, drawWidth = _j.drawWidth, drawHeight = _j.drawHeight, anchor = _j.anchor, offset = _j.offset, opacity = _j.opacity, flipHorizontal = _j.flipHorizontal, flipVertical = _j.flipVertical;
var xpoint = drawWidth * anchor.x + offset.x + x;
var ypoint = drawHeight * anchor.y + offset.y + y;
ctx.save();
ctx.translate(xpoint, ypoint);
ctx.scale(this.scale.x, this.scale.y);
ctx.rotate(rotation);
ctx.beginPath();
ctx.lineWidth = this.lineWidth;
// Iterate through the supplied points and construct a 'polygon'
var firstPoint = this._points[0];
ctx.moveTo(firstPoint.x, firstPoint.y);
var i = 0;
var len = this._points.length;
for (i; i < len; i++) {
ctx.lineTo(this._points[i].x, this._points[i].y);
}
ctx.lineTo(firstPoint.x, firstPoint.y);
ctx.closePath();
if (this.filled) {
ctx.fillStyle = this.fillColor.toString();
ctx.fill();
}
ctx.strokeStyle = this.lineColor.toString();
if (flipHorizontal) {
ctx.translate(drawWidth, 0);
ctx.scale(-1, 1);
}
if (flipVertical) {
ctx.translate(0, drawHeight);
ctx.scale(1, -1);
}
var oldAlpha = ctx.globalAlpha;
ctx.globalAlpha = opacity !== null && opacity !== void 0 ? opacity : 1;
ctx.stroke();
ctx.globalAlpha = oldAlpha;
ctx.restore();
};
return Polygon;
}());
/***/ }),
/***/ "./Drawing/Sprite.ts":
/*!***************************!*\
!*** ./Drawing/Sprite.ts ***!
\***************************/
/*! exports provided: SpriteImpl, Sprite */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SpriteImpl", function() { return SpriteImpl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Sprite", function() { return Sprite; });
/* harmony import */ var _SpriteEffects__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./SpriteEffects */ "./Drawing/SpriteEffects.ts");
/* harmony import */ var _Color__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Color */ "./Drawing/Color.ts");
/* harmony import */ var _Resources_Texture__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Resources/Texture */ "./Resources/Texture.ts");
/* harmony import */ var _Algebra__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Algebra */ "./Algebra.ts");
/* harmony import */ var _Util_Log__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Util/Log */ "./Util/Log.ts");
/* harmony import */ var _Util_Util__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Util/Util */ "./Util/Util.ts");
/* harmony import */ var _Configurable__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Configurable */ "./Configurable.ts");
var __extends = (undefined && undefined.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __assign = (undefined && undefined.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
/**
* @hidden
*/
var SpriteImpl = /** @class */ (function () {
/**
* @param image The backing image texture to build the Sprite
* @param x The x position of the sprite
* @param y The y position of the sprite
* @param width The width of the sprite in pixels
* @param height The height of the sprite in pixels
*/
function SpriteImpl(imageOrConfig, x, y, width, height) {
var _this = this;
this.x = 0;
this.y = 0;
this.rotation = 0.0;
this.anchor = new _Algebra__WEBPACK_IMPORTED_MODULE_3__["Vector"](0.0, 0.0);
this.offset = _Algebra__WEBPACK_IMPORTED_MODULE_3__["Vector"].Zero;
this.scale = _Algebra__WEBPACK_IMPORTED_MODULE_3__["Vector"].One;
this.logger = _Util_Log__WEBPACK_IMPORTED_MODULE_4__["Logger"].getInstance();
/**
* Draws the sprite flipped vertically
*/
this.flipVertical = false;
/**
* Draws the sprite flipped horizontally
*/
this.flipHorizontal = false;
this.effects = [];
this.width = 0;
this.height = 0;
this._spriteCanvas = null;
this._spriteCtx = null;
this._pixelData = null;
this._pixelsLoaded = false;
this._dirtyEffect = false;
this._opacity = 1;
var image = imageOrConfig;
if (imageOrConfig && !(imageOrConfig instanceof _Resources_Texture__WEBPACK_IMPORTED_MODULE_2__["Texture"])) {
x = imageOrConfig.x | 0;
y = imageOrConfig.y | 0;
width = imageOrConfig.width | 0;
height = imageOrConfig.height | 0;
image = imageOrConfig.image;
if (!image) {
var message = 'An image texture is required to contsruct a sprite';
throw new Error(message);
}
}
this.x = x || 0;
this.y = y || 0;
this._texture = image;
this._spriteCanvas = document.createElement('canvas');
this._spriteCanvas.width = width;
this._spriteCanvas.height = height;
this._spriteCtx = this._spriteCanvas.getContext('2d'); // eslint-disable-line
this._texture.loaded
.then(function () {
_this.width = _this.width || _this._texture.image.naturalWidth;
_this.height = _this.height || _this._texture.image.naturalHeight;
_this._spriteCanvas.width = _this._spriteCanvas.width || _this._texture.image.naturalWidth;
_this._spriteCanvas.height = _this._spriteCanvas.height || _this._texture.image.naturalHeight;
_this._loadPixels();
_this._dirtyEffect = true;
})
.error(function (e) {
_this.logger.error('Error loading texture ', _this._texture.path, e);
});
this.width = width;
this.height = height;
}
Object.defineProperty(SpriteImpl.prototype, "drawWidth", {
get: function () {
return this.width * this.scale.x;
},
enumerable: false,
configurable: true
});
Object.defineProperty(SpriteImpl.prototype, "drawHeight", {
get: function () {
return this.height * this.scale.y;
},
enumerable: false,
configurable: true
});
SpriteImpl.prototype._loadPixels = function () {
if (this._texture.isLoaded() && !this._pixelsLoaded) {
var naturalWidth = this._texture.image.naturalWidth || 0;
var naturalHeight = this._texture.image.naturalHeight || 0;
if (this.width > naturalWidth) {
this.logger.warn("The sprite width " + this.width + " exceeds the width \n " + naturalWidth + " of the backing texture " + this._texture.path);
}
if (this.width <= 0 || naturalWidth <= 0) {
throw new Error("The width of a sprite cannot be 0 or negative, sprite width: " + this.width + ", original width: " + naturalWidth);
}
if (this.height > naturalHeight) {
this.logger.warn("The sprite height " + this.height + " exceeds the height \n " + naturalHeight + " of the backing texture " + this._texture.path);
}
if (this.height <= 0 || naturalHeight <= 0) {
throw new Error("The height of a sprite cannot be 0 or negative, sprite height: " + this.height + ", original height: " + naturalHeight);
}
this._spriteCtx.drawImage(this._texture.image, Object(_Util_Util__WEBPACK_IMPORTED_MODULE_5__["clamp"])(this.x, 0, naturalWidth), Object(_Util_Util__WEBPACK_IMPORTED_MODULE_5__["clamp"])(this.y, 0, naturalHeight), Object(_Util_Util__WEBPACK_IMPORTED_MODULE_5__["clamp"])(this.width, 0, naturalWidth), Object(_Util_Util__WEBPACK_IMPORTED_MODULE_5__["clamp"])(this.height, 0, naturalHeight), 0, 0, this.width, this.height);
this._pixelsLoaded = true;
}
};
/**
* Applies the [[Opacity]] effect to a sprite, setting the alpha of all pixels to a given value
*/
SpriteImpl.prototype.opacity = function (value) {
this._opacity = value;
};
/**
* Applies the [[Grayscale]] effect to a sprite, removing color information.
*/
SpriteImpl.prototype.grayscale = function () {
this.addEffect(new _SpriteEffects__WEBPACK_IMPORTED_MODULE_0__["Grayscale"]());
};
/**
* Applies the [[Invert]] effect to a sprite, inverting the pixel colors.
*/
SpriteImpl.prototype.invert = function () {
this.addEffect(new _SpriteEffects__WEBPACK_IMPORTED_MODULE_0__["Invert"]());
};
/**
* Applies the [[Fill]] effect to a sprite, changing the color channels of all non-transparent pixels to match a given color
*/
SpriteImpl.prototype.fill = function (color) {
this.addEffect(new _SpriteEffects__WEBPACK_IMPORTED_MODULE_0__["Fill"](color));
};
/**
* Applies the [[Colorize]] effect to a sprite, changing the color channels of all pixels to be the average of the original color
* and the provided color.
*/
SpriteImpl.prototype.colorize = function (color) {
this.addEffect(new _SpriteEffects__WEBPACK_IMPORTED_MODULE_0__["Colorize"](color));
};
/**
* Applies the [[Lighten]] effect to a sprite, changes the lightness of the color according to HSL
*/
SpriteImpl.prototype.lighten = function (factor) {
if (factor === void 0) { factor = 0.1; }
this.addEffect(new _SpriteEffects__WEBPACK_IMPORTED_MODULE_0__["Lighten"](factor));
};
/**
* Applies the [[Darken]] effect to a sprite, changes the darkness of the color according to HSL
*/
SpriteImpl.prototype.darken = function (factor) {
if (factor === void 0) { factor = 0.1; }
this.addEffect(new _SpriteEffects__WEBPACK_IMPORTED_MODULE_0__["Darken"](factor));
};
/**
* Applies the [[Saturate]] effect to a sprite, saturates the color according to HSL
*/
SpriteImpl.prototype.saturate = function (factor) {
if (factor === void 0) { factor = 0.1; }
this.addEffect(new _SpriteEffects__WEBPACK_IMPORTED_MODULE_0__["Saturate"](factor));
};
/**
* Applies the [[Desaturate]] effect to a sprite, desaturates the color according to HSL
*/
SpriteImpl.prototype.desaturate = function (factor) {
if (factor === void 0) { factor = 0.1; }
this.addEffect(new _SpriteEffects__WEBPACK_IMPORTED_MODULE_0__["Desaturate"](factor));
};
/**
* Adds a new [[SpriteEffect]] to this drawing.
* @param effect Effect to add to the this drawing
*/
SpriteImpl.prototype.addEffect = function (effect) {
this.effects.push(effect);
// We must check if the texture and the backing sprite pixels are loaded as well before
// an effect can be applied
if (!this._texture.isLoaded() || !this._pixelsLoaded) {
this._dirtyEffect = true;
}
else {
this._applyEffects();
}
};
SpriteImpl.prototype.removeEffect = function (param) {
var indexToRemove = -1;
if (typeof param === 'number') {
indexToRemove = param;
}
else {
indexToRemove = this.effects.indexOf(param);
}
// bounds check
if (indexToRemove < 0 || indexToRemove >= this.effects.length) {
return;
}
this.effects.splice(indexToRemove, 1);
// We must check if the texture and the backing sprite pixels are loaded as well before
// an effect can be applied
if (!this._texture.isLoaded() || !this._pixelsLoaded) {
this._dirtyEffect = true;
}
else {
this._applyEffects();
}
};
SpriteImpl.prototype._applyEffects = function () {
var naturalWidth = this._texture.image.naturalWidth || 0;
var naturalHeight = this._texture.image.naturalHeight || 0;
this._spriteCtx.clearRect(0, 0, this.width, this.height);
this._spriteCtx.drawImage(this._texture.image, Object(_Util_Util__WEBPACK_IMPORTED_MODULE_5__["clamp"])(this.x, 0, naturalWidth), Object(_Util_Util__WEBPACK_IMPORTED_MODULE_5__["clamp"])(this.y, 0, naturalHeight), Object(_Util_Util__WEBPACK_IMPORTED_MODULE_5__["clamp"])(this.width, 0, naturalWidth), Object(_Util_Util__WEBPACK_IMPORTED_MODULE_5__["clamp"])(this.height, 0, naturalHeight), 0, 0, this.width, this.height);
if (this.effects.length > 0) {
this._pixelData = this._spriteCtx.getImageData(0, 0, this.width, this.height);
var len = this.effects.length;
for (var i = 0; i < len; i++) {
for (var y = 0; y < this.height; y++) {
for (var x = 0; x < this.width; x++) {
this.effects[i].updatePixel(x, y, this._pixelData);
}
}
}
this._spriteCtx.clearRect(0, 0, this.width, this.height);
this._spriteCtx.putImageData(this._pixelData, 0, 0);
}
this._dirtyEffect = false;
};
/**
* Clears all effects from the drawing and return it to its original state.
*/
SpriteImpl.prototype.clearEffects = function () {
this.effects.length = 0;
this._applyEffects();
};
/**
* Resets the internal state of the drawing (if any)
*/
SpriteImpl.prototype.reset = function () {
// do nothing
};
SpriteImpl.prototype.debugDraw = function (ctx, x, y) {
ctx.save();
ctx.translate(x, y);
ctx.rotate(this.rotation);
var xpoint = this.drawWidth * this.anchor.x;
var ypoint = this.drawHeight * this.anchor.y;
ctx.strokeStyle = _Color__WEBPACK_IMPORTED_MODULE_1__["Color"].Black.toString();
ctx.strokeRect(-xpoint, -ypoint, this.drawWidth, this.drawHeight);
ctx.restore();
};
SpriteImpl.prototype.draw = function (ctxOrOptions, x, y) {
if (ctxOrOptions instanceof CanvasRenderingContext2D) {
this._drawWithOptions({ ctx: ctxOrOptions, x: x, y: y });
}
else {
this._drawWithOptions(ctxOrOptions);
}
};
SpriteImpl.prototype._drawWithOptions = function (options) {
var _a, _b, _c, _d, _e, _f, _g, _h;
var _j = __assign(__assign({}, options), { rotation: (_a = options.rotation) !== null && _a !== void 0 ? _a : this.rotation, drawWidth: (_b = options.drawWidth) !== null && _b !== void 0 ? _b : this.drawWidth, drawHeight: (_c = options.drawHeight) !== null && _c !== void 0 ? _c : this.drawHeight, flipHorizontal: (_d = options.flipHorizontal) !== null && _d !== void 0 ? _d : this.flipHorizontal, flipVertical: (_e = options.flipVertical) !== null && _e !== void 0 ? _e : this.flipVertical, anchor: (_f = options.anchor) !== null && _f !== void 0 ? _f : this.anchor, offset: (_g = options.offset) !== null && _g !== void 0 ? _g : this.offset, opacity: (_h = options.opacity) !== null && _h !== void 0 ? _h : this._opacity }), ctx = _j.ctx, x = _j.x, y = _j.y, rotation = _j.rotation, drawWidth = _j.drawWidth, drawHeight = _j.drawHeight, anchor = _j.anchor, offset = _j.offset, opacity = _j.opacity, flipHorizontal = _j.flipHorizontal, flipVertical = _j.flipVertical;
if (this._dirtyEffect) {
this._applyEffects();
}
// calculating current dimensions
ctx.save();
var xpoint = drawWidth * anchor.x + offset.x;
var ypoint = drawHeight * anchor.y + offset.y;
ctx.translate(x, y);
ctx.rotate(rotation);
// todo cache flipped sprites
if (flipHorizontal) {
ctx.translate(drawWidth, 0);
ctx.scale(-1, 1);
}
if (flipVertical) {
ctx.translate(0, drawHeight);
ctx.scale(1, -1);
}
if (this._dirtyEffect) {
this._applyEffects();
}
var oldAlpha = ctx.globalAlpha;
ctx.globalAlpha = opacity !== null && opacity !== void 0 ? opacity : 1;
ctx.drawImage(this._spriteCanvas, 0, 0, this.width, this.height, -xpoint, -ypoint, drawWidth, drawHeight);
ctx.globalAlpha = oldAlpha;
ctx.restore();
};
/**
* Produces a copy of the current sprite
*/
SpriteImpl.prototype.clone = function () {
var result = new Sprite(this._texture, this.x, this.y, this.width, this.height);
result.scale = this.scale.clone();
result.rotation = this.rotation;
result.flipHorizontal = this.flipHorizontal;
result.flipVertical = this.flipVertical;
var len = this.effects.length;
for (var i = 0; i < len; i++) {
result.addEffect(this.effects[i]);
}
return result;
};
return SpriteImpl;
}());
/**
* A [[Sprite]] is one of the main drawing primitives. It is responsible for drawing
* images or parts of images from a [[Texture]] resource to the screen.
*
* [[include:Sprites.md]]
*/
var Sprite = /** @class */ (function (_super) {
__extends(Sprite, _super);
function Sprite(imageOrConfig, x, y, width, height) {
return _super.call(this, imageOrConfig, x, y, width, height) || this;
}
return Sprite;
}(Object(_Configurable__WEBPACK_IMPORTED_MODULE_6__["Configurable"])(SpriteImpl)));
/***/ }),
/***/ "./Drawing/SpriteEffects.ts":
/*!**********************************!*\
!*** ./Drawing/SpriteEffects.ts ***!
\**********************************/
/*! exports provided: Grayscale, Invert, Opacity, Colorize, Lighten, Darken, Saturate, Desaturate, Fill */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Grayscale", function() { return Grayscale; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Invert", function() { return Invert; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Opacity", function() { return Opacity; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Colorize", function() { return Colorize; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Lighten", function() { return Lighten; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Darken", function() { return Darken; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Saturate", function() { return Saturate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Desaturate", function() { return Desaturate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Fill", function() { return Fill; });
/* harmony import */ var _Color__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Color */ "./Drawing/Color.ts");
/**
* These effects can be applied to any bitmap image but are mainly used
* for [[Sprite]] effects or [[Animation]] effects.
*
* [[include:SpriteEffects.md]]
*/
/**
* @typedoc
*/
/**
* Applies the "Grayscale" effect to a sprite, removing color information.
*/
var Grayscale = /** @class */ (function () {
function Grayscale() {
}
Grayscale.prototype.updatePixel = function (x, y, imageData) {
var firstPixel = (x + y * imageData.width) * 4;
var pixel = imageData.data;
var avg = (pixel[firstPixel + 0] + pixel[firstPixel + 1] + pixel[firstPixel + 2]) / 3;
pixel[firstPixel + 0] = avg;
pixel[firstPixel + 1] = avg;
pixel[firstPixel + 2] = avg;
};
return Grayscale;
}());
/**
* Applies the "Invert" effect to a sprite, inverting the pixel colors.
*/
var Invert = /** @class */ (function () {
function Invert() {
}
Invert.prototype.updatePixel = function (x, y, imageData) {
var firstPixel = (x + y * imageData.width) * 4;
var pixel = imageData.data;
pixel[firstPixel + 0] = 255 - pixel[firstPixel + 0];
pixel[firstPixel + 1] = 255 - pixel[firstPixel + 1];
pixel[firstPixel + 2] = 255 - pixel[firstPixel + 2];
};
return Invert;
}());
/**
* Applies the "Opacity" effect to a sprite, setting the alpha of all pixels to a given value.
*/
var Opacity = /** @class */ (function () {
/**
* @param opacity The new opacity of the sprite from 0-1.0
*/
function Opacity(opacity) {
this.opacity = opacity;
}
Opacity.prototype.updatePixel = function (x, y, imageData) {
var firstPixel = (x + y * imageData.width) * 4;
var pixel = imageData.data;
if (pixel[firstPixel + 3] !== 0) {
pixel[firstPixel + 3] = Math.round(this.opacity * pixel[firstPixel + 3]);
}
};
return Opacity;
}());
/**
* Applies the "Colorize" effect to a sprite, changing the color channels of all the pixels to an
* average of the original color and the provided color
*/
var Colorize = /** @class */ (function () {
/**
* @param color The color to apply to the sprite
*/
function Colorize(color) {
this.color = color;
}
Colorize.prototype.updatePixel = function (x, y, imageData) {
var firstPixel = (x + y * imageData.width) * 4;
var pixel = imageData.data;
if (pixel[firstPixel + 3] !== 0) {
pixel[firstPixel + 0] = (pixel[firstPixel + 0] + this.color.r) / 2;
pixel[firstPixel + 1] = (pixel[firstPixel + 1] + this.color.g) / 2;
pixel[firstPixel + 2] = (pixel[firstPixel + 2] + this.color.b) / 2;
}
};
return Colorize;
}());
/**
* Applies the "Lighten" effect to a sprite, changes the lightness of the color according to HSL
*/
var Lighten = /** @class */ (function () {
/**
* @param factor The factor of the effect between 0-1
*/
function Lighten(factor) {
if (factor === void 0) { factor = 0.1; }
this.factor = factor;
}
Lighten.prototype.updatePixel = function (x, y, imageData) {
var firstPixel = (x + y * imageData.width) * 4;
var pixel = imageData.data;
var color = _Color__WEBPACK_IMPORTED_MODULE_0__["Color"].fromRGB(pixel[firstPixel + 0], pixel[firstPixel + 1], pixel[firstPixel + 2], pixel[firstPixel + 3]).lighten(this.factor);
pixel[firstPixel + 0] = color.r;
pixel[firstPixel + 1] = color.g;
pixel[firstPixel + 2] = color.b;
pixel[firstPixel + 3] = color.a;
};
return Lighten;
}());
/**
* Applies the "Darken" effect to a sprite, changes the darkness of the color according to HSL
*/
var Darken = /** @class */ (function () {
/**
* @param factor The factor of the effect between 0-1
*/
function Darken(factor) {
if (factor === void 0) { factor = 0.1; }
this.factor = factor;
}
Darken.prototype.updatePixel = function (x, y, imageData) {
var firstPixel = (x + y * imageData.width) * 4;
var pixel = imageData.data;
var color = _Color__WEBPACK_IMPORTED_MODULE_0__["Color"].fromRGB(pixel[firstPixel + 0], pixel[firstPixel + 1], pixel[firstPixel + 2], pixel[firstPixel + 3]).darken(this.factor);
pixel[firstPixel + 0] = color.r;
pixel[firstPixel + 1] = color.g;
pixel[firstPixel + 2] = color.b;
pixel[firstPixel + 3] = color.a;
};
return Darken;
}());
/**
* Applies the "Saturate" effect to a sprite, saturates the color according to HSL
*/
var Saturate = /** @class */ (function () {
/**
* @param factor The factor of the effect between 0-1
*/
function Saturate(factor) {
if (factor === void 0) { factor = 0.1; }
this.factor = factor;
}
Saturate.prototype.updatePixel = function (x, y, imageData) {
var firstPixel = (x + y * imageData.width) * 4;
var pixel = imageData.data;
var color = _Color__WEBPACK_IMPORTED_MODULE_0__["Color"].fromRGB(pixel[firstPixel + 0], pixel[firstPixel + 1], pixel[firstPixel + 2], pixel[firstPixel + 3]).saturate(this.factor);
pixel[firstPixel + 0] = color.r;
pixel[firstPixel + 1] = color.g;
pixel[firstPixel + 2] = color.b;
pixel[firstPixel + 3] = color.a;
};
return Saturate;
}());
/**
* Applies the "Desaturate" effect to a sprite, desaturates the color according to HSL
*/
var Desaturate = /** @class */ (function () {
/**
* @param factor The factor of the effect between 0-1
*/
function Desaturate(factor) {
if (factor === void 0) { factor = 0.1; }
this.factor = factor;
}
Desaturate.prototype.updatePixel = function (x, y, imageData) {
var firstPixel = (x + y * imageData.width) * 4;
var pixel = imageData.data;
var color = _Color__WEBPACK_IMPORTED_MODULE_0__["Color"].fromRGB(pixel[firstPixel + 0], pixel[firstPixel + 1], pixel[firstPixel + 2], pixel[firstPixel + 3]).desaturate(this.factor);
pixel[firstPixel + 0] = color.r;
pixel[firstPixel + 1] = color.g;
pixel[firstPixel + 2] = color.b;
pixel[firstPixel + 3] = color.a;
};
return Desaturate;
}());
/**
* Applies the "Fill" effect to a sprite, changing the color channels of all non-transparent pixels to match
* a given color
*/
var Fill = /** @class */ (function () {
/**
* @param color The color to apply to the sprite
*/
function Fill(color) {
this.color = color;
}
Fill.prototype.updatePixel = function (x, y, imageData) {
var firstPixel = (x + y * imageData.width) * 4;
var pixel = imageData.data;
if (pixel[firstPixel + 3] !== 0) {
pixel[firstPixel + 0] = this.color.r;
pixel[firstPixel + 1] = this.color.g;
pixel[firstPixel + 2] = this.color.b;
}
};
return Fill;
}());
/***/ }),
/***/ "./Drawing/SpriteSheet.ts":
/*!********************************!*\
!*** ./Drawing/SpriteSheet.ts ***!
\********************************/
/*! exports provided: SpriteSheetImpl, SpriteSheet, SpriteFontImpl, SpriteFont */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SpriteSheetImpl", function() { return SpriteSheetImpl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SpriteSheet", function() { return SpriteSheet; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SpriteFontImpl", function() { return SpriteFontImpl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SpriteFont", function() { return SpriteFont; });
/* harmony import */ var _Sprite__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Sprite */ "./Drawing/Sprite.ts");
/* harmony import */ var _Animation__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Animation */ "./Drawing/Animation.ts");
/* harmony import */ var _Color__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Color */ "./Drawing/Color.ts");
/* harmony import */ var _SpriteEffects__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./SpriteEffects */ "./Drawing/SpriteEffects.ts");
/* harmony import */ var _Resources_Texture__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Resources/Texture */ "./Resources/Texture.ts");
/* harmony import */ var _Util_Log__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Util/Log */ "./Util/Log.ts");
/* harmony import */ var _Label__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Label */ "./Label.ts");
/* harmony import */ var _Configurable__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Configurable */ "./Configurable.ts");
var __extends = (undefined && undefined.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
/**
* @hidden
*/
var SpriteSheetImpl = /** @class */ (function () {
/**
* @param image The backing image texture to build the SpriteSheet
* @param columns The number of columns in the image texture
* @param rows The number of rows in the image texture
* @param spWidth The width of each individual sprite in pixels
* @param spHeight The height of each individual sprite in pixels
* @param spacing The spacing between every sprite in a spritesheet
*/
function SpriteSheetImpl(imageOrConfigOrSprites, columns, rows, spWidth, spHeight, spacing) {
var _this = this;
this.sprites = [];
this.image = null;
this.columns = 0;
this.rows = 0;
this.spWidth = 0;
this.spHeight = 0;
this.spacing = 0;
var loadFromImage = false;
if (imageOrConfigOrSprites instanceof Array) {
this.sprites = imageOrConfigOrSprites;
}
else {
if (imageOrConfigOrSprites && !(imageOrConfigOrSprites instanceof _Resources_Texture__WEBPACK_IMPORTED_MODULE_4__["Texture"])) {
this.columns = imageOrConfigOrSprites.columns;
this.rows = imageOrConfigOrSprites.rows;
this.spWidth = imageOrConfigOrSprites.spWidth;
this.spHeight = imageOrConfigOrSprites.spHeight;
this.image = imageOrConfigOrSprites.image;
this.spacing = imageOrConfigOrSprites.spacing || 0;
}
else {
this.image = imageOrConfigOrSprites;
this.columns = columns;
this.rows = rows;
this.spWidth = spWidth;
this.spHeight = spHeight;
this.spacing = spacing || 0;
}
this.sprites = new Array(this.columns * this.rows);
loadFromImage = true;
}
// Inspect actual image dimensions with preloading
if (this.image instanceof _Resources_Texture__WEBPACK_IMPORTED_MODULE_4__["Texture"]) {
var isWidthError_1 = false;
var isHeightError_1 = false;
this.image.loaded.then(function (image) {
isWidthError_1 = _this.spWidth * _this.columns > image.naturalWidth;
isHeightError_1 = _this.spHeight * _this.rows > image.naturalHeight;
});
if (isWidthError_1) {
throw new RangeError("SpriteSheet specified is wider, " +
(this.columns + " cols x " + this.spWidth + " pixels > " + this.image.image.naturalWidth + " ") +
"pixels than image width");
}
if (isHeightError_1) {
throw new RangeError("SpriteSheet specified is taller, " +
(this.rows + " rows x " + this.spHeight + " pixels > " + this.image.image.naturalHeight + " ") +
"pixels than image height");
}
}
if (loadFromImage) {
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
this.sprites[j + i * this.columns] = new _Sprite__WEBPACK_IMPORTED_MODULE_0__["Sprite"](this.image, j * this.spWidth + this.spacing * j + this.spacing, i * this.spHeight + this.spacing * i + this.spacing, this.spWidth, this.spHeight);
}
}
}
}
/**
* Create an animation from the this SpriteSheet by listing out the
* sprite indices. Sprites are organized in row major order in the SpriteSheet.
* @param engine Reference to the current game [[Engine]]
* @param indices An array of sprite indices to use in the animation
* @param speed The number in milliseconds to display each frame in the animation
*/
SpriteSheetImpl.prototype.getAnimationByIndices = function (engine, indices, speed) {
var _this = this;
var images = indices.map(function (index) {
return _this.sprites[index];
});
images = images.map(function (i) {
return i.clone();
});
return new _Animation__WEBPACK_IMPORTED_MODULE_1__["Animation"](engine, images, speed);
};
/**
* Create an animation from the this SpriteSheet by specifying the range of
* images with the beginning (inclusive) and ending (exclusive) index
* For example `getAnimationBetween(engine, 0, 5, 200)` returns an animation with 5 frames.
* @param engine Reference to the current game Engine
* @param beginIndex The index to start taking frames (inclusive)
* @param endIndex The index to stop taking frames (exclusive)
* @param speed The number in milliseconds to display each frame in the animation
*/
SpriteSheetImpl.prototype.getAnimationBetween = function (engine, beginIndex, endIndex, speed) {
var images = this.sprites.slice(beginIndex, endIndex);
images = images.map(function (i) {
return i.clone();
});
return new _Animation__WEBPACK_IMPORTED_MODULE_1__["Animation"](engine, images, speed);
};
/**
* Treat the entire SpriteSheet as one animation, organizing the frames in
* row major order.
* @param engine Reference to the current game [[Engine]]
* @param speed The number in milliseconds to display each frame the animation
*/
SpriteSheetImpl.prototype.getAnimationForAll = function (engine, speed) {
var sprites = this.sprites.map(function (i) {
return i.clone();
});
return new _Animation__WEBPACK_IMPORTED_MODULE_1__["Animation"](engine, sprites, speed);
};
/**
* Retrieve a specific sprite from the SpriteSheet by its index. Sprites are organized
* in row major order in the SpriteSheet.
* @param index The index of the sprite
*/
SpriteSheetImpl.prototype.getSprite = function (index) {
if (index >= 0 && index < this.sprites.length) {
return this.sprites[index];
}
else {
throw new Error('Invalid index: ' + index);
}
};
/**
* Get an animation with bespoke sprite coordinates. This is useful if the SpriteSheet is
* packed and not a uniform width or height. The resulting [[Animation]] will have the height and width of the
* largest dimension (width, height) from among the sprite coordinates
* @param engine
* @param spriteCoordinates
* @param speed
*/
SpriteSheetImpl.prototype.getAnimationByCoords = function (engine, spriteCoordinates, speed) {
var maxWidth = 0;
var maxHeight = 0;
var sprites = new Array(spriteCoordinates.length);
for (var i = 0; i < spriteCoordinates.length; i++) {
var coord = spriteCoordinates[i];
// no need to pass image again if using a spritesheet
coord.image = coord.image || this.image;
maxWidth = Math.max(maxWidth, coord.drawWidth);
maxHeight = Math.max(maxHeight, coord.drawHeight);
sprites[i] = new _Sprite__WEBPACK_IMPORTED_MODULE_0__["Sprite"](coord);
}
var anim = new _Animation__WEBPACK_IMPORTED_MODULE_1__["Animation"](engine, sprites, speed);
anim.drawWidth = maxWidth;
anim.drawHeight = maxHeight;
return anim;
};
return SpriteSheetImpl;
}());
/**
* Sprite sheets are a useful mechanism for slicing up image resources into
* separate sprites or for generating in game animations. [[Sprite|Sprites]] are organized
* in row major order in the [[SpriteSheet]].
*
* [[include:SpriteSheets.md]]
*/
var SpriteSheet = /** @class */ (function (_super) {
__extends(SpriteSheet, _super);
function SpriteSheet(imageOrConfigOrSprites, columns, rows, spWidth, spHeight, spacing) {
return _super.call(this, imageOrConfigOrSprites, columns, rows, spWidth, spHeight, spacing) || this;
}
return SpriteSheet;
}(Object(_Configurable__WEBPACK_IMPORTED_MODULE_7__["Configurable"])(SpriteSheetImpl)));
var SpriteFontImpl = /** @class */ (function (_super) {
__extends(SpriteFontImpl, _super);
/**
* @param image The backing image texture to build the SpriteFont
* @param alphabet A string representing all the characters in the image, in row major order.
* @param caseInsensitive Indicate whether this font takes case into account
* @param columns The number of columns of characters in the image
* @param rows The number of rows of characters in the image
* @param spWidth The width of each character in pixels
* @param spHeight The height of each character in pixels
*/
function SpriteFontImpl(imageOrConfig, alphabet, caseInsensitive, columns, rows, spWidth, spHeight, spacing) {
var _this = _super.call(this, imageOrConfig instanceof _Resources_Texture__WEBPACK_IMPORTED_MODULE_4__["Texture"] ?
{
image: imageOrConfig,
spWidth: spWidth,
spHeight: spHeight,
rows: rows,
columns: columns,
spacing: spacing || 0
}
: imageOrConfig) || this;
_this._currentColor = _Color__WEBPACK_IMPORTED_MODULE_2__["Color"].Black;
_this._currentOpacity = 1.0;
_this._sprites = {};
// text shadow
_this._textShadowOn = false;
_this._textShadowDirty = true;
_this._textShadowColor = _Color__WEBPACK_IMPORTED_MODULE_2__["Color"].Black;
_this._textShadowSprites = {};
_this._shadowOffsetX = 5;
_this._shadowOffsetY = 5;
if (imageOrConfig && !(imageOrConfig instanceof _Resources_Texture__WEBPACK_IMPORTED_MODULE_4__["Texture"])) {
alphabet = imageOrConfig.alphabet;
caseInsensitive = imageOrConfig.caseInsensitive;
}
_this._alphabet = alphabet;
_this._caseInsensitive = caseInsensitive;
_this._sprites = _this.getTextSprites();
return _this;
}
/**
* Returns a dictionary that maps each character in the alphabet to the appropriate [[Sprite]].
*/
SpriteFontImpl.prototype.getTextSprites = function () {
var lookup = {};
for (var i = 0; i < this._alphabet.length; i++) {
var char = this._alphabet[i];
if (this._caseInsensitive) {
char = char.toLowerCase();
}
lookup[char] = this.sprites[i].clone();
}
return lookup;
};
/**
* Sets the text shadow for sprite fonts
* @param offsetX The x offset in pixels to place the shadow
* @param offsetY The y offset in pixels to place the shadow
* @param shadowColor The color of the text shadow
*/
SpriteFontImpl.prototype.setTextShadow = function (offsetX, offsetY, shadowColor) {
this._textShadowOn = true;
this._shadowOffsetX = offsetX;
this._shadowOffsetY = offsetY;
this._textShadowColor = shadowColor.clone();
this._textShadowDirty = true;
for (var character in this._sprites) {
this._textShadowSprites[character] = this._sprites[character].clone();
}
};
/**
* Toggles text shadows on or off
*/
SpriteFontImpl.prototype.useTextShadow = function (on) {
this._textShadowOn = on;
if (on) {
this.setTextShadow(5, 5, this._textShadowColor);
}
};
/**
* Draws the current sprite font
*/
SpriteFontImpl.prototype.draw = function (ctx, text, x, y, options) {
options = this._parseOptions(options);
if (this._currentColor.toString() !== options.color.toString() || this._currentOpacity !== options.opacity) {
this._currentOpacity = options.opacity;
this._currentColor = options.color;
for (var char in this._sprites) {
this._sprites[char].clearEffects();
this._sprites[char].fill(options.color);
this._sprites[char].opacity(options.opacity);
}
}
if (this._textShadowOn && this._textShadowDirty && this._textShadowColor) {
for (var characterShadow in this._textShadowSprites) {
this._textShadowSprites[characterShadow].clearEffects();
this._textShadowSprites[characterShadow].addEffect(new _SpriteEffects__WEBPACK_IMPORTED_MODULE_3__["Fill"](this._textShadowColor.clone()));
}
this._textShadowDirty = false;
}
// find the current length of text in pixels
var sprite = this.sprites[0];
// find the current height fo the text in pixels
var height = sprite.drawHeight;
// calculate appropriate scale for font size
var scale = options.fontSize / height;
var length = text.length * sprite.drawWidth * scale + text.length * options.letterSpacing;
var currX = x;
if (options.textAlign === _Label__WEBPACK_IMPORTED_MODULE_6__["TextAlign"].Left || options.textAlign === _Label__WEBPACK_IMPORTED_MODULE_6__["TextAlign"].Start) {
currX = x;
}
else if (options.textAlign === _Label__WEBPACK_IMPORTED_MODULE_6__["TextAlign"].Right || options.textAlign === _Label__WEBPACK_IMPORTED_MODULE_6__["TextAlign"].End) {
currX = x - length;
}
else if (options.textAlign === _Label__WEBPACK_IMPORTED_MODULE_6__["TextAlign"].Center) {
currX = x - length / 2;
}
var currY = y - height * scale;
if (options.baseAlign === _Label__WEBPACK_IMPORTED_MODULE_6__["BaseAlign"].Top || options.baseAlign === _Label__WEBPACK_IMPORTED_MODULE_6__["BaseAlign"].Hanging) {
currY = y;
}
else if (options.baseAlign === _Label__WEBPACK_IMPORTED_MODULE_6__["BaseAlign"].Ideographic ||
options.baseAlign === _Label__WEBPACK_IMPORTED_MODULE_6__["BaseAlign"].Bottom ||
options.baseAlign === _Label__WEBPACK_IMPORTED_MODULE_6__["BaseAlign"].Alphabetic) {
currY = y - height * scale;
}
else if (options.baseAlign === _Label__WEBPACK_IMPORTED_MODULE_6__["BaseAlign"].Middle) {
currY = y - (height * scale) / 2;
}
for (var i = 0; i < text.length; i++) {
var character = text[i];
if (this._caseInsensitive) {
character = character.toLowerCase();
}
try {
// if text shadow
if (this._textShadowOn) {
this._textShadowSprites[character].scale.x = scale;
this._textShadowSprites[character].scale.y = scale;
this._textShadowSprites[character].draw(ctx, currX + this._shadowOffsetX, currY + this._shadowOffsetY);
}
var charSprite = this._sprites[character];
charSprite.scale.x = scale;
charSprite.scale.y = scale;
charSprite.draw(ctx, currX, currY);
currX += charSprite.drawWidth + options.letterSpacing;
}
catch (e) {
_Util_Log__WEBPACK_IMPORTED_MODULE_5__["Logger"].getInstance().error("SpriteFont Error drawing char " + character);
}
}
};
SpriteFontImpl.prototype._parseOptions = function (options) {
return {
fontSize: options.fontSize || 10,
letterSpacing: options.letterSpacing || 0,
color: options.color || _Color__WEBPACK_IMPORTED_MODULE_2__["Color"].Black,
textAlign: typeof options.textAlign === undefined ? _Label__WEBPACK_IMPORTED_MODULE_6__["TextAlign"].Left : options.textAlign,
baseAlign: typeof options.baseAlign === undefined ? _Label__WEBPACK_IMPORTED_MODULE_6__["BaseAlign"].Bottom : options.baseAlign,
maxWidth: options.maxWidth || -1,
opacity: options.opacity || 0
};
};
return SpriteFontImpl;
}(SpriteSheet));
/**
* Sprite fonts are a used in conjunction with a [[Label]] to specify
* a particular bitmap as a font. Note that some font features are not
* supported by Sprite fonts.
*
* [[include:SpriteFonts.md]]
*/
var SpriteFont = /** @class */ (function (_super) {
__extends(SpriteFont, _super);
function SpriteFont(imageOrConfig, alphabet, caseInsensitive, columns, rows, spWidth, spHeight, spacing) {
return _super.call(this, imageOrConfig, alphabet, caseInsensitive, columns, rows, spWidth, spHeight, spacing) || this;
}
return SpriteFont;
}(Object(_Configurable__WEBPACK_IMPORTED_MODULE_7__["Configurable"])(SpriteFontImpl)));
/***/ }),
/***/ "./Engine.ts":
/*!*******************!*\
!*** ./Engine.ts ***!
\*******************/
/*! exports provided: ScrollPreventionMode, Engine */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ScrollPreventionMode", function() { return ScrollPreventionMode; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Engine", function() { return Engine; });
/* harmony import */ var ___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ */ "./index.ts");
/* harmony import */ var _Polyfill__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Polyfill */ "./Polyfill.ts");
/* harmony import */ var _Promises__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Promises */ "./Promises.ts");
/* harmony import */ var _Screen__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Screen */ "./Screen.ts");
/* harmony import */ var _ScreenElement__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./ScreenElement */ "./ScreenElement.ts");
/* harmony import */ var _Actor__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Actor */ "./Actor.ts");
/* harmony import */ var _Timer__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Timer */ "./Timer.ts");
/* harmony import */ var _TileMap__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./TileMap */ "./TileMap.ts");
/* harmony import */ var _Loader__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Loader */ "./Loader.ts");
/* harmony import */ var _Util_Detector__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Util/Detector */ "./Util/Detector.ts");
/* harmony import */ var _Events__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./Events */ "./Events.ts");
/* harmony import */ var _Util_Log__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./Util/Log */ "./Util/Log.ts");
/* harmony import */ var _Drawing_Color__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./Drawing/Color */ "./Drawing/Color.ts");
/* harmony import */ var _Scene__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./Scene */ "./Scene.ts");
/* harmony import */ var _Debug__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./Debug */ "./Debug.ts");
/* harmony import */ var _Class__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./Class */ "./Class.ts");
/* harmony import */ var _Input_Index__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./Input/Index */ "./Input/Index.ts");
/* harmony import */ var _Util_Browser__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./Util/Browser */ "./Util/Browser.ts");
var __extends = (undefined && undefined.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __assign = (undefined && undefined.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object(_Polyfill__WEBPACK_IMPORTED_MODULE_1__["polyfill"])();
/**
* Enum representing the different mousewheel event bubble prevention
*/
var ScrollPreventionMode;
(function (ScrollPreventionMode) {
/**
* Do not prevent any page scrolling
*/
ScrollPreventionMode[ScrollPreventionMode["None"] = 0] = "None";
/**
* Prevent page scroll if mouse is over the game canvas
*/
ScrollPreventionMode[ScrollPreventionMode["Canvas"] = 1] = "Canvas";
/**
* Prevent all page scrolling via mouse wheel
*/
ScrollPreventionMode[ScrollPreventionMode["All"] = 2] = "All";
})(ScrollPreventionMode || (ScrollPreventionMode = {}));
/**
* The Excalibur Engine
*
* The [[Engine]] is the main driver for a game. It is responsible for
* starting/stopping the game, maintaining state, transmitting events,
* loading resources, and managing the scene.
*
* [[include:Engine.md]]
*/
var Engine = /** @class */ (function (_super) {
__extends(Engine, _super);
/**
* Creates a new game using the given [[EngineOptions]]. By default, if no options are provided,
* the game will be rendered full screen (taking up all available browser window space).
* You can customize the game rendering through [[EngineOptions]].
*
* Example:
*
* ```js
* var game = new ex.Engine({
* width: 0, // the width of the canvas
* height: 0, // the height of the canvas
* enableCanvasTransparency: true, // the transparencySection of the canvas
* canvasElementId: '', // the DOM canvas element ID, if you are providing your own
* displayMode: ex.DisplayMode.FullScreen, // the display mode
* pointerScope: ex.Input.PointerScope.Document, // the scope of capturing pointer (mouse/touch) events
* backgroundColor: ex.Color.fromHex('#2185d0') // background color of the engine
* });
*
* // call game.start, which is a Promise
* game.start().then(function () {
* // ready, set, go!
* });
* ```
*/
function Engine(options) {
var _a, _b, _c;
var _this = _super.call(this) || this;
_this._hasStarted = false;
/**
* Gets or sets the list of post processors to apply at the end of drawing a frame (such as [[ColorBlindCorrector]])
*/
_this.postProcessors = [];
/**
* Contains all the scenes currently registered with Excalibur
*/
_this.scenes = {};
_this._animations = [];
_this._suppressPlayButton = false;
/**
* Indicates whether audio should be paused when the game is no longer visible.
*/
_this.pauseAudioWhenHidden = true;
/**
* Indicates whether the engine should draw with debug information
*/
_this.isDebug = false;
_this.debugColor = new _Drawing_Color__WEBPACK_IMPORTED_MODULE_12__["Color"](255, 255, 255);
/**
* Sets the Transparency for the engine.
*/
_this.enableCanvasTransparency = true;
/**
* The action to take when a fatal exception is thrown
*/
_this.onFatalException = function (e) {
_Util_Log__WEBPACK_IMPORTED_MODULE_11__["Logger"].getInstance().fatal(e);
};
_this._timescale = 1.0;
_this._isLoading = false;
_this._isInitialized = false;
options = __assign(__assign({}, Engine._DefaultEngineOptions), options);
// Initialize browser events facade
_this.browser = new _Util_Browser__WEBPACK_IMPORTED_MODULE_17__["BrowserEvents"](window, document);
// Check compatibility
var detector = new _Util_Detector__WEBPACK_IMPORTED_MODULE_9__["Detector"]();
if (!options.suppressMinimumBrowserFeatureDetection && !(_this._compatible = detector.test())) {
var message = document.createElement('div');
message.innerText = 'Sorry, your browser does not support all the features needed for Excalibur';
document.body.appendChild(message);
detector.failedTests.forEach(function (test) {
var testMessage = document.createElement('div');
testMessage.innerText = 'Browser feature missing ' + test;
document.body.appendChild(testMessage);
});
if (options.canvasElementId) {
var canvas = document.getElementById(options.canvasElementId);
if (canvas) {
canvas.parentElement.removeChild(canvas);
}
}
return _this;
}
else {
_this._compatible = true;
}
// Use native console API for color fun
// eslint-disable-next-line no-console
if (console.log && !options.suppressConsoleBootMessage) {
// eslint-disable-next-line no-console
console.log("%cPowered by Excalibur.js (v" + ___WEBPACK_IMPORTED_MODULE_0__["EX_VERSION"] + ")", 'background: #176BAA; color: white; border-radius: 5px; padding: 15px; font-size: 1.5em; line-height: 80px;');
// eslint-disable-next-line no-console
console.log('\n\
/| ________________\n\
O|===|* >________________>\n\
\\|');
// eslint-disable-next-line no-console
console.log('Visit', 'http://excaliburjs.com', 'for more information');
}
// Suppress play button
if (options.suppressPlayButton) {
_this._suppressPlayButton = true;
}
_this._logger = _Util_Log__WEBPACK_IMPORTED_MODULE_11__["Logger"].getInstance();
// If debug is enabled, let's log browser features to the console.
if (_this._logger.defaultLevel === _Util_Log__WEBPACK_IMPORTED_MODULE_11__["LogLevel"].Debug) {
detector.logBrowserFeatures();
}
_this._logger.debug('Building engine...');
_this.canvasElementId = options.canvasElementId;
if (options.canvasElementId) {
_this._logger.debug('Using Canvas element specified: ' + options.canvasElementId);
_this.canvas = document.getElementById(options.canvasElementId);
}
else if (options.canvasElement) {
_this._logger.debug('Using Canvas element specified:', options.canvasElement);
_this.canvas = options.canvasElement;
}
else {
_this._logger.debug('Using generated canvas element');
_this.canvas = document.createElement('canvas');
}
var displayMode = (_a = options.displayMode) !== null && _a !== void 0 ? _a : _Screen__WEBPACK_IMPORTED_MODULE_3__["DisplayMode"].Fixed;
if ((options.width && options.height) || options.viewport) {
if (options.displayMode === undefined) {
displayMode = _Screen__WEBPACK_IMPORTED_MODULE_3__["DisplayMode"].Fixed;
}
_this._logger.debug('Engine viewport is size ' + options.width + ' x ' + options.height);
}
else if (!options.displayMode) {
_this._logger.debug('Engine viewport is fullscreen');
displayMode = _Screen__WEBPACK_IMPORTED_MODULE_3__["DisplayMode"].FullScreen;
}
// eslint-disable-next-line
_this.ctx = _this.canvas.getContext('2d', { alpha: _this.enableCanvasTransparency });
_this.screen = new _Screen__WEBPACK_IMPORTED_MODULE_3__["Screen"]({
canvas: _this.canvas,
context: _this.ctx,
antialiasing: (_b = options.antialiasing) !== null && _b !== void 0 ? _b : true,
browser: _this.browser,
viewport: (_c = options.viewport) !== null && _c !== void 0 ? _c : { width: options.width, height: options.height },
resolution: options.resolution,
displayMode: displayMode,
position: options.position,
pixelRatio: options.suppressHiDPIScaling ? 1 : null
});
_this.screen.applyResolutionAndViewport();
if (options.backgroundColor) {
_this.backgroundColor = options.backgroundColor.clone();
}
_this.enableCanvasTransparency = options.enableCanvasTransparency;
_this._loader = new _Loader__WEBPACK_IMPORTED_MODULE_8__["Loader"]();
_this.debug = new _Debug__WEBPACK_IMPORTED_MODULE_14__["Debug"](_this);
_this._initialize(options);
_this.rootScene = _this.currentScene = new _Scene__WEBPACK_IMPORTED_MODULE_13__["Scene"](_this);
_this.addScene('root', _this.rootScene);
_this.goToScene('root');
return _this;
}
Object.defineProperty(Engine.prototype, "canvasWidth", {
/**
* The width of the game canvas in pixels (physical width component of the
* resolution of the canvas element)
*/
get: function () {
return this.screen.canvasWidth;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Engine.prototype, "halfCanvasWidth", {
/**
* Returns half width of the game canvas in pixels (half physical width component)
*/
get: function () {
return this.screen.halfCanvasWidth;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Engine.prototype, "canvasHeight", {
/**
* The height of the game canvas in pixels, (physical height component of
* the resolution of the canvas element)
*/
get: function () {
return this.screen.canvasHeight;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Engine.prototype, "halfCanvasHeight", {
/**
* Returns half height of the game canvas in pixels (half physical height component)
*/
get: function () {
return this.screen.halfCanvasHeight;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Engine.prototype, "drawWidth", {
/**
* Returns the width of the engine's visible drawing surface in pixels including zoom and device pixel ratio.
*/
get: function () {
return this.screen.drawWidth;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Engine.prototype, "halfDrawWidth", {
/**
* Returns half the width of the engine's visible drawing surface in pixels including zoom and device pixel ratio.
*/
get: function () {
return this.screen.halfDrawWidth;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Engine.prototype, "drawHeight", {
/**
* Returns the height of the engine's visible drawing surface in pixels including zoom and device pixel ratio.
*/
get: function () {
return this.screen.drawHeight;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Engine.prototype, "halfDrawHeight", {
/**
* Returns half the height of the engine's visible drawing surface in pixels including zoom and device pixel ratio.
*/
get: function () {
return this.screen.halfDrawHeight;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Engine.prototype, "isHiDpi", {
/**
* Returns whether excalibur detects the current screen to be HiDPI
*/
get: function () {
return this.screen.isHiDpi;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Engine.prototype, "stats", {
/**
* Access [[stats]] that holds frame statistics.
*/
get: function () {
return this.debug.stats;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Engine.prototype, "isFullscreen", {
/**
* Indicates whether the engine is set to fullscreen or not
*/
get: function () {
return this.screen.isFullScreen;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Engine.prototype, "displayMode", {
/**
* Indicates the current [[DisplayMode]] of the engine.
*/
get: function () {
return this.screen.displayMode;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Engine.prototype, "pixelRatio", {
/**
* Returns the calculated pixel ration for use in rendering
*/
get: function () {
return this.screen.pixelRatio;
},
enumerable: false,
configurable: true
});
Engine.prototype.on = function (eventName, handler) {
_super.prototype.on.call(this, eventName, handler);
};
Engine.prototype.once = function (eventName, handler) {
_super.prototype.once.call(this, eventName, handler);
};
Engine.prototype.off = function (eventName, handler) {
_super.prototype.off.call(this, eventName, handler);
};
/**
* Returns a BoundingBox of the top left corner of the screen
* and the bottom right corner of the screen.
*/
Engine.prototype.getWorldBounds = function () {
return this.screen.getWorldBounds();
};
Object.defineProperty(Engine.prototype, "timescale", {
/**
* Gets the current engine timescale factor (default is 1.0 which is 1:1 time)
*/
get: function () {
return this._timescale;
},
/**
* Sets the current engine timescale factor. Useful for creating slow-motion effects or fast-forward effects
* when using time-based movement.
*/
set: function (value) {
if (value <= 0) {
_Util_Log__WEBPACK_IMPORTED_MODULE_11__["Logger"].getInstance().error('Cannot set engine.timescale to a value of 0 or less than 0.');
return;
}
this._timescale = value;
},
enumerable: false,
configurable: true
});
/**
* Plays a sprite animation on the screen at the specified `x` and `y`
* (in game coordinates, not screen pixels). These animations play
* independent of actors, and will be cleaned up internally as soon
* as they are complete. Note animations that loop will never be
* cleaned up.
*
* @param animation Animation to play
* @param x x game coordinate to play the animation
* @param y y game coordinate to play the animation
*/
Engine.prototype.playAnimation = function (animation, x, y) {
this._animations.push(new AnimationNode(animation, x, y));
};
/**
* Adds a [[TileMap]] to the [[currentScene]], once this is done the TileMap
* will be drawn and updated.
*/
Engine.prototype.addTileMap = function (tileMap) {
this.currentScene.addTileMap(tileMap);
};
/**
* Removes a [[TileMap]] from the [[currentScene]], it will no longer be drawn or updated.
*/
Engine.prototype.removeTileMap = function (tileMap) {
this.currentScene.removeTileMap(tileMap);
};
/**
* Adds a [[Timer]] to the [[currentScene]].
* @param timer The timer to add to the [[currentScene]].
*/
Engine.prototype.addTimer = function (timer) {
return this.currentScene.addTimer(timer);
};
/**
* Removes a [[Timer]] from the [[currentScene]].
* @param timer The timer to remove to the [[currentScene]].
*/
Engine.prototype.removeTimer = function (timer) {
return this.currentScene.removeTimer(timer);
};
/**
* Adds a [[Scene]] to the engine, think of scenes in Excalibur as you
* would levels or menus.
*
* @param key The name of the scene, must be unique
* @param scene The scene to add to the engine
*/
Engine.prototype.addScene = function (key, scene) {
if (this.scenes[key]) {
this._logger.warn('Scene', key, 'already exists overwriting');
}
this.scenes[key] = scene;
};
/**
* @internal
*/
Engine.prototype.removeScene = function (entity) {
if (entity instanceof _Scene__WEBPACK_IMPORTED_MODULE_13__["Scene"]) {
// remove scene
for (var key in this.scenes) {
if (this.scenes.hasOwnProperty(key)) {
if (this.scenes[key] === entity) {
delete this.scenes[key];
}
}
}
}
if (typeof entity === 'string') {
// remove scene
delete this.scenes[entity];
}
};
Engine.prototype.add = function (entity) {
if (entity instanceof _ScreenElement__WEBPACK_IMPORTED_MODULE_4__["ScreenElement"]) {
this.currentScene.addScreenElement(entity);
return;
}
if (entity instanceof _Actor__WEBPACK_IMPORTED_MODULE_5__["Actor"]) {
this._addChild(entity);
}
if (entity instanceof _Timer__WEBPACK_IMPORTED_MODULE_6__["Timer"]) {
this.addTimer(entity);
}
if (entity instanceof _TileMap__WEBPACK_IMPORTED_MODULE_7__["TileMap"]) {
this.addTileMap(entity);
}
if (arguments.length === 2) {
this.addScene(arguments[0], arguments[1]);
}
};
Engine.prototype.remove = function (entity) {
if (entity instanceof _ScreenElement__WEBPACK_IMPORTED_MODULE_4__["ScreenElement"]) {
this.currentScene.removeScreenElement(entity);
return;
}
if (entity instanceof _Actor__WEBPACK_IMPORTED_MODULE_5__["Actor"]) {
this._removeChild(entity);
}
if (entity instanceof _Timer__WEBPACK_IMPORTED_MODULE_6__["Timer"]) {
this.removeTimer(entity);
}
if (entity instanceof _TileMap__WEBPACK_IMPORTED_MODULE_7__["TileMap"]) {
this.removeTileMap(entity);
}
if (entity instanceof _Scene__WEBPACK_IMPORTED_MODULE_13__["Scene"]) {
this.removeScene(entity);
}
if (typeof entity === 'string') {
this.removeScene(entity);
}
};
/**
* Adds an actor to the [[currentScene]] of the game. This is synonymous
* to calling `engine.currentScene.add(actor)`.
*
* Actors can only be drawn if they are a member of a scene, and only
* the [[currentScene]] may be drawn or updated.
*
* @param actor The actor to add to the [[currentScene]]
*/
Engine.prototype._addChild = function (actor) {
this.currentScene.add(actor);
};
/**
* Removes an actor from the [[currentScene]] of the game. This is synonymous
* to calling `engine.currentScene.remove(actor)`.
* Actors that are removed from a scene will no longer be drawn or updated.
*
* @param actor The actor to remove from the [[currentScene]].
*/
Engine.prototype._removeChild = function (actor) {
this.currentScene.remove(actor);
};
/**
* Changes the currently updating and drawing scene to a different,
* named scene. Calls the [[Scene]] lifecycle events.
* @param key The key of the scene to transition to.
*/
Engine.prototype.goToScene = function (key) {
if (this.scenes[key]) {
var oldScene = this.currentScene;
var newScene = this.scenes[key];
this._logger.debug('Going to scene:', key);
// only deactivate when initialized
if (this.currentScene.isInitialized) {
this.currentScene._deactivate.call(this.currentScene, [oldScene, newScene]);
this.currentScene.eventDispatcher.emit('deactivate', new _Events__WEBPACK_IMPORTED_MODULE_10__["DeactivateEvent"](newScene, this.currentScene));
}
// set current scene to new one
this.currentScene = newScene;
this.screen.setCurrentCamera(newScene.camera);
// initialize the current scene if has not been already
this.currentScene._initialize(this);
this.currentScene._activate.call(this.currentScene, [oldScene, newScene]);
this.currentScene.eventDispatcher.emit('activate', new _Events__WEBPACK_IMPORTED_MODULE_10__["ActivateEvent"](oldScene, this.currentScene));
}
else {
this._logger.error('Scene', key, 'does not exist!');
}
};
/**
* Transforms the current x, y from screen coordinates to world coordinates
* @param point Screen coordinate to convert
*/
Engine.prototype.screenToWorldCoordinates = function (point) {
return this.screen.screenToWorldCoordinates(point);
};
/**
* Transforms a world coordinate, to a screen coordinate
* @param point World coordinate to convert
*/
Engine.prototype.worldToScreenCoordinates = function (point) {
return this.screen.worldToScreenCoordinates(point);
};
/**
* Initializes the internal canvas, rendering context, display mode, and native event listeners
*/
Engine.prototype._initialize = function (options) {
var _this = this;
this.pageScrollPreventionMode = options.scrollPreventionMode;
// initialize inputs
this.input = {
keyboard: new _Input_Index__WEBPACK_IMPORTED_MODULE_16__["Keyboard"](),
pointers: new _Input_Index__WEBPACK_IMPORTED_MODULE_16__["Pointers"](this),
gamepads: new _Input_Index__WEBPACK_IMPORTED_MODULE_16__["Gamepads"]()
};
this.input.keyboard.init();
this.input.pointers.init(options && options.pointerScope === _Input_Index__WEBPACK_IMPORTED_MODULE_16__["PointerScope"].Document ? document : this.canvas);
this.input.gamepads.init();
// Issue #385 make use of the visibility api
// https://developer.mozilla.org/en-US/docs/Web/Guide/User_experience/Using_the_Page_Visibility_API
var hidden, visibilityChange;
if (typeof document.hidden !== 'undefined') {
// Opera 12.10 and Firefox 18 and later support
hidden = 'hidden';
visibilityChange = 'visibilitychange';
}
else if ('msHidden' in document) {
hidden = 'msHidden';
visibilityChange = 'msvisibilitychange';
}
else if ('webkitHidden' in document) {
hidden = 'webkitHidden';
visibilityChange = 'webkitvisibilitychange';
}
this.browser.document.on(visibilityChange, function () {
if (document[hidden]) {
_this.eventDispatcher.emit('hidden', new _Events__WEBPACK_IMPORTED_MODULE_10__["HiddenEvent"](_this));
_this._logger.debug('Window hidden');
}
else {
_this.eventDispatcher.emit('visible', new _Events__WEBPACK_IMPORTED_MODULE_10__["VisibleEvent"](_this));
_this._logger.debug('Window visible');
}
});
if (!this.canvasElementId && !options.canvasElement) {
document.body.appendChild(this.canvas);
}
};
Engine.prototype.onInitialize = function (_engine) {
// Override me
};
/**
* If supported by the browser, this will set the antialiasing flag on the
* canvas. Set this to `false` if you want a 'jagged' pixel art look to your
* image resources.
* @param isSmooth Set smoothing to true or false
*/
Engine.prototype.setAntialiasing = function (isSmooth) {
this.screen.antialiasing = isSmooth;
};
/**
* Return the current smoothing status of the canvas
*/
Engine.prototype.getAntialiasing = function () {
return this.screen.antialiasing;
};
Object.defineProperty(Engine.prototype, "isInitialized", {
/**
* Gets whether the actor is Initialized
*/
get: function () {
return this._isInitialized;
},
enumerable: false,
configurable: true
});
Engine.prototype._overrideInitialize = function (engine) {
if (!this.isInitialized) {
this.onInitialize(engine);
_super.prototype.emit.call(this, 'initialize', new _Events__WEBPACK_IMPORTED_MODULE_10__["InitializeEvent"](engine, this));
this._isInitialized = true;
}
};
/**
* Updates the entire state of the game
* @param delta Number of milliseconds elapsed since the last update.
*/
Engine.prototype._update = function (delta) {
if (this._isLoading) {
// suspend updates until loading is finished
this._loader.update(this, delta);
// Update input listeners
this.input.keyboard.update();
this.input.pointers.update();
this.input.gamepads.update();
return;
}
this._overrideInitialize(this);
// Publish preupdate events
this._preupdate(delta);
// process engine level events
this.currentScene.update(this, delta);
// update animations
// TODO remove
this._animations = this._animations.filter(function (a) {
return !a.animation.isDone();
});
// Update input listeners
this.input.keyboard.update();
this.input.pointers.update();
this.input.gamepads.update();
// Publish update event
this._postupdate(delta);
};
/**
* @internal
*/
Engine.prototype._preupdate = function (delta) {
this.emit('preupdate', new _Events__WEBPACK_IMPORTED_MODULE_10__["PreUpdateEvent"](this, delta, this));
this.onPreUpdate(this, delta);
};
Engine.prototype.onPreUpdate = function (_engine, _delta) {
// Override me
};
/**
* @internal
*/
Engine.prototype._postupdate = function (delta) {
this.emit('postupdate', new _Events__WEBPACK_IMPORTED_MODULE_10__["PostUpdateEvent"](this, delta, this));
this.onPostUpdate(this, delta);
};
Engine.prototype.onPostUpdate = function (_engine, _delta) {
// Override me
};
/**
* Draws the entire game
* @param delta Number of milliseconds elapsed since the last draw.
*/
Engine.prototype._draw = function (delta) {
var ctx = this.ctx;
this._predraw(ctx, delta);
if (this._isLoading) {
this._loader.draw(ctx, delta);
// Drawing nothing else while loading
return;
}
ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
ctx.fillStyle = this.backgroundColor.toString();
ctx.fillRect(0, 0, this.canvasWidth, this.canvasHeight);
this.currentScene.draw(this.ctx, delta);
// todo needs to be a better way of doing this
var a = 0;
var len = this._animations.length;
for (a; a < len; a++) {
this._animations[a].animation.draw(ctx, this._animations[a].x, this._animations[a].y);
}
// Draw debug information
if (this.isDebug) {
this.ctx.font = 'Consolas';
this.ctx.fillStyle = this.debugColor.toString();
var keys = this.input.keyboard.getKeys();
for (var j = 0; j < keys.length; j++) {
this.ctx.fillText(keys[j].toString() + ' : ' + (_Input_Index__WEBPACK_IMPORTED_MODULE_16__["Keys"][keys[j]] ? _Input_Index__WEBPACK_IMPORTED_MODULE_16__["Keys"][keys[j]] : 'Not Mapped'), 100, 10 * j + 10);
}
this.ctx.fillText('FPS:' + this.stats.currFrame.fps.toFixed(2).toString(), 10, 10);
}
// Post processing
for (var i = 0; i < this.postProcessors.length; i++) {
this.postProcessors[i].process(this.ctx.getImageData(0, 0, this.canvasWidth, this.canvasHeight), this.ctx);
}
this._postdraw(ctx, delta);
};
/**
* @internal
*/
Engine.prototype._predraw = function (_ctx, delta) {
this.emit('predraw', new _Events__WEBPACK_IMPORTED_MODULE_10__["PreDrawEvent"](_ctx, delta, this));
this.onPreDraw(_ctx, delta);
};
Engine.prototype.onPreDraw = function (_ctx, _delta) {
// Override me
};
/**
* @internal
*/
Engine.prototype._postdraw = function (_ctx, delta) {
this.emit('postdraw', new _Events__WEBPACK_IMPORTED_MODULE_10__["PostDrawEvent"](_ctx, delta, this));
this.onPostDraw(_ctx, delta);
};
Engine.prototype.onPostDraw = function (_ctx, _delta) {
// Override me
};
/**
* Starts the internal game loop for Excalibur after loading
* any provided assets.
* @param loader Optional [[Loader]] to use to load resources. The default loader is [[Loader]], override to provide your own
* custom loader.
*/
Engine.prototype.start = function (loader) {
var _this = this;
if (!this._compatible) {
var promise = new _Promises__WEBPACK_IMPORTED_MODULE_2__["Promise"]();
return promise.reject('Excalibur is incompatible with your browser');
}
// Changing resolution invalidates context state, so we need to capture it before applying
this.screen.pushResolutionAndViewport();
this.screen.resolution = this.screen.viewport;
this.screen.applyResolutionAndViewport();
var loadingComplete;
if (loader) {
this._loader = loader;
this._loader.suppressPlayButton = this._suppressPlayButton || this._loader.suppressPlayButton;
this._loader.wireEngine(this);
loadingComplete = this.load(this._loader);
}
else {
loadingComplete = _Promises__WEBPACK_IMPORTED_MODULE_2__["Promise"].resolve();
}
loadingComplete.then(function () {
_this.screen.popResolutionAndViewport();
_this.screen.applyResolutionAndViewport();
_this.emit('start', new _Events__WEBPACK_IMPORTED_MODULE_10__["GameStartEvent"](_this));
});
if (!this._hasStarted) {
this._hasStarted = true;
this._logger.debug('Starting game...');
this.browser.resume();
Engine.createMainLoop(this, window.requestAnimationFrame, Date.now)();
this._logger.debug('Game started');
}
else {
// Game already started;
}
return loadingComplete;
};
Engine.createMainLoop = function (game, raf, nowFn) {
var lastTime = nowFn();
return function mainloop() {
if (!game._hasStarted) {
return;
}
try {
game._requestId = raf(mainloop);
game.emit('preframe', new _Events__WEBPACK_IMPORTED_MODULE_10__["PreFrameEvent"](game, game.stats.prevFrame));
// Get the time to calculate time-elapsed
var now = nowFn();
var elapsed = Math.floor(now - lastTime) || 1;
// Resolves issue #138 if the game has been paused, or blurred for
// more than a 200 milliseconds, reset elapsed time to 1. This improves reliability
// and provides more expected behavior when the engine comes back
// into focus
if (elapsed > 200) {
elapsed = 1;
}
var delta = elapsed * game.timescale;
// reset frame stats (reuse existing instances)
var frameId = game.stats.prevFrame.id + 1;
game.stats.currFrame.reset();
game.stats.currFrame.id = frameId;
game.stats.currFrame.delta = delta;
game.stats.currFrame.fps = 1.0 / (delta / 1000);
var beforeUpdate = nowFn();
game._update(delta);
var afterUpdate = nowFn();
game._draw(delta);
var afterDraw = nowFn();
game.stats.currFrame.duration.update = afterUpdate - beforeUpdate;
game.stats.currFrame.duration.draw = afterDraw - afterUpdate;
lastTime = now;
game.emit('postframe', new _Events__WEBPACK_IMPORTED_MODULE_10__["PostFrameEvent"](game, game.stats.currFrame));
game.stats.prevFrame.reset(game.stats.currFrame);
}
catch (e) {
window.cancelAnimationFrame(game._requestId);
game.stop();
game.onFatalException(e);
}
};
};
/**
* Stops Excalibur's main loop, useful for pausing the game.
*/
Engine.prototype.stop = function () {
if (this._hasStarted) {
this.emit('stop', new _Events__WEBPACK_IMPORTED_MODULE_10__["GameStopEvent"](this));
this.browser.pause();
this._hasStarted = false;
this._logger.debug('Game stopped');
}
};
/**
* Returns the Engine's Running status, Useful for checking whether engine is running or paused.
*/
Engine.prototype.isPaused = function () {
return !this._hasStarted;
};
/**
* Takes a screen shot of the current viewport and returns it as an
* HTML Image Element.
*/
Engine.prototype.screenshot = function () {
var result = new Image();
var raw = this.canvas.toDataURL('image/png');
result.src = raw;
return result;
};
/**
* Another option available to you to load resources into the game.
* Immediately after calling this the game will pause and the loading screen
* will appear.
* @param loader Some [[Loadable]] such as a [[Loader]] collection, [[Sound]], or [[Texture]].
*/
Engine.prototype.load = function (loader) {
var _this = this;
var complete = new _Promises__WEBPACK_IMPORTED_MODULE_2__["Promise"]();
this._isLoading = true;
loader.load().then(function () {
if (_this._suppressPlayButton) {
setTimeout(function () {
_this._isLoading = false;
complete.resolve();
// Delay is to give the logo a chance to show, otherwise don't delay
}, 500);
}
else {
_this._isLoading = false;
complete.resolve();
}
});
return complete;
};
/**
* Default [[EngineOptions]]
*/
Engine._DefaultEngineOptions = {
width: 0,
height: 0,
enableCanvasTransparency: true,
canvasElementId: '',
canvasElement: undefined,
pointerScope: _Input_Index__WEBPACK_IMPORTED_MODULE_16__["PointerScope"].Document,
suppressConsoleBootMessage: null,
suppressMinimumBrowserFeatureDetection: null,
suppressHiDPIScaling: null,
suppressPlayButton: null,
scrollPreventionMode: ScrollPreventionMode.Canvas,
backgroundColor: _Drawing_Color__WEBPACK_IMPORTED_MODULE_12__["Color"].fromHex('#2185d0') // Excalibur blue
};
return Engine;
}(_Class__WEBPACK_IMPORTED_MODULE_15__["Class"]));
/**
* @internal
*/
var AnimationNode = /** @class */ (function () {
function AnimationNode(animation, x, y) {
this.animation = animation;
this.x = x;
this.y = y;
}
return AnimationNode;
}());
/***/ }),
/***/ "./EntityComponentSystem/Component.ts":
/*!********************************************!*\
!*** ./EntityComponentSystem/Component.ts ***!
\********************************************/
/*! exports provided: Component, TagComponent */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Component", function() { return Component; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TagComponent", function() { return TagComponent; });
var __extends = (undefined && undefined.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
function hasClone(x) {
return !!(x === null || x === void 0 ? void 0 : x.clone);
}
/**
* Components are containers for state in Excalibur, the are meant to convey capabilities that an Entity posesses
*
* Implementations of Component must have a zero-arg constructor
*/
var Component = /** @class */ (function () {
function Component() {
}
Component.prototype.clone = function () {
var newComponent = new this.constructor();
for (var prop in this) {
if (this.hasOwnProperty(prop)) {
var val = this[prop];
if (hasClone(val) && prop !== 'owner' && prop !== 'clone') {
newComponent[prop] = val.clone();
}
else {
newComponent[prop] = val;
}
}
}
return newComponent;
};
return Component;
}());
/**
* Tag components are a way of tagging a component with label and a simple value
*/
var TagComponent = /** @class */ (function (_super) {
__extends(TagComponent, _super);
function TagComponent(type, value) {
var _this = _super.call(this) || this;
_this.type = type;
_this.value = value;
return _this;
}
return TagComponent;
}(Component));
/***/ }),
/***/ "./EntityComponentSystem/Entity.ts":
/*!*****************************************!*\
!*** ./EntityComponentSystem/Entity.ts ***!
\*****************************************/
/*! exports provided: AddedComponent, isAddedComponent, RemovedComponent, isRemovedComponent, Entity */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AddedComponent", function() { return AddedComponent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isAddedComponent", function() { return isAddedComponent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RemovedComponent", function() { return RemovedComponent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isRemovedComponent", function() { return isRemovedComponent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Entity", function() { return Entity; });
/* harmony import */ var _Component__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Component */ "./EntityComponentSystem/Component.ts");
/* harmony import */ var _Util_Observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Util/Observable */ "./Util/Observable.ts");
/* harmony import */ var _Class__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Class */ "./Class.ts");
/* harmony import */ var _Events__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Events */ "./Events.ts");
var __extends = (undefined && undefined.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var AddedComponent = /** @class */ (function () {
function AddedComponent(data) {
this.data = data;
this.type = 'Component Added';
}
return AddedComponent;
}());
function isAddedComponent(x) {
return !!x && x.type === 'Component Added';
}
var RemovedComponent = /** @class */ (function () {
function RemovedComponent(data) {
this.data = data;
this.type = 'Component Removed';
}
return RemovedComponent;
}());
function isRemovedComponent(x) {
return !!x && x.type === 'Component Removed';
}
var Entity = /** @class */ (function (_super) {
__extends(Entity, _super);
function Entity() {
var _this = _super !== null && _super.apply(this, arguments) || this;
/**
* The unique identifier for the entity
*/
_this.id = Entity._ID++;
/**
* Whether this entity is active, if set to false it will be reclaimed
*/
_this.active = true;
_this._componentsToRemove = [];
_this._typesMemo = [];
_this._dirty = true;
_this._handleChanges = {
defineProperty: function (obj, prop, descriptor) {
obj[prop] = descriptor.value;
_this.changes.notifyAll(new AddedComponent({
component: descriptor.value,
entity: _this
}));
return true;
},
deleteProperty: function (obj, prop) {
if (prop in obj) {
_this.changes.notifyAll(new RemovedComponent({
component: obj[prop],
entity: _this
}));
delete obj[prop];
return true;
}
return false;
}
};
_this.components = new Proxy({}, _this._handleChanges);
_this.changes = new _Util_Observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
_this._isInitialized = false;
return _this;
}
Entity.prototype.kill = function () {
this.active = false;
};
Entity.prototype.isKilled = function () {
return !this.active;
};
Object.defineProperty(Entity.prototype, "types", {
/**
* The types of the components on the Entity
*/
get: function () {
return this._dirty ? (this._typesMemo = Object.keys(this.components)) : this._typesMemo;
},
enumerable: false,
configurable: true
});
/**
* Creates a deep copy of the entity and a copy of all its components
*/
Entity.prototype.clone = function () {
var newEntity = new Entity();
for (var _i = 0, _a = this.types; _i < _a.length; _i++) {
var c = _a[_i];
newEntity.addComponent(this.components[c].clone());
}
return newEntity;
};
Entity.prototype.addComponent = function (componentOrEntity, force) {
if (force === void 0) { force = false; }
// If you use an entity as a "prefab" or template
if (componentOrEntity instanceof Entity) {
for (var c in componentOrEntity.components) {
this.addComponent(componentOrEntity.components[c].clone());
}
// Normal component case
}
else {
// if component already exists, skip if not forced
if (this.components[componentOrEntity.type] && !force) {
return this;
}
// Remove existing component type if exists when forced
if (this.components[componentOrEntity.type] && force) {
this.removeComponent(componentOrEntity);
}
// todo circular dependencies will be a problem
if (componentOrEntity.dependencies && componentOrEntity.dependencies.length) {
for (var _i = 0, _a = componentOrEntity.dependencies; _i < _a.length; _i++) {
var ctor = _a[_i];
this.addComponent(new ctor());
this._dirty = true;
}
}
componentOrEntity.owner = this;
this.components[componentOrEntity.type] = componentOrEntity;
if (componentOrEntity.onAdd) {
this._dirty = true;
componentOrEntity.onAdd(this);
}
}
return this;
};
/**
* Removes a component from the entity, by default removals are deferred to the end of entity processing to avoid consistency issues
*
* Components can be force removed with the `force` flag, the removal is not deferred and happens immediately
* @param componentOrType
* @param force
*/
Entity.prototype.removeComponent = function (componentOrType, force) {
if (force === void 0) { force = false; }
if (force) {
if (typeof componentOrType === 'string') {
this._removeComponentByType(componentOrType);
}
else if (componentOrType instanceof _Component__WEBPACK_IMPORTED_MODULE_0__["Component"]) {
this._removeComponentByType(componentOrType.type);
}
}
else {
this._componentsToRemove.push(componentOrType);
}
return this;
};
Entity.prototype._removeComponentByType = function (type) {
if (this.components[type]) {
this.components[type].owner = null;
if (this.components[type].onRemove) {
this.components[type].onRemove(this);
}
delete this.components[type];
this._dirty = true;
}
};
/**
* @hidden
* @internal
*/
Entity.prototype.processRemoval = function () {
for (var _i = 0, _a = this._componentsToRemove; _i < _a.length; _i++) {
var componentOrType = _a[_i];
var type = typeof componentOrType === 'string' ? componentOrType : componentOrType.type;
this._removeComponentByType(type);
}
this._componentsToRemove.length = 0;
};
Entity.prototype.has = function (type) {
return !!this.components[type];
};
Object.defineProperty(Entity.prototype, "isInitialized", {
/**
* Gets whether the actor is Initialized
*/
get: function () {
return this._isInitialized;
},
enumerable: false,
configurable: true
});
/**
* Initializes this entity, meant to be called by the Scene before first update not by users of Excalibur.
*
* It is not recommended that internal excalibur methods be overriden, do so at your own risk.
*
* @internal
*/
Entity.prototype._initialize = function (engine) {
if (!this.isInitialized) {
this.onInitialize(engine);
_super.prototype.emit.call(this, 'initialize', new _Events__WEBPACK_IMPORTED_MODULE_3__["InitializeEvent"](engine, this));
this._isInitialized = true;
}
};
/**
* It is not recommended that internal excalibur methods be overriden, do so at your own risk.
*
* Internal _preupdate handler for [[onPreUpdate]] lifecycle event
* @internal
*/
Entity.prototype._preupdate = function (engine, delta) {
this.emit('preupdate', new _Events__WEBPACK_IMPORTED_MODULE_3__["PreUpdateEvent"](engine, delta, this));
this.onPreUpdate(engine, delta);
};
/**
* It is not recommended that internal excalibur methods be overriden, do so at your own risk.
*
* Internal _preupdate handler for [[onPostUpdate]] lifecycle event
* @internal
*/
Entity.prototype._postupdate = function (engine, delta) {
this.emit('postupdate', new _Events__WEBPACK_IMPORTED_MODULE_3__["PostUpdateEvent"](engine, delta, this));
this.onPostUpdate(engine, delta);
};
/**
* `onInitialize` is called before the first update of the entity. This method is meant to be
* overridden.
*
* Synonymous with the event handler `.on('initialize', (evt) => {...})`
*/
Entity.prototype.onInitialize = function (_engine) {
// Override me
};
/**
* Safe to override onPreUpdate lifecycle event handler. Synonymous with `.on('preupdate', (evt) =>{...})`
*
* `onPreUpdate` is called directly before an entity is updated.
*/
Entity.prototype.onPreUpdate = function (_engine, _delta) {
// Override me
};
/**
* Safe to override onPostUpdate lifecycle event handler. Synonymous with `.on('postupdate', (evt) =>{...})`
*
* `onPostUpdate` is called directly after an entity is updated.
*/
Entity.prototype.onPostUpdate = function (_engine, _delta) {
// Override me
};
Entity._ID = 0;
return Entity;
}(_Class__WEBPACK_IMPORTED_MODULE_2__["Class"]));
/***/ }),
/***/ "./EntityComponentSystem/EntityManager.ts":
/*!************************************************!*\
!*** ./EntityComponentSystem/EntityManager.ts ***!
\************************************************/
/*! exports provided: EntityManager */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EntityManager", function() { return EntityManager; });
/* harmony import */ var _Entity__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Entity */ "./EntityComponentSystem/Entity.ts");
/* harmony import */ var ___WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! .. */ "./index.ts");
// Add/Remove entitys and components
var EntityManager = /** @class */ (function () {
function EntityManager(_scene) {
this._scene = _scene;
this.entities = [];
this._entityIndex = {};
}
/**
* EntityManager observes changes on entities
* @param message
*/
EntityManager.prototype.notify = function (message) {
if (Object(_Entity__WEBPACK_IMPORTED_MODULE_0__["isAddedComponent"])(message)) {
// we don't need the component, it's already on the entity
this._scene.queryManager.addEntity(message.data.entity);
}
if (Object(_Entity__WEBPACK_IMPORTED_MODULE_0__["isRemovedComponent"])(message)) {
this._scene.queryManager.removeComponent(message.data.entity, message.data.component);
}
};
/**
* Adds an entity to be tracked by the EntityManager
* @param entity
*/
EntityManager.prototype.addEntity = function (entity) {
if (entity) {
this._entityIndex[entity.id] = entity;
this.entities.push(entity);
this._scene.queryManager.addEntity(entity);
entity.changes.register(this);
}
};
EntityManager.prototype.removeEntity = function (idOrEntity) {
var id = 0;
if (idOrEntity instanceof _Entity__WEBPACK_IMPORTED_MODULE_0__["Entity"]) {
id = idOrEntity.id;
}
else {
id = idOrEntity;
}
var entity = this._entityIndex[id];
delete this._entityIndex[id];
if (entity) {
___WEBPACK_IMPORTED_MODULE_1__["Util"].removeItemFromArray(entity, this.entities);
this._scene.queryManager.removeEntity(entity);
entity.changes.unregister(this);
}
};
EntityManager.prototype.processRemovals = function () {
for (var _i = 0, _a = this.entities; _i < _a.length; _i++) {
var entity = _a[_i];
entity.processRemoval();
}
};
EntityManager.prototype.getById = function (id) {
return this._entityIndex[id];
};
return EntityManager;
}());
/***/ }),
/***/ "./EntityComponentSystem/Query.ts":
/*!****************************************!*\
!*** ./EntityComponentSystem/Query.ts ***!
\****************************************/
/*! exports provided: Query */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Query", function() { return Query; });
/* harmony import */ var _Entity__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Entity */ "./EntityComponentSystem/Entity.ts");
/* harmony import */ var _Util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Util */ "./EntityComponentSystem/Util.ts");
/* harmony import */ var _Util_Observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Util/Observable */ "./Util/Observable.ts");
/* harmony import */ var ___WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! .. */ "./index.ts");
/* harmony import */ var _System__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./System */ "./EntityComponentSystem/System.ts");
var __extends = (undefined && undefined.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
/**
* Represents query for entities that match a list of types that is cached and observable
*
* Queries can be strongly typed by supplying a type union in the optional type parameter
* ```typescript
* const queryAB = new ex.Query<ComponentTypeA, ComponentTypeB>(['A', 'B']);
* ```
*/
var Query = /** @class */ (function (_super) {
__extends(Query, _super);
function Query(types) {
var _this = _super.call(this) || this;
_this.types = types;
_this.entities = [];
return _this;
}
Object.defineProperty(Query.prototype, "key", {
get: function () {
return Object(_Util__WEBPACK_IMPORTED_MODULE_1__["buildTypeKey"])(this.types);
},
enumerable: false,
configurable: true
});
/**
* Add an entity to the query, will only be added if the entity matches the query types
* @param entity
*/
Query.prototype.addEntity = function (entity) {
if (!___WEBPACK_IMPORTED_MODULE_3__["Util"].contains(this.entities, entity) && this.matches(entity)) {
this.entities.push(entity);
this.notifyAll(new _System__WEBPACK_IMPORTED_MODULE_4__["AddedEntity"](entity));
}
};
/**
* If the entity is part of the query it will be removed regardless of types
* @param entity
*/
Query.prototype.removeEntity = function (entity) {
if (___WEBPACK_IMPORTED_MODULE_3__["Util"].removeItemFromArray(entity, this.entities)) {
this.notifyAll(new _System__WEBPACK_IMPORTED_MODULE_4__["RemovedEntity"](entity));
}
};
/**
* Removes all entities and observers from the query
*/
Query.prototype.clear = function () {
this.entities.length = 0;
for (var _i = 0, _a = this.observers; _i < _a.length; _i++) {
var observer = _a[_i];
this.unregister(observer);
}
};
Query.prototype.matches = function (typesOrEntity) {
var types = [];
if (typesOrEntity instanceof _Entity__WEBPACK_IMPORTED_MODULE_0__["Entity"]) {
types = typesOrEntity.types;
}
else {
types = typesOrEntity;
}
var matches = true;
for (var _i = 0, _a = this.types; _i < _a.length; _i++) {
var type = _a[_i];
matches = matches && types.indexOf(type) > -1;
if (!matches) {
return false;
}
}
return matches;
};
return Query;
}(_Util_Observable__WEBPACK_IMPORTED_MODULE_2__["Observable"]));
/***/ }),
/***/ "./EntityComponentSystem/QueryManager.ts":
/*!***********************************************!*\
!*** ./EntityComponentSystem/QueryManager.ts ***!
\***********************************************/
/*! exports provided: QueryManager */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "QueryManager", function() { return QueryManager; });
/* harmony import */ var _Util__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Util */ "./EntityComponentSystem/Util.ts");
/* harmony import */ var _Query__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Query */ "./EntityComponentSystem/Query.ts");
/**
* The query manager is responsible for updating all queries when entities/components change
*/
var QueryManager = /** @class */ (function () {
function QueryManager(scene) {
this.scene = scene;
this._queries = {};
}
/**
* Adds a query to the manager and populates with any entities that match
* @param query
*/
QueryManager.prototype._addQuery = function (query) {
this._queries[Object(_Util__WEBPACK_IMPORTED_MODULE_0__["buildTypeKey"])(query.types)] = query;
for (var _i = 0, _a = this.scene.entityManager.entities; _i < _a.length; _i++) {
var entity = _a[_i];
query.addEntity(entity);
}
};
/**
* Removes the query if there are no observers left
* @param query
*/
QueryManager.prototype.maybeRemoveQuery = function (query) {
if (query.observers.length === 0) {
query.clear();
delete this._queries[Object(_Util__WEBPACK_IMPORTED_MODULE_0__["buildTypeKey"])(query.types)];
}
};
/**
* Adds the entity to any matching query in the query manage
* @param entity
*/
QueryManager.prototype.addEntity = function (entity) {
for (var queryType in this._queries) {
if (this._queries[queryType]) {
this._queries[queryType].addEntity(entity);
}
}
};
/**
* Removes an entity from queries if the removed component disqualifies it
* @param entity
* @param component
*/
QueryManager.prototype.removeComponent = function (entity, component) {
for (var queryType in this._queries) {
if (this._queries[queryType].matches(entity.types.concat([component.type]))) {
this._queries[queryType].removeEntity(entity);
}
}
};
/**
* Removes an entity from all queries it is currently a part of
* @param entity
*/
QueryManager.prototype.removeEntity = function (entity) {
for (var queryType in this._queries) {
if (this._queries[queryType].entities.indexOf(entity) > -1) {
this._queries[queryType].removeEntity(entity);
}
}
};
/**
* Creates a populated query and returns, if the query already exists that will be returned instead of a new instance
* @param types
*/
QueryManager.prototype.createQuery = function (types) {
var maybeExistingQuery = this.getQuery(types);
if (maybeExistingQuery) {
return maybeExistingQuery;
}
var query = new _Query__WEBPACK_IMPORTED_MODULE_1__["Query"](types);
this._addQuery(query);
return query;
};
/**
* Retrieves an existing query by types if it exists otherwise returns null
* @param types
*/
QueryManager.prototype.getQuery = function (types) {
var key = Object(_Util__WEBPACK_IMPORTED_MODULE_0__["buildTypeKey"])(types);
if (this._queries[key]) {
return this._queries[key];
}
return null;
};
return QueryManager;
}());
/***/ }),
/***/ "./EntityComponentSystem/System.ts":
/*!*****************************************!*\
!*** ./EntityComponentSystem/System.ts ***!
\*****************************************/
/*! exports provided: SystemType, System, AddedEntity, isAddedSystemEntity, RemovedEntity, isRemoveSystemEntity */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SystemType", function() { return SystemType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "System", function() { return System; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AddedEntity", function() { return AddedEntity; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isAddedSystemEntity", function() { return isAddedSystemEntity; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RemovedEntity", function() { return RemovedEntity; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isRemoveSystemEntity", function() { return isRemoveSystemEntity; });
var SystemType;
(function (SystemType) {
SystemType["Update"] = "update";
SystemType["Draw"] = "draw";
})(SystemType || (SystemType = {}));
/**
* An Excalibur [[System]] that updates entities of certain types.
* Systems are scene specific
*/
var System = /** @class */ (function () {
function System() {
/**
* System can execute in priority order, by default all systems are priority 0. Lower values indicated higher priority.
* For a system to execute before all other a lower priority value (-1 for example) must be set.
* For a system to exectue after all other a higher priority value (10 for example) must be set.
*/
this.priority = 0;
}
/**
* Systems observe when entities match their types or no longer match their types, override
* @param _entityAddedOrRemoved
*/
System.prototype.notify = function (_entityAddedOrRemoved) {
// Override me
};
return System;
}());
/**
* An [[Entity]] with [[Component]] types that matches a [[System]] types exists in the current scene.
*/
var AddedEntity = /** @class */ (function () {
function AddedEntity(data) {
this.data = data;
this.type = 'Entity Added';
}
return AddedEntity;
}());
function isAddedSystemEntity(x) {
return !!x && x.type === 'Entity Added';
}
/**
* An [[Entity]] with [[Component]] types that no longer matches a [[System]] types exists in the current scene.
*/
var RemovedEntity = /** @class */ (function () {
function RemovedEntity(data) {
this.data = data;
this.type = 'Entity Removed';
}
return RemovedEntity;
}());
function isRemoveSystemEntity(x) {
return !!x && x.type === 'Entity Removed';
}
/***/ }),
/***/ "./EntityComponentSystem/SystemManager.ts":
/*!************************************************!*\
!*** ./EntityComponentSystem/SystemManager.ts ***!
\************************************************/
/*! exports provided: SystemManager */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SystemManager", function() { return SystemManager; });
/* harmony import */ var ___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! .. */ "./index.ts");
/**
* The SystemManager is responsible for keeping track of all systems in a scene.
* Systems are scene specific
*/
var SystemManager = /** @class */ (function () {
function SystemManager(_scene) {
this._scene = _scene;
this.systems = [];
}
/**
* Adds a system to the manager, it will now be updated every frame
* @param system
*/
SystemManager.prototype.addSystem = function (system) {
// validate system has types
if (!system.types || system.types.length === 0) {
throw new Error("Attempted to add a System without any types");
}
var query = this._scene.queryManager.createQuery(system.types);
this.systems.push(system);
// TODO polyfil stable .sort(), this mechanism relies on a stable sort
this.systems.sort(function (a, b) { return a.priority - b.priority; });
query.register(system);
};
/**
* Removes a system from the manager, it will no longer be updated
* @param system
*/
SystemManager.prototype.removeSystem = function (system) {
___WEBPACK_IMPORTED_MODULE_0__["Util"].removeItemFromArray(system, this.systems);
var query = this._scene.queryManager.getQuery(system.types);
if (query) {
query.unregister(system);
this._scene.queryManager.maybeRemoveQuery(query);
}
};
/**
* Updates all systems
* @param engine
* @param delta
*/
SystemManager.prototype.updateSystems = function (type, engine, delta) {
var systems = this.systems.filter(function (s) { return s.systemType === type; });
for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
var s = systems_1[_i];
if (s.preupdate) {
s.preupdate(engine, delta);
}
}
for (var _a = 0, systems_2 = systems; _a < systems_2.length; _a++) {
var s = systems_2[_a];
var entities = this._scene.queryManager.getQuery(s.types).entities;
s.update(entities, delta);
}
for (var _b = 0, systems_3 = systems; _b < systems_3.length; _b++) {
var s = systems_3[_b];
if (s.postupdate) {
s.postupdate(engine, delta);
}
}
};
return SystemManager;
}());
/***/ }),
/***/ "./EntityComponentSystem/Util.ts":
/*!***************************************!*\
!*** ./EntityComponentSystem/Util.ts ***!
\***************************************/
/*! exports provided: buildTypeKey */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "buildTypeKey", function() { return buildTypeKey; });
var buildTypeKey = function (types) {
var key = types.sort(function (a, b) { return a.localeCompare(b); }).join('+');
return key;
};
/***/ }),
/***/ "./EntityComponentSystem/index.ts":
/*!****************************************!*\
!*** ./EntityComponentSystem/index.ts ***!
\****************************************/
/*! exports provided: Component, TagComponent, AddedComponent, isAddedComponent, RemovedComponent, isRemovedComponent, Entity, EntityManager, Query, QueryManager, SystemType, System, AddedEntity, isAddedSystemEntity, RemovedEntity, isRemoveSystemEntity, SystemManager */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _Component__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Component */ "./EntityComponentSystem/Component.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Component", function() { return _Component__WEBPACK_IMPORTED_MODULE_0__["Component"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TagComponent", function() { return _Component__WEBPACK_IMPORTED_MODULE_0__["TagComponent"]; });
/* harmony import */ var _Entity__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Entity */ "./EntityComponentSystem/Entity.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AddedComponent", function() { return _Entity__WEBPACK_IMPORTED_MODULE_1__["AddedComponent"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isAddedComponent", function() { return _Entity__WEBPACK_IMPORTED_MODULE_1__["isAddedComponent"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RemovedComponent", function() { return _Entity__WEBPACK_IMPORTED_MODULE_1__["RemovedComponent"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isRemovedComponent", function() { return _Entity__WEBPACK_IMPORTED_MODULE_1__["isRemovedComponent"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Entity", function() { return _Entity__WEBPACK_IMPORTED_MODULE_1__["Entity"]; });
/* harmony import */ var _EntityManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./EntityManager */ "./EntityComponentSystem/EntityManager.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EntityManager", function() { return _EntityManager__WEBPACK_IMPORTED_MODULE_2__["EntityManager"]; });
/* harmony import */ var _Query__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Query */ "./EntityComponentSystem/Query.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Query", function() { return _Query__WEBPACK_IMPORTED_MODULE_3__["Query"]; });
/* harmony import */ var _QueryManager__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./QueryManager */ "./EntityComponentSystem/QueryManager.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "QueryManager", function() { return _QueryManager__WEBPACK_IMPORTED_MODULE_4__["QueryManager"]; });
/* harmony import */ var _System__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./System */ "./EntityComponentSystem/System.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SystemType", function() { return _System__WEBPACK_IMPORTED_MODULE_5__["SystemType"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "System", function() { return _System__WEBPACK_IMPORTED_MODULE_5__["System"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AddedEntity", function() { return _System__WEBPACK_IMPORTED_MODULE_5__["AddedEntity"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isAddedSystemEntity", function() { return _System__WEBPACK_IMPORTED_MODULE_5__["isAddedSystemEntity"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RemovedEntity", function() { return _System__WEBPACK_IMPORTED_MODULE_5__["RemovedEntity"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "isRemoveSystemEntity", function() { return _System__WEBPACK_IMPORTED_MODULE_5__["isRemoveSystemEntity"]; });
/* harmony import */ var _SystemManager__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./SystemManager */ "./EntityComponentSystem/SystemManager.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SystemManager", function() { return _SystemManager__WEBPACK_IMPORTED_MODULE_6__["SystemManager"]; });
/***/ }),
/***/ "./EventDispatcher.ts":
/*!****************************!*\
!*** ./EventDispatcher.ts ***!
\****************************/
/*! exports provided: EventDispatcher */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EventDispatcher", function() { return EventDispatcher; });
/* harmony import */ var _Events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Events */ "./Events.ts");
/**
* Excalibur's internal event dispatcher implementation.
* Callbacks are fired immediately after an event is published.
* Typically you will use [[Class.eventDispatcher]] since most classes in
* Excalibur inherit from [[Class]]. You will rarely create an `EventDispatcher`
* yourself.
*
* [[include:Events.md]]
*/
var EventDispatcher = /** @class */ (function () {
/**
* @param target The object that will be the recipient of events from this event dispatcher
*/
function EventDispatcher(target) {
this._handlers = {};
this._wiredEventDispatchers = [];
this._target = target;
}
/**
* Clears any existing handlers or wired event dispatchers on this event dispatcher
*/
EventDispatcher.prototype.clear = function () {
this._handlers = {};
this._wiredEventDispatchers = [];
};
/**
* Emits an event for target
* @param eventName The name of the event to publish
* @param event Optionally pass an event data object to the handler
*/
EventDispatcher.prototype.emit = function (eventName, event) {
if (!eventName) {
// key not mapped
return;
}
eventName = eventName.toLowerCase();
var target = this._target;
if (!event) {
event = new _Events__WEBPACK_IMPORTED_MODULE_0__["GameEvent"]();
}
event.target = target;
var i, len;
if (this._handlers[eventName]) {
i = 0;
len = this._handlers[eventName].length;
for (i; i < len; i++) {
this._handlers[eventName][i].call(target, event);
}
}
i = 0;
len = this._wiredEventDispatchers.length;
for (i; i < len; i++) {
this._wiredEventDispatchers[i].emit(eventName, event);
}
};
/**
* Subscribe an event handler to a particular event name, multiple handlers per event name are allowed.
* @param eventName The name of the event to subscribe to
* @param handler The handler callback to fire on this event
*/
EventDispatcher.prototype.on = function (eventName, handler) {
eventName = eventName.toLowerCase();
if (!this._handlers[eventName]) {
this._handlers[eventName] = [];
}
this._handlers[eventName].push(handler);
// meta event handlers
if (eventName !== 'unsubscribe' && eventName !== 'subscribe') {
this.emit('subscribe', new _Events__WEBPACK_IMPORTED_MODULE_0__["SubscribeEvent"](eventName, handler));
}
};
/**
* Unsubscribe an event handler(s) from an event. If a specific handler
* is specified for an event, only that handler will be unsubscribed.
* Otherwise all handlers will be unsubscribed for that event.
*
* @param eventName The name of the event to unsubscribe
* @param handler Optionally the specific handler to unsubscribe
*
*/
EventDispatcher.prototype.off = function (eventName, handler) {
eventName = eventName.toLowerCase();
var eventHandlers = this._handlers[eventName];
if (eventHandlers) {
// if no explicit handler is give with the event name clear all handlers
if (!handler) {
this._handlers[eventName].length = 0;
}
else {
var index = eventHandlers.indexOf(handler);
this._handlers[eventName].splice(index, 1);
}
}
// meta event handlers
if (eventName !== 'unsubscribe' && eventName !== 'subscribe') {
this.emit('unsubscribe', new _Events__WEBPACK_IMPORTED_MODULE_0__["UnsubscribeEvent"](eventName, handler));
}
};
/**
* Once listens to an event one time, then unsubscribes from that event
*
* @param eventName The name of the event to subscribe to once
* @param handler The handler of the event that will be auto unsubscribed
*/
EventDispatcher.prototype.once = function (eventName, handler) {
var _this = this;
var metaHandler = function (event) {
var ev = event || new _Events__WEBPACK_IMPORTED_MODULE_0__["GameEvent"]();
ev.target = ev.target || _this._target;
_this.off(eventName, handler);
handler.call(ev.target, ev);
};
this.on(eventName, metaHandler);
};
/**
* Wires this event dispatcher to also receive events from another
*/
EventDispatcher.prototype.wire = function (eventDispatcher) {
eventDispatcher._wiredEventDispatchers.push(this);
};
/**
* Unwires this event dispatcher from another
*/
EventDispatcher.prototype.unwire = function (eventDispatcher) {
var index = eventDispatcher._wiredEventDispatchers.indexOf(this);
if (index > -1) {
eventDispatcher._wiredEventDispatchers.splice(index, 1);
}
};
return EventDispatcher;
}());
/***/ }),
/***/ "./Events.ts":
/*!*******************!*\
!*** ./Events.ts ***!
\*******************/
/*! exports provided: EventTypes, GameEvent, KillEvent, PreKillEvent, PostKillEvent, GameStartEvent, GameStopEvent, PreDrawEvent, PostDrawEvent, PreDebugDrawEvent, PostDebugDrawEvent, PreUpdateEvent, PostUpdateEvent, PreFrameEvent, PostFrameEvent, GamepadConnectEvent, GamepadDisconnectEvent, GamepadButtonEvent, GamepadAxisEvent, SubscribeEvent, UnsubscribeEvent, VisibleEvent, HiddenEvent, PreCollisionEvent, PostCollisionEvent, CollisionStartEvent, CollisionEndEvent, InitializeEvent, ActivateEvent, DeactivateEvent, ExitViewPortEvent, EnterViewPortEvent, EnterTriggerEvent, ExitTriggerEvent */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EventTypes", function() { return EventTypes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GameEvent", function() { return GameEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KillEvent", function() { return KillEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PreKillEvent", function() { return PreKillEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PostKillEvent", function() { return PostKillEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GameStartEvent", function() { return GameStartEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GameStopEvent", function() { return GameStopEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PreDrawEvent", function() { return PreDrawEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PostDrawEvent", function() { return PostDrawEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PreDebugDrawEvent", function() { return PreDebugDrawEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PostDebugDrawEvent", function() { return PostDebugDrawEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PreUpdateEvent", function() { return PreUpdateEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PostUpdateEvent", function() { return PostUpdateEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PreFrameEvent", function() { return PreFrameEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PostFrameEvent", function() { return PostFrameEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GamepadConnectEvent", function() { return GamepadConnectEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GamepadDisconnectEvent", function() { return GamepadDisconnectEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GamepadButtonEvent", function() { return GamepadButtonEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GamepadAxisEvent", function() { return GamepadAxisEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubscribeEvent", function() { return SubscribeEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UnsubscribeEvent", function() { return UnsubscribeEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VisibleEvent", function() { return VisibleEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HiddenEvent", function() { return HiddenEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PreCollisionEvent", function() { return PreCollisionEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PostCollisionEvent", function() { return PostCollisionEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CollisionStartEvent", function() { return CollisionStartEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CollisionEndEvent", function() { return CollisionEndEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InitializeEvent", function() { return InitializeEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ActivateEvent", function() { return ActivateEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DeactivateEvent", function() { return DeactivateEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ExitViewPortEvent", function() { return ExitViewPortEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EnterViewPortEvent", function() { return EnterViewPortEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EnterTriggerEvent", function() { return EnterTriggerEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ExitTriggerEvent", function() { return ExitTriggerEvent; });
var __extends = (undefined && undefined.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var EventTypes;
(function (EventTypes) {
EventTypes["Kill"] = "kill";
EventTypes["PreKill"] = "prekill";
EventTypes["PostKill"] = "postkill";
EventTypes["PreDraw"] = "predraw";
EventTypes["PostDraw"] = "postdraw";
EventTypes["PreDebugDraw"] = "predebugdraw";
EventTypes["PostDebugDraw"] = "postdebugdraw";
EventTypes["PreUpdate"] = "preupdate";
EventTypes["PostUpdate"] = "postupdate";
EventTypes["PreFrame"] = "preframe";
EventTypes["PostFrame"] = "postframe";
EventTypes["PreCollision"] = "precollision";
EventTypes["CollisionStart"] = "collisionstart";
EventTypes["CollisionEnd"] = "collisionend";
EventTypes["PostCollision"] = "postcollision";
EventTypes["Initialize"] = "initialize";
EventTypes["Activate"] = "activate";
EventTypes["Deactivate"] = "deactivate";
EventTypes["ExitViewport"] = "exitviewport";
EventTypes["EnterViewport"] = "enterviewport";
EventTypes["ExitTrigger"] = "exit";
EventTypes["EnterTrigger"] = "enter";
EventTypes["Connect"] = "connect";
EventTypes["Disconnect"] = "disconnect";
EventTypes["Button"] = "button";
EventTypes["Axis"] = "axis";
EventTypes["Subscribe"] = "subscribe";
EventTypes["Unsubscribe"] = "unsubscribe";
EventTypes["Visible"] = "visible";
EventTypes["Hidden"] = "hidden";
EventTypes["Start"] = "start";
EventTypes["Stop"] = "stop";
EventTypes["PointerUp"] = "pointerup";
EventTypes["PointerDown"] = "pointerdown";
EventTypes["PointerMove"] = "pointermove";
EventTypes["PointerEnter"] = "pointerenter";
EventTypes["PointerLeave"] = "pointerleave";
EventTypes["PointerCancel"] = "pointercancel";
EventTypes["PointerWheel"] = "pointerwheel";
EventTypes["Up"] = "up";
EventTypes["Down"] = "down";
EventTypes["Move"] = "move";
EventTypes["Enter"] = "enter";
EventTypes["Leave"] = "leave";
EventTypes["Cancel"] = "cancel";
EventTypes["Wheel"] = "wheel";
EventTypes["Press"] = "press";
EventTypes["Release"] = "release";
EventTypes["Hold"] = "hold";
EventTypes["PointerDragStart"] = "pointerdragstart";
EventTypes["PointerDragEnd"] = "pointerdragend";
EventTypes["PointerDragEnter"] = "pointerdragenter";
EventTypes["PointerDragLeave"] = "pointerdragleave";
EventTypes["PointerDragMove"] = "pointerdragmove";
})(EventTypes || (EventTypes = {}));
/**
* Base event type in Excalibur that all other event types derive from. Not all event types are thrown on all Excalibur game objects,
* some events are unique to a type, others are not.
*
*/
var GameEvent = /** @class */ (function () {
function GameEvent() {
this._bubbles = true;
}
Object.defineProperty(GameEvent.prototype, "bubbles", {
/**
* If set to false, prevents event from propagating to other actors. If true it will be propagated
* to all actors that apply.
*/
get: function () {
return this._bubbles;
},
set: function (value) {
this._bubbles = value;
},
enumerable: false,
configurable: true
});
/**
* Prevents event from bubbling
*/
GameEvent.prototype.stopPropagation = function () {
this.bubbles = false;
};
return GameEvent;
}());
/**
* The 'kill' event is emitted on actors when it is killed. The target is the actor that was killed.
*/
var KillEvent = /** @class */ (function (_super) {
__extends(KillEvent, _super);
function KillEvent(target) {
var _this = _super.call(this) || this;
_this.target = target;
return _this;
}
return KillEvent;
}(GameEvent));
/**
* The 'prekill' event is emitted directly before an actor is killed.
*/
var PreKillEvent = /** @class */ (function (_super) {
__extends(PreKillEvent, _super);
function PreKillEvent(target) {
var _this = _super.call(this) || this;
_this.target = target;
return _this;
}
return PreKillEvent;
}(GameEvent));
/**
* The 'postkill' event is emitted directly after the actor is killed.
*/
var PostKillEvent = /** @class */ (function (_super) {
__extends(PostKillEvent, _super);
function PostKillEvent(target) {
var _this = _super.call(this) || this;
_this.target = target;
return _this;
}
return PostKillEvent;
}(GameEvent));
/**
* The 'start' event is emitted on engine when has started and is ready for interaction.
*/
var GameStartEvent = /** @class */ (function (_super) {
__extends(GameStartEvent, _super);
function GameStartEvent(target) {
var _this = _super.call(this) || this;
_this.target = target;
return _this;
}
return GameStartEvent;
}(GameEvent));
/**
* The 'stop' event is emitted on engine when has been stopped and will no longer take input, update or draw.
*/
var GameStopEvent = /** @class */ (function (_super) {
__extends(GameStopEvent, _super);
function GameStopEvent(target) {
var _this = _super.call(this) || this;
_this.target = target;
return _this;
}
return GameStopEvent;
}(GameEvent));
/**
* The 'predraw' event is emitted on actors, scenes, and engine before drawing starts. Actors' predraw happens inside their graphics
* transform so that all drawing takes place with the actor as the origin.
*
*/
var PreDrawEvent = /** @class */ (function (_super) {
__extends(PreDrawEvent, _super);
function PreDrawEvent(ctx, delta, target) {
var _this = _super.call(this) || this;
_this.ctx = ctx;
_this.delta = delta;
_this.target = target;
return _this;
}
return PreDrawEvent;
}(GameEvent));
/**
* The 'postdraw' event is emitted on actors, scenes, and engine after drawing finishes. Actors' postdraw happens inside their graphics
* transform so that all drawing takes place with the actor as the origin.
*
*/
var PostDrawEvent = /** @class */ (function (_super) {
__extends(PostDrawEvent, _super);
function PostDrawEvent(ctx, delta, target) {
var _this = _super.call(this) || this;
_this.ctx = ctx;
_this.delta = delta;
_this.target = target;
return _this;
}
return PostDrawEvent;
}(GameEvent));
/**
* The 'predebugdraw' event is emitted on actors, scenes, and engine before debug drawing starts.
*/
var PreDebugDrawEvent = /** @class */ (function (_super) {
__extends(PreDebugDrawEvent, _super);
function PreDebugDrawEvent(ctx, target) {
var _this = _super.call(this) || this;
_this.ctx = ctx;
_this.target = target;
return _this;
}
return PreDebugDrawEvent;
}(GameEvent));
/**
* The 'postdebugdraw' event is emitted on actors, scenes, and engine after debug drawing starts.
*/
var PostDebugDrawEvent = /** @class */ (function (_super) {
__extends(PostDebugDrawEvent, _super);
function PostDebugDrawEvent(ctx, target) {
var _this = _super.call(this) || this;
_this.ctx = ctx;
_this.target = target;
return _this;
}
return PostDebugDrawEvent;
}(GameEvent));
/**
* The 'preupdate' event is emitted on actors, scenes, camera, and engine before the update starts.
*/
var PreUpdateEvent = /** @class */ (function (_super) {
__extends(PreUpdateEvent, _super);
function PreUpdateEvent(engine, delta, target) {
var _this = _super.call(this) || this;
_this.engine = engine;
_this.delta = delta;
_this.target = target;
return _this;
}
return PreUpdateEvent;
}(GameEvent));
/**
* The 'postupdate' event is emitted on actors, scenes, camera, and engine after the update ends.
*/
var PostUpdateEvent = /** @class */ (function (_super) {
__extends(PostUpdateEvent, _super);
function PostUpdateEvent(engine, delta, target) {
var _this = _super.call(this) || this;
_this.engine = engine;
_this.delta = delta;
_this.target = target;
return _this;
}
return PostUpdateEvent;
}(GameEvent));
/**
* The 'preframe' event is emitted on the engine, before the frame begins.
*/
var PreFrameEvent = /** @class */ (function (_super) {
__extends(PreFrameEvent, _super);
function PreFrameEvent(engine, prevStats) {
var _this = _super.call(this) || this;
_this.engine = engine;
_this.prevStats = prevStats;
_this.target = engine;
return _this;
}
return PreFrameEvent;
}(GameEvent));
/**
* The 'postframe' event is emitted on the engine, after a frame ends.
*/
var PostFrameEvent = /** @class */ (function (_super) {
__extends(PostFrameEvent, _super);
function PostFrameEvent(engine, stats) {
var _this = _super.call(this) || this;
_this.engine = engine;
_this.stats = stats;
_this.target = engine;
return _this;
}
return PostFrameEvent;
}(GameEvent));
/**
* Event received when a gamepad is connected to Excalibur. [[Gamepads]] receives this event.
*/
var GamepadConnectEvent = /** @class */ (function (_super) {
__extends(GamepadConnectEvent, _super);
function GamepadConnectEvent(index, gamepad) {
var _this = _super.call(this) || this;
_this.index = index;
_this.gamepad = gamepad;
_this.target = gamepad;
return _this;
}
return GamepadConnectEvent;
}(GameEvent));
/**
* Event received when a gamepad is disconnected from Excalibur. [[Gamepads]] receives this event.
*/
var GamepadDisconnectEvent = /** @class */ (function (_super) {
__extends(GamepadDisconnectEvent, _super);
function GamepadDisconnectEvent(index, gamepad) {
var _this = _super.call(this) || this;
_this.index = index;
_this.gamepad = gamepad;
_this.target = gamepad;
return _this;
}
return GamepadDisconnectEvent;
}(GameEvent));
/**
* Gamepad button event. See [[Gamepads]] for information on responding to controller input. [[Gamepad]] instances receive this event;
*/
var GamepadButtonEvent = /** @class */ (function (_super) {
__extends(GamepadButtonEvent, _super);
/**
* @param button The Gamepad button
* @param value A numeric value between 0 and 1
*/
function GamepadButtonEvent(button, value, target) {
var _this = _super.call(this) || this;
_this.button = button;
_this.value = value;
_this.target = target;
return _this;
}
return GamepadButtonEvent;
}(GameEvent));
/**
* Gamepad axis event. See [[Gamepads]] for information on responding to controller input. [[Gamepad]] instances receive this event;
*/
var GamepadAxisEvent = /** @class */ (function (_super) {
__extends(GamepadAxisEvent, _super);
/**
* @param axis The Gamepad axis
* @param value A numeric value between -1 and 1
*/
function GamepadAxisEvent(axis, value, target) {
var _this = _super.call(this) || this;
_this.axis = axis;
_this.value = value;
_this.target = target;
return _this;
}
return GamepadAxisEvent;
}(GameEvent));
/**
* Subscribe event thrown when handlers for events other than subscribe are added. Meta event that is received by
* [[EventDispatcher|event dispatchers]].
*/
var SubscribeEvent = /** @class */ (function (_super) {
__extends(SubscribeEvent, _super);
function SubscribeEvent(topic, handler) {
var _this = _super.call(this) || this;
_this.topic = topic;
_this.handler = handler;
return _this;
}
return SubscribeEvent;
}(GameEvent));
/**
* Unsubscribe event thrown when handlers for events other than unsubscribe are removed. Meta event that is received by
* [[EventDispatcher|event dispatchers]].
*/
var UnsubscribeEvent = /** @class */ (function (_super) {
__extends(UnsubscribeEvent, _super);
function UnsubscribeEvent(topic, handler) {
var _this = _super.call(this) || this;
_this.topic = topic;
_this.handler = handler;
return _this;
}
return UnsubscribeEvent;
}(GameEvent));
/**
* Event received by the [[Engine]] when the browser window is visible on a screen.
*/
var VisibleEvent = /** @class */ (function (_super) {
__extends(VisibleEvent, _super);
function VisibleEvent(target) {
var _this = _super.call(this) || this;
_this.target = target;
return _this;
}
return VisibleEvent;
}(GameEvent));
/**
* Event received by the [[Engine]] when the browser window is hidden from all screens.
*/
var HiddenEvent = /** @class */ (function (_super) {
__extends(HiddenEvent, _super);
function HiddenEvent(target) {
var _this = _super.call(this) || this;
_this.target = target;
return _this;
}
return HiddenEvent;
}(GameEvent));
/**
* Event thrown on an [[Actor|actor]] when a collision will occur this frame if it resolves
*/
var PreCollisionEvent = /** @class */ (function (_super) {
__extends(PreCollisionEvent, _super);
/**
* @param actor The actor the event was thrown on
* @param other The actor that will collided with the current actor
* @param side The side that will be collided with the current actor
* @param intersection Intersection vector
*/
function PreCollisionEvent(actor, other, side, intersection) {
var _this = _super.call(this) || this;
_this.other = other;
_this.side = side;
_this.intersection = intersection;
_this.target = actor;
return _this;
}
Object.defineProperty(PreCollisionEvent.prototype, "actor", {
get: function () {
return this.target;
},
set: function (actor) {
this.target = actor;
},
enumerable: false,
configurable: true
});
return PreCollisionEvent;
}(GameEvent));
/**
* Event thrown on an [[Actor|actor]] when a collision has been resolved (body reacted) this frame
*/
var PostCollisionEvent = /** @class */ (function (_super) {
__extends(PostCollisionEvent, _super);
/**
* @param actor The actor the event was thrown on
* @param other The actor that did collide with the current actor
* @param side The side that did collide with the current actor
* @param intersection Intersection vector
*/
function PostCollisionEvent(actor, other, side, intersection) {
var _this = _super.call(this) || this;
_this.other = other;
_this.side = side;
_this.intersection = intersection;
_this.target = actor;
return _this;
}
Object.defineProperty(PostCollisionEvent.prototype, "actor", {
get: function () {
return this.target;
},
set: function (actor) {
this.target = actor;
},
enumerable: false,
configurable: true
});
return PostCollisionEvent;
}(GameEvent));
/**
* Event thrown the first time an [[Actor|actor]] collides with another, after an actor is in contact normal collision events are fired.
*/
var CollisionStartEvent = /** @class */ (function (_super) {
__extends(CollisionStartEvent, _super);
/**
*
* @param actor
* @param other
* @param pair
*/
function CollisionStartEvent(actor, other, pair) {
var _this = _super.call(this) || this;
_this.other = other;
_this.pair = pair;
_this.target = actor;
return _this;
}
Object.defineProperty(CollisionStartEvent.prototype, "actor", {
get: function () {
return this.target;
},
set: function (actor) {
this.target = actor;
},
enumerable: false,
configurable: true
});
return CollisionStartEvent;
}(GameEvent));
/**
* Event thrown when the [[Actor|actor]] is no longer colliding with another
*/
var CollisionEndEvent = /** @class */ (function (_super) {
__extends(CollisionEndEvent, _super);
/**
*
*/
function CollisionEndEvent(actor, other) {
var _this = _super.call(this) || this;
_this.other = other;
_this.target = actor;
return _this;
}
Object.defineProperty(CollisionEndEvent.prototype, "actor", {
get: function () {
return this.target;
},
set: function (actor) {
this.target = actor;
},
enumerable: false,
configurable: true
});
return CollisionEndEvent;
}(GameEvent));
/**
* Event thrown on an [[Actor]] and a [[Scene]] only once before the first update call
*/
var InitializeEvent = /** @class */ (function (_super) {
__extends(InitializeEvent, _super);
/**
* @param engine The reference to the current engine
*/
function InitializeEvent(engine, target) {
var _this = _super.call(this) || this;
_this.engine = engine;
_this.target = target;
return _this;
}
return InitializeEvent;
}(GameEvent));
/**
* Event thrown on a [[Scene]] on activation
*/
var ActivateEvent = /** @class */ (function (_super) {
__extends(ActivateEvent, _super);
/**
* @param oldScene The reference to the old scene
*/
function ActivateEvent(oldScene, target) {
var _this = _super.call(this) || this;
_this.oldScene = oldScene;
_this.target = target;
return _this;
}
return ActivateEvent;
}(GameEvent));
/**
* Event thrown on a [[Scene]] on deactivation
*/
var DeactivateEvent = /** @class */ (function (_super) {
__extends(DeactivateEvent, _super);
/**
* @param newScene The reference to the new scene
*/
function DeactivateEvent(newScene, target) {
var _this = _super.call(this) || this;
_this.newScene = newScene;
_this.target = target;
return _this;
}
return DeactivateEvent;
}(GameEvent));
/**
* Event thrown on an [[Actor]] when it completely leaves the screen.
*/
var ExitViewPortEvent = /** @class */ (function (_super) {
__extends(ExitViewPortEvent, _super);
function ExitViewPortEvent(target) {
var _this = _super.call(this) || this;
_this.target = target;
return _this;
}
return ExitViewPortEvent;
}(GameEvent));
/**
* Event thrown on an [[Actor]] when it completely leaves the screen.
*/
var EnterViewPortEvent = /** @class */ (function (_super) {
__extends(EnterViewPortEvent, _super);
function EnterViewPortEvent(target) {
var _this = _super.call(this) || this;
_this.target = target;
return _this;
}
return EnterViewPortEvent;
}(GameEvent));
var EnterTriggerEvent = /** @class */ (function (_super) {
__extends(EnterTriggerEvent, _super);
function EnterTriggerEvent(target, actor) {
var _this = _super.call(this) || this;
_this.target = target;
_this.actor = actor;
return _this;
}
return EnterTriggerEvent;
}(GameEvent));
var ExitTriggerEvent = /** @class */ (function (_super) {
__extends(ExitTriggerEvent, _super);
function ExitTriggerEvent(target, actor) {
var _this = _super.call(this) || this;
_this.target = target;
_this.actor = actor;
return _this;
}
return ExitTriggerEvent;
}(GameEvent));
/***/ }),
/***/ "./Events/MediaEvents.ts":
/*!*******************************!*\
!*** ./Events/MediaEvents.ts ***!
\*******************************/
/*! exports provided: MediaEvent, NativeSoundEvent, NativeSoundProcessedEvent */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MediaEvent", function() { return MediaEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NativeSoundEvent", function() { return NativeSoundEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NativeSoundProcessedEvent", function() { return NativeSoundProcessedEvent; });
/* harmony import */ var _Events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Events */ "./Events.ts");
var __extends = (undefined && undefined.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var MediaEvent = /** @class */ (function (_super) {
__extends(MediaEvent, _super);
function MediaEvent(target, _name) {
if (_name === void 0) { _name = 'MediaEvent'; }
var _this = _super.call(this) || this;
_this.target = target;
_this._name = _name;
return _this;
}
Object.defineProperty(MediaEvent.prototype, "bubbles", {
/**
* Media event cannot bubble
*/
get: function () {
return false;
},
/**
* Media event cannot bubble
*/
set: function (_value) {
// stubbed
},
enumerable: false,
configurable: true
});
Object.defineProperty(MediaEvent.prototype, "_path", {
/**
* Media event cannot bubble, so they have no path
*/
get: function () {
return null;
},
/**
* Media event cannot bubble, so they have no path
*/
set: function (_val) {
// stubbed
},
enumerable: false,
configurable: true
});
/**
* Prevents event from bubbling
*/
MediaEvent.prototype.stopPropagation = function () {
/**
* Stub
*/
};
/**
* Action, that calls when event happens
*/
MediaEvent.prototype.action = function () {
/**
* Stub
*/
};
/**
* Propagate event further through event path
*/
MediaEvent.prototype.propagate = function () {
/**
* Stub
*/
};
MediaEvent.prototype.layPath = function (_actor) {
/**
* Stub
*/
};
return MediaEvent;
}(_Events__WEBPACK_IMPORTED_MODULE_0__["GameEvent"]));
var NativeSoundEvent = /** @class */ (function (_super) {
__extends(NativeSoundEvent, _super);
function NativeSoundEvent(target, track) {
var _this = _super.call(this, target, 'NativeSoundEvent') || this;
_this.track = track;
return _this;
}
return NativeSoundEvent;
}(MediaEvent));
var NativeSoundProcessedEvent = /** @class */ (function (_super) {
__extends(NativeSoundProcessedEvent, _super);
function NativeSoundProcessedEvent(target, processedData) {
var _this = _super.call(this, target, 'NativeSoundProcessedEvent') || this;
_this.processedData = processedData;
_this.data = _this.processedData;
return _this;
}
return NativeSoundProcessedEvent;
}(MediaEvent));
/***/ }),
/***/ "./Input/EngineInput.ts":
/*!******************************!*\
!*** ./Input/EngineInput.ts ***!
\******************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/***/ }),
/***/ "./Input/Gamepad.ts":
/*!**************************!*\
!*** ./Input/Gamepad.ts ***!
\**************************/
/*! exports provided: Gamepads, Gamepad, Buttons, Axes */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Gamepads", function() { return Gamepads; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Gamepad", function() { return Gamepad; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Buttons", function() { return Buttons; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Axes", function() { return Axes; });
/* harmony import */ var _Class__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./../Class */ "./Class.ts");
/* harmony import */ var _Events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Events */ "./Events.ts");
var __extends = (undefined && undefined.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
/**
* Excalibur leverages the HTML5 Gamepad API [where it is supported](http://caniuse.com/#feat=gamepad)
* to provide controller support for your games.
*
* [[include:Gamepads.md]]
*/
var Gamepads = /** @class */ (function (_super) {
__extends(Gamepads, _super);
function Gamepads() {
var _this = _super.call(this) || this;
/**
* Whether or not to poll for Gamepad input (default: `false`)
*/
_this.enabled = false;
/**
* Whether or not Gamepad API is supported
*/
_this.supported = !!navigator.getGamepads;
_this._gamePadTimeStamps = [0, 0, 0, 0];
_this._oldPads = [];
_this._pads = [];
_this._initSuccess = false;
_this._navigator = navigator;
_this._minimumConfiguration = null;
return _this;
}
Gamepads.prototype.init = function () {
if (!this.supported) {
return;
}
if (this._initSuccess) {
return;
}
// In Chrome, this will return 4 undefined items until a button is pressed
// In FF, this will not return any items until a button is pressed
this._oldPads = this._clonePads(this._navigator.getGamepads());
if (this._oldPads.length && this._oldPads[0]) {
this._initSuccess = true;
}
};
/**
* Sets the minimum gamepad configuration, for example {axis: 4, buttons: 4} means
* this game requires at minimum 4 axis inputs and 4 buttons, this is not restrictive
* all other controllers with more axis or buttons are valid as well. If no minimum
* configuration is set all pads are valid.
*/
Gamepads.prototype.setMinimumGamepadConfiguration = function (config) {
this._enableAndUpdate(); // if config is used, implicitly enable
this._minimumConfiguration = config;
};
/**
* When implicitly enabled, set the enabled flag and run an update so information is updated
*/
Gamepads.prototype._enableAndUpdate = function () {
if (!this.enabled) {
this.enabled = true;
this.update();
}
};
/**
* Checks a navigator gamepad against the minimum configuration if present.
*/
Gamepads.prototype._isGamepadValid = function (pad) {
if (!this._minimumConfiguration) {
return true;
}
if (!pad) {
return false;
}
var axesLength = pad.axes.filter(function (value) {
return typeof value !== undefined;
}).length;
var buttonLength = pad.buttons.filter(function (value) {
return typeof value !== undefined;
}).length;
return axesLength >= this._minimumConfiguration.axis && buttonLength >= this._minimumConfiguration.buttons && pad.connected;
};
Gamepads.prototype.on = function (eventName, handler) {
this._enableAndUpdate(); // implicitly enable
_super.prototype.on.call(this, eventName, handler);
};
Gamepads.prototype.off = function (eventName, handler) {
this._enableAndUpdate(); // implicitly enable
_super.prototype.off.call(this, eventName, handler);
};
/**
* Updates Gamepad state and publishes Gamepad events
*/
Gamepads.prototype.update = function () {
if (!this.enabled || !this.supported) {
return;
}
this.init();
var gamepads = this._navigator.getGamepads();
for (var i = 0; i < gamepads.length; i++) {
if (!gamepads[i]) {
var gamepad = this.at(i);
// If was connected, but now isn't emit the disconnect event
if (gamepad.connected) {
this.eventDispatcher.emit('disconnect', new _Events__WEBPACK_IMPORTED_MODULE_1__["GamepadDisconnectEvent"](i, gamepad));
}
// Reset connection status
gamepad.connected = false;
continue;
}
else {
if (!this.at(i).connected && this._isGamepadValid(gamepads[i])) {
this.eventDispatcher.emit('connect', new _Events__WEBPACK_IMPORTED_MODULE_1__["GamepadConnectEvent"](i, this.at(i)));
}
// Set connection status
this.at(i).connected = true;
}
// Only supported in Chrome
if (gamepads[i].timestamp && gamepads[i].timestamp === this._gamePadTimeStamps[i]) {
continue;
}
this._gamePadTimeStamps[i] = gamepads[i].timestamp;
// Add reference to navigator gamepad
this.at(i).navigatorGamepad = gamepads[i];
// Buttons
var b = void 0, bi = void 0, a = void 0, ai = void 0, value = void 0;
for (b in Buttons) {
bi = Buttons[b];
if (typeof bi === 'number') {
if (gamepads[i].buttons[bi]) {
value = gamepads[i].buttons[bi].value;
if (value !== this._oldPads[i].getButton(bi)) {
if (gamepads[i].buttons[bi].pressed) {
this.at(i).updateButton(bi, value);
this.at(i).eventDispatcher.emit('button', new _Events__WEBPACK_IMPORTED_MODULE_1__["GamepadButtonEvent"](bi, value, this.at(i)));
}
else {
this.at(i).updateButton(bi, 0);
}
}
}
}
}
// Axes
for (a in Axes) {
ai = Axes[a];
if (typeof ai === 'number') {
value = gamepads[i].axes[ai];
if (value !== this._oldPads[i].getAxes(ai)) {
this.at(i).updateAxes(ai, value);
this.at(i).eventDispatcher.emit('axis', new _Events__WEBPACK_IMPORTED_MODULE_1__["GamepadAxisEvent"](ai, value, this.at(i)));
}
}
}
this._oldPads[i] = this._clonePad(gamepads[i]);
}
};
/**
* Safely retrieves a Gamepad at a specific index and creates one if it doesn't yet exist
*/
Gamepads.prototype.at = function (index) {
this._enableAndUpdate(); // implicitly enable gamepads when at() is called
if (index >= this._pads.length) {
// Ensure there is a pad to retrieve
for (var i = this._pads.length - 1, max = index; i < max; i++) {
this._pads.push(new Gamepad());
this._oldPads.push(new Gamepad());
}
}
return this._pads[index];
};
/**
* Returns a list of all valid gamepads that meet the minimum configuration requirement.
*/
Gamepads.prototype.getValidGamepads = function () {
this._enableAndUpdate();
var result = [];
for (var i = 0; i < this._pads.length; i++) {
if (this._isGamepadValid(this.at(i).navigatorGamepad) && this.at(i).connected) {
result.push(this.at(i));
}
}
return result;
};
/**
* Gets the number of connected gamepads
*/
Gamepads.prototype.count = function () {
return this._pads.filter(function (p) { return p.connected; }).length;
};
Gamepads.prototype._clonePads = function (pads) {
var arr = [];
for (var i = 0, len = pads.length; i < len; i++) {
arr.push(this._clonePad(pads[i]));
}
return arr;
};
/**
* Fastest way to clone a known object is to do it yourself
*/
Gamepads.prototype._clonePad = function (pad) {
var i, len;
var clonedPad = new Gamepad();
if (!pad) {
return clonedPad;
}
for (i = 0, len = pad.buttons.length; i < len; i++) {
if (pad.buttons[i]) {
clonedPad.updateButton(i, pad.buttons[i].value);
}
}
for (i = 0, len = pad.axes.length; i < len; i++) {
clonedPad.updateAxes(i, pad.axes[i]);
}
return clonedPad;
};
/**
* The minimum value an axis has to move before considering it a change
*/
Gamepads.MinAxisMoveThreshold = 0.05;
return Gamepads;
}(_Class__WEBPACK_IMPORTED_MODULE_0__["Class"]));
/**
* Gamepad holds state information for a connected controller. See [[Gamepads]]
* for more information on handling controller input.
*/
var Gamepad = /** @class */ (function (_super) {
__extends(Gamepad, _super);
function Gamepad() {
var _this = _super.call(this) || this;
_this.connected = false;
_this._buttons = new Array(16);
_this._axes = new Array(4);
for (var i = 0; i < _this._buttons.length; i++) {
_this._buttons[i] = 0;
}
for (var i = 0; i < _this._axes.length; i++) {
_this._axes[i] = 0;
}
return _this;
}
/**
* Whether or not the given button is pressed
* @param button The button to query
* @param threshold The threshold over which the button is considered to be pressed
*/
Gamepad.prototype.isButtonPressed = function (button, threshold) {
if (threshold === void 0) { threshold = 1; }
return this._buttons[button] >= threshold;
};
/**
* Gets the given button value between 0 and 1
*/
Gamepad.prototype.getButton = function (button) {
return this._buttons[button];
};
/**
* Gets the given axis value between -1 and 1. Values below
* [[MinAxisMoveThreshold]] are considered 0.
*/
Gamepad.prototype.getAxes = function (axes) {
var value = this._axes[axes];
if (Math.abs(value) < Gamepads.MinAxisMoveThreshold) {
return 0;
}
else {
return value;
}
};
Gamepad.prototype.updateButton = function (buttonIndex, value) {
this._buttons[buttonIndex] = value;
};
Gamepad.prototype.updateAxes = function (axesIndex, value) {
this._axes[axesIndex] = value;
};
return Gamepad;
}(_Class__WEBPACK_IMPORTED_MODULE_0__["Class"]));
/**
* Gamepad Buttons enumeration
*/
var Buttons;
(function (Buttons) {
/**
* Face 1 button (e.g. A)
*/
Buttons[Buttons["Face1"] = 0] = "Face1";
/**
* Face 2 button (e.g. B)
*/
Buttons[Buttons["Face2"] = 1] = "Face2";
/**
* Face 3 button (e.g. X)
*/
Buttons[Buttons["Face3"] = 2] = "Face3";
/**
* Face 4 button (e.g. Y)
*/
Buttons[Buttons["Face4"] = 3] = "Face4";
/**
* Left bumper button
*/
Buttons[Buttons["LeftBumper"] = 4] = "LeftBumper";
/**
* Right bumper button
*/
Buttons[Buttons["RightBumper"] = 5] = "RightBumper";
/**
* Left trigger button
*/
Buttons[Buttons["LeftTrigger"] = 6] = "LeftTrigger";
/**
* Right trigger button
*/
Buttons[Buttons["RightTrigger"] = 7] = "RightTrigger";
/**
* Select button
*/
Buttons[Buttons["Select"] = 8] = "Select";
/**
* Start button
*/
Buttons[Buttons["Start"] = 9] = "Start";
/**
* Left analog stick press (e.g. L3)
*/
Buttons[Buttons["LeftStick"] = 10] = "LeftStick";
/**
* Right analog stick press (e.g. R3)
*/
Buttons[Buttons["RightStick"] = 11] = "RightStick";
/**
* D-pad up
*/
Buttons[Buttons["DpadUp"] = 12] = "DpadUp";
/**
* D-pad down
*/
Buttons[Buttons["DpadDown"] = 13] = "DpadDown";
/**
* D-pad left
*/
Buttons[Buttons["DpadLeft"] = 14] = "DpadLeft";
/**
* D-pad right
*/
Buttons[Buttons["DpadRight"] = 15] = "DpadRight";
})(Buttons || (Buttons = {}));
/**
* Gamepad Axes enumeration
*/
var Axes;
(function (Axes) {
/**
* Left analogue stick X direction
*/
Axes[Axes["LeftStickX"] = 0] = "LeftStickX";
/**
* Left analogue stick Y direction
*/
Axes[Axes["LeftStickY"] = 1] = "LeftStickY";
/**
* Right analogue stick X direction
*/
Axes[Axes["RightStickX"] = 2] = "RightStickX";
/**
* Right analogue stick Y direction
*/
Axes[Axes["RightStickY"] = 3] = "RightStickY";
})(Axes || (Axes = {}));
/***/ }),
/***/ "./Input/Index.ts":
/*!************************!*\
!*** ./Input/Index.ts ***!
\************************/
/*! exports provided: Gamepads, Gamepad, Buttons, Axes, PointerType, PointerScope, Pointer, Pointers, NativePointerButton, PointerButton, WheelDeltaMode, PointerEvent, PointerEventFactory, PointerDragEvent, PointerUpEvent, PointerDownEvent, PointerMoveEvent, PointerEnterEvent, PointerLeaveEvent, PointerCancelEvent, WheelEvent, createPointerEventByName, Keys, KeyEvent, Keyboard */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _Gamepad__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Gamepad */ "./Input/Gamepad.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Gamepads", function() { return _Gamepad__WEBPACK_IMPORTED_MODULE_0__["Gamepads"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Gamepad", function() { return _Gamepad__WEBPACK_IMPORTED_MODULE_0__["Gamepad"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Buttons", function() { return _Gamepad__WEBPACK_IMPORTED_MODULE_0__["Buttons"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Axes", function() { return _Gamepad__WEBPACK_IMPORTED_MODULE_0__["Axes"]; });
/* harmony import */ var _Pointer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Pointer */ "./Input/Pointer.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerType", function() { return _Pointer__WEBPACK_IMPORTED_MODULE_1__["PointerType"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerScope", function() { return _Pointer__WEBPACK_IMPORTED_MODULE_1__["PointerScope"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Pointer", function() { return _Pointer__WEBPACK_IMPORTED_MODULE_1__["Pointer"]; });
/* harmony import */ var _Pointers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Pointers */ "./Input/Pointers.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Pointers", function() { return _Pointers__WEBPACK_IMPORTED_MODULE_2__["Pointers"]; });
/* harmony import */ var _PointerEvents__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./PointerEvents */ "./Input/PointerEvents.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NativePointerButton", function() { return _PointerEvents__WEBPACK_IMPORTED_MODULE_3__["NativePointerButton"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerButton", function() { return _PointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerButton"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WheelDeltaMode", function() { return _PointerEvents__WEBPACK_IMPORTED_MODULE_3__["WheelDeltaMode"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerEvent", function() { return _PointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEvent"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerEventFactory", function() { return _PointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventFactory"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerDragEvent", function() { return _PointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerDragEvent"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerUpEvent", function() { return _PointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerUpEvent"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerDownEvent", function() { return _PointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerDownEvent"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerMoveEvent", function() { return _PointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerMoveEvent"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerEnterEvent", function() { return _PointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEnterEvent"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerLeaveEvent", function() { return _PointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerLeaveEvent"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerCancelEvent", function() { return _PointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerCancelEvent"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WheelEvent", function() { return _PointerEvents__WEBPACK_IMPORTED_MODULE_3__["WheelEvent"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "createPointerEventByName", function() { return _PointerEvents__WEBPACK_IMPORTED_MODULE_3__["createPointerEventByName"]; });
/* harmony import */ var _Keyboard__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Keyboard */ "./Input/Keyboard.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Keys", function() { return _Keyboard__WEBPACK_IMPORTED_MODULE_4__["Keys"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KeyEvent", function() { return _Keyboard__WEBPACK_IMPORTED_MODULE_4__["KeyEvent"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Keyboard", function() { return _Keyboard__WEBPACK_IMPORTED_MODULE_4__["Keyboard"]; });
/* harmony import */ var _EngineInput__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./EngineInput */ "./Input/EngineInput.ts");
/* empty/unused harmony star reexport *//**
* Provides support for mice, keyboards, and controllers.
*
* [[include:Input.md]]
*/
/**
* @typedoc
*/
/***/ }),
/***/ "./Input/Keyboard.ts":
/*!***************************!*\
!*** ./Input/Keyboard.ts ***!
\***************************/
/*! exports provided: Keys, KeyEvent, Keyboard */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Keys", function() { return Keys; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KeyEvent", function() { return KeyEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Keyboard", function() { return Keyboard; });
/* harmony import */ var _Util_Log__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Util/Log */ "./Util/Log.ts");
/* harmony import */ var _Class__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Class */ "./Class.ts");
/* harmony import */ var _Events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Events */ "./Events.ts");
var __extends = (undefined && undefined.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
/**
* Enum representing input key codes
*/
var Keys;
(function (Keys) {
Keys[Keys["Num1"] = 97] = "Num1";
Keys[Keys["Num2"] = 98] = "Num2";
Keys[Keys["Num3"] = 99] = "Num3";
Keys[Keys["Num4"] = 100] = "Num4";
Keys[Keys["Num5"] = 101] = "Num5";
Keys[Keys["Num6"] = 102] = "Num6";
Keys[Keys["Num7"] = 103] = "Num7";
Keys[Keys["Num8"] = 104] = "Num8";
Keys[Keys["Num9"] = 105] = "Num9";
Keys[Keys["Num0"] = 96] = "Num0";
Keys[Keys["Numlock"] = 144] = "Numlock";
Keys[Keys["Semicolon"] = 186] = "Semicolon";
Keys[Keys["A"] = 65] = "A";
Keys[Keys["B"] = 66] = "B";
Keys[Keys["C"] = 67] = "C";
Keys[Keys["D"] = 68] = "D";
Keys[Keys["E"] = 69] = "E";
Keys[Keys["F"] = 70] = "F";
Keys[Keys["G"] = 71] = "G";
Keys[Keys["H"] = 72] = "H";
Keys[Keys["I"] = 73] = "I";
Keys[Keys["J"] = 74] = "J";
Keys[Keys["K"] = 75] = "K";
Keys[Keys["L"] = 76] = "L";
Keys[Keys["M"] = 77] = "M";
Keys[Keys["N"] = 78] = "N";
Keys[Keys["O"] = 79] = "O";
Keys[Keys["P"] = 80] = "P";
Keys[Keys["Q"] = 81] = "Q";
Keys[Keys["R"] = 82] = "R";
Keys[Keys["S"] = 83] = "S";
Keys[Keys["T"] = 84] = "T";
Keys[Keys["U"] = 85] = "U";
Keys[Keys["V"] = 86] = "V";
Keys[Keys["W"] = 87] = "W";
Keys[Keys["X"] = 88] = "X";
Keys[Keys["Y"] = 89] = "Y";
Keys[Keys["Z"] = 90] = "Z";
Keys[Keys["Shift"] = 16] = "Shift";
Keys[Keys["Alt"] = 18] = "Alt";
Keys[Keys["Up"] = 38] = "Up";
Keys[Keys["Down"] = 40] = "Down";
Keys[Keys["Left"] = 37] = "Left";
Keys[Keys["Right"] = 39] = "Right";
Keys[Keys["Space"] = 32] = "Space";
Keys[Keys["Esc"] = 27] = "Esc";
})(Keys || (Keys = {}));
/**
* Event thrown on a game object for a key event
*/
var KeyEvent = /** @class */ (function (_super) {
__extends(KeyEvent, _super);
/**
* @param key The key responsible for throwing the event
*/
function KeyEvent(key) {
var _this = _super.call(this) || this;
_this.key = key;
return _this;
}
return KeyEvent;
}(_Events__WEBPACK_IMPORTED_MODULE_2__["GameEvent"]));
/**
* Provides keyboard support for Excalibur.
*
* [[include:Keyboard.md]]
*/
var Keyboard = /** @class */ (function (_super) {
__extends(Keyboard, _super);
function Keyboard() {
var _this = _super.call(this) || this;
_this._keys = [];
_this._keysUp = [];
_this._keysDown = [];
return _this;
}
Keyboard.prototype.on = function (eventName, handler) {
_super.prototype.on.call(this, eventName, handler);
};
/**
* Initialize Keyboard event listeners
*/
Keyboard.prototype.init = function (global) {
var _this = this;
if (!global) {
try {
// Try and listen to events on top window frame if within an iframe.
//
// See https://github.com/excaliburjs/Excalibur/issues/1294
//
// Attempt to add an event listener, which triggers a DOMException on
// cross-origin iframes
var noop = function () {
return;
};
window.top.addEventListener('blur', noop);
window.top.removeEventListener('blur', noop);
// this will be the same as window if not embedded within an iframe
global = window.top;
}
catch (_a) {
// fallback to current frame
global = window;
_Util_Log__WEBPACK_IMPORTED_MODULE_0__["Logger"].getInstance().warn('Failed to bind to keyboard events to top frame. ' +
'If you are trying to embed Excalibur in a cross-origin iframe, keyboard events will not fire.');
}
}
global.addEventListener('blur', function () {
_this._keys.length = 0; // empties array efficiently
});
// key up is on window because canvas cannot have focus
global.addEventListener('keyup', function (ev) {
var code = _this._normalizeKeyCode(ev.keyCode);
var key = _this._keys.indexOf(code);
_this._keys.splice(key, 1);
_this._keysUp.push(code);
var keyEvent = new KeyEvent(code);
// alias the old api, we may want to deprecate this in the future
_this.eventDispatcher.emit('up', keyEvent);
_this.eventDispatcher.emit('release', keyEvent);
});
// key down is on window because canvas cannot have focus
global.addEventListener('keydown', function (ev) {
var code = _this._normalizeKeyCode(ev.keyCode);
if (_this._keys.indexOf(code) === -1) {
_this._keys.push(code);
_this._keysDown.push(code);
var keyEvent = new KeyEvent(code);
_this.eventDispatcher.emit('down', keyEvent);
_this.eventDispatcher.emit('press', keyEvent);
}
});
};
Keyboard.prototype.update = function () {
// Reset keysDown and keysUp after update is complete
this._keysDown.length = 0;
this._keysUp.length = 0;
// Emit synthetic "hold" event
for (var i = 0; i < this._keys.length; i++) {
this.eventDispatcher.emit('hold', new KeyEvent(this._keys[i]));
}
};
/**
* Gets list of keys being pressed down
*/
Keyboard.prototype.getKeys = function () {
return this._keys;
};
/**
* Tests if a certain key was just pressed this frame. This is cleared at the end of the update frame.
* @param key Test whether a key was just pressed
*/
Keyboard.prototype.wasPressed = function (key) {
return this._keysDown.indexOf(key) > -1;
};
/**
* Tests if a certain key is held down. This is persisted between frames.
* @param key Test whether a key is held down
*/
Keyboard.prototype.isHeld = function (key) {
return this._keys.indexOf(key) > -1;
};
/**
* Tests if a certain key was just released this frame. This is cleared at the end of the update frame.
* @param key Test whether a key was just released
*/
Keyboard.prototype.wasReleased = function (key) {
return this._keysUp.indexOf(key) > -1;
};
/**
* Normalizes some browser event key codes to map to standard Excalibur key codes
* @param code Event keyCode
* @see http://unixpapa.com/js/key.html
*/
Keyboard.prototype._normalizeKeyCode = function (code) {
switch (code) {
case 59: // : ; in Firefox, Opera
return Keys.Semicolon;
default:
return code;
}
};
return Keyboard;
}(_Class__WEBPACK_IMPORTED_MODULE_1__["Class"]));
/***/ }),
/***/ "./Input/Pointer.ts":
/*!**************************!*\
!*** ./Input/Pointer.ts ***!
\**************************/
/*! exports provided: PointerType, PointerScope, Pointer */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PointerType", function() { return PointerType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PointerScope", function() { return PointerScope; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Pointer", function() { return Pointer; });
/* harmony import */ var _Algebra__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Algebra */ "./Algebra.ts");
/* harmony import */ var _Class__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Class */ "./Class.ts");
/* harmony import */ var _Util_Actors__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Util/Actors */ "./Util/Actors.ts");
/* harmony import */ var _Util_Util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Util/Util */ "./Util/Util.ts");
var __extends = (undefined && undefined.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __spreadArrays = (undefined && undefined.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
/**
* The type of pointer for a [[PointerEvent]].
*/
var PointerType;
(function (PointerType) {
PointerType["Touch"] = "Touch";
PointerType["Mouse"] = "Mouse";
PointerType["Pen"] = "Pen";
PointerType["Unknown"] = "Unknown";
})(PointerType || (PointerType = {}));
/**
* Determines the scope of handling mouse/touch events. See [[Pointers]] for more information.
*/
var PointerScope;
(function (PointerScope) {
/**
* Handle events on the `canvas` element only. Events originating outside the
* `canvas` will not be handled.
*/
PointerScope["Canvas"] = "Canvas";
/**
* Handles events on the entire document. All events will be handled by Excalibur.
*/
PointerScope["Document"] = "Document";
})(PointerScope || (PointerScope = {}));
/**
* Captures and dispatches PointerEvents
*/
var Pointer = /** @class */ (function (_super) {
__extends(Pointer, _super);
function Pointer() {
var _this = _super.call(this) || this;
_this.id = Pointer._MAX_ID++;
_this._isDown = false;
_this._wasDown = false;
_this._actorsUnderPointer = { length: 0 };
_this._actors = [];
_this._actorsLastFrame = [];
_this._actorsNoLongerUnderPointer = [];
/**
* The last position on the document this pointer was at. Can be `null` if pointer was never active.
*/
_this.lastPagePos = null;
/**
* The last position on the screen this pointer was at. Can be `null` if pointer was never active.
*/
_this.lastScreenPos = null;
/**
* The last position in the game world coordinates this pointer was at. Can be `null` if pointer was never active.
*/
_this.lastWorldPos = null;
/**
* Returns the currently dragging target or null if it isn't exist
*/
_this.dragTarget = null;
_this.on('move', _this._onPointerMove);
_this.on('down', _this._onPointerDown);
_this.on('up', _this._onPointerUp);
return _this;
}
Object.defineProperty(Pointer.prototype, "isDragging", {
/**
* Whether the Pointer is currently dragging.
*/
get: function () {
return this._isDown;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Pointer.prototype, "isDragStart", {
/**
* Whether the Pointer just started dragging.
*/
get: function () {
return !this._wasDown && this._isDown;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Pointer.prototype, "isDragEnd", {
/**
* Whether the Pointer just ended dragging.
*/
get: function () {
return this._wasDown && !this._isDown;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Pointer.prototype, "hasActorsUnderPointer", {
/**
* Returns true if pointer has any actors under
*/
get: function () {
return !!this._actorsUnderPointer.length;
},
enumerable: false,
configurable: true
});
Pointer.prototype.on = function (event, handler) {
_super.prototype.on.call(this, event, handler);
};
Pointer.prototype.once = function (event, handler) {
_super.prototype.once.call(this, event, handler);
};
Pointer.prototype.off = function (event, handler) {
_super.prototype.off.call(this, event, handler);
};
/**
* Update the state of current pointer, meant to be called a the end of frame
*/
Pointer.prototype.update = function () {
if (this._wasDown && !this._isDown) {
this._wasDown = false;
}
else if (!this._wasDown && this._isDown) {
this._wasDown = true;
}
this._actorsLastFrame = __spreadArrays(this._actors);
this._actorsNoLongerUnderPointer = [];
};
/**
* Adds an Actor to actorsUnderPointer object.
* @param actor An Actor to be added;
*/
Pointer.prototype.addActorUnderPointer = function (actor) {
if (!this.isActorAliveUnderPointer(actor)) {
this._actorsUnderPointer[actor.id] = actor;
this._actorsUnderPointer.length += 1;
this._actors.push(actor);
}
// Actors under the pointer are sorted by z, ties are broken by id
this._actors.sort(function (a, b) {
if (a.z === b.z) {
return a.id - b.id;
}
return a.z - b.z;
});
};
/**
* Removes an Actor from actorsUnderPointer object.
* @param actor An Actor to be removed;
*/
Pointer.prototype.removeActorUnderPointer = function (actor) {
if (this.isActorAliveUnderPointer(actor)) {
delete this._actorsUnderPointer[actor.id];
this._actorsUnderPointer.length -= 1;
Object(_Util_Util__WEBPACK_IMPORTED_MODULE_3__["removeItemFromArray"])(actor, this._actors);
this._actorsNoLongerUnderPointer.push(actor);
}
};
/**
* Returns all actors under this pointer this frame
*/
Pointer.prototype.getActorsUnderPointer = function () {
return this._actors;
};
/**
* Returns all actors that are no longer under the pointer this frame
*/
Pointer.prototype.getActorsUnderPointerLastFrame = function () {
return this._actorsLastFrame;
};
/**
* Returns all actors relevant for events to pointer this frame
*/
Pointer.prototype.getActorsForEvents = function () {
return this._actors.concat(this._actorsLastFrame).filter(function (actor, i, self) {
return self.indexOf(actor) === i;
});
};
/**
* Checks if Pointer location has a specific Actor bounds contained underneath.
* @param actor An Actor for check;
*/
Pointer.prototype.checkActorUnderPointer = function (actor) {
if (this.lastWorldPos) {
return actor.contains(this.lastWorldPos.x, this.lastWorldPos.y, !_Util_Actors__WEBPACK_IMPORTED_MODULE_2__["isScreenElement"](actor));
}
return false;
};
/**
* Checks if an actor was under the pointer last frame
* @param actor
*/
Pointer.prototype.wasActorUnderPointer = function (actor) {
return this._actorsLastFrame.indexOf(actor) > -1; // || !!this._actorsUnderPointerLastFrame.hasOwnProperty(actor.id.toString());
};
/**
* Checks if Pointer has a specific Actor in ActorsUnderPointer list.
* @param actor An Actor for check;
*/
Pointer.prototype.isActorAliveUnderPointer = function (actor) {
return !!(!actor.isKilled() && actor.scene && this._actorsUnderPointer.hasOwnProperty(actor.id.toString()));
};
Pointer.prototype._onPointerMove = function (ev) {
this.lastPagePos = new _Algebra__WEBPACK_IMPORTED_MODULE_0__["Vector"](ev.pagePos.x, ev.pagePos.y);
this.lastScreenPos = new _Algebra__WEBPACK_IMPORTED_MODULE_0__["Vector"](ev.screenPos.x, ev.screenPos.y);
this.lastWorldPos = new _Algebra__WEBPACK_IMPORTED_MODULE_0__["Vector"](ev.worldPos.x, ev.worldPos.y);
};
Pointer.prototype._onPointerDown = function (ev) {
this.lastPagePos = new _Algebra__WEBPACK_IMPORTED_MODULE_0__["Vector"](ev.pagePos.x, ev.pagePos.y);
this.lastScreenPos = new _Algebra__WEBPACK_IMPORTED_MODULE_0__["Vector"](ev.screenPos.x, ev.screenPos.y);
this.lastWorldPos = new _Algebra__WEBPACK_IMPORTED_MODULE_0__["Vector"](ev.worldPos.x, ev.worldPos.y);
this._isDown = true;
};
Pointer.prototype._onPointerUp = function (_ev) {
this._isDown = false;
this.dragTarget = null;
};
Pointer._MAX_ID = 0;
return Pointer;
}(_Class__WEBPACK_IMPORTED_MODULE_1__["Class"]));
/***/ }),
/***/ "./Input/PointerEvents.ts":
/*!********************************!*\
!*** ./Input/PointerEvents.ts ***!
\********************************/
/*! exports provided: NativePointerButton, PointerButton, WheelDeltaMode, PointerEvent, PointerEventFactory, PointerDragEvent, PointerUpEvent, PointerDownEvent, PointerMoveEvent, PointerEnterEvent, PointerLeaveEvent, PointerCancelEvent, WheelEvent, createPointerEventByName */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NativePointerButton", function() { return NativePointerButton; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PointerButton", function() { return PointerButton; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WheelDeltaMode", function() { return WheelDeltaMode; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PointerEvent", function() { return PointerEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PointerEventFactory", function() { return PointerEventFactory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PointerDragEvent", function() { return PointerDragEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PointerUpEvent", function() { return PointerUpEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PointerDownEvent", function() { return PointerDownEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PointerMoveEvent", function() { return PointerMoveEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PointerEnterEvent", function() { return PointerEnterEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PointerLeaveEvent", function() { return PointerLeaveEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PointerCancelEvent", function() { return PointerCancelEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WheelEvent", function() { return WheelEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createPointerEventByName", function() { return createPointerEventByName; });
/* harmony import */ var _Events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Events */ "./Events.ts");
var __extends = (undefined && undefined.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
/**
* Native browser button enumeration
*/
var NativePointerButton;
(function (NativePointerButton) {
NativePointerButton[NativePointerButton["NoButton"] = -1] = "NoButton";
NativePointerButton[NativePointerButton["Left"] = 0] = "Left";
NativePointerButton[NativePointerButton["Middle"] = 1] = "Middle";
NativePointerButton[NativePointerButton["Right"] = 2] = "Right";
NativePointerButton[NativePointerButton["Unknown"] = 3] = "Unknown";
})(NativePointerButton || (NativePointerButton = {}));
/**
* The mouse button being pressed.
*/
var PointerButton;
(function (PointerButton) {
PointerButton["Left"] = "Left";
PointerButton["Middle"] = "Middle";
PointerButton["Right"] = "Right";
PointerButton["Unknown"] = "Unknown";
PointerButton["NoButton"] = "NoButton";
})(PointerButton || (PointerButton = {}));
var WheelDeltaMode;
(function (WheelDeltaMode) {
WheelDeltaMode["Pixel"] = "Pixel";
WheelDeltaMode["Line"] = "Line";
WheelDeltaMode["Page"] = "Page";
})(WheelDeltaMode || (WheelDeltaMode = {}));
/**
* Pointer events
*
* Represents a mouse, touch, or stylus event. See [[Pointers]] for more information on
* handling pointer input.
*
* For mouse-based events, you can inspect [[PointerEvent.button]] to see what button was pressed.
*/
var PointerEvent = /** @class */ (function (_super) {
__extends(PointerEvent, _super);
/**
* @param coordinates The [[GlobalCoordinates]] of the event
* @param pointer The [[Pointer]] of the event
* @param index The index of the pointer (zero-based)
* @param pointerType The type of pointer
* @param button The button pressed (if [[PointerType.Mouse]])
* @param ev The raw DOM event being handled
* @param pos (Will be added to signature in 0.14.0 release) The position of the event (in world coordinates)
*/
function PointerEvent(coordinates, pointer, index, pointerType, button, ev) {
var _this = _super.call(this) || this;
_this.coordinates = coordinates;
_this.pointer = pointer;
_this.index = index;
_this.pointerType = pointerType;
_this.button = button;
_this.ev = ev;
return _this;
}
Object.defineProperty(PointerEvent.prototype, "name", {
get: function () {
return this._name;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PointerEvent.prototype, "worldPos", {
/** The world coordinates of the event. */
get: function () {
return this.coordinates.worldPos.clone();
},
enumerable: false,
configurable: true
});
Object.defineProperty(PointerEvent.prototype, "pagePos", {
/** The page coordinates of the event. */
get: function () {
return this.coordinates.pagePos.clone();
},
enumerable: false,
configurable: true
});
Object.defineProperty(PointerEvent.prototype, "screenPos", {
/** The screen coordinates of the event. */
get: function () {
return this.coordinates.screenPos.clone();
},
enumerable: false,
configurable: true
});
Object.defineProperty(PointerEvent.prototype, "pos", {
get: function () {
return this.coordinates.worldPos.clone();
},
enumerable: false,
configurable: true
});
PointerEvent.prototype.propagate = function (actor) {
this.doAction(actor);
if (this.bubbles && actor.parent) {
this.propagate(actor.parent);
}
};
/**
* Action, that calls when event happens
*/
PointerEvent.prototype.doAction = function (actor) {
if (actor) {
this._onActionStart(actor);
actor.emit(this._name, this);
this._onActionEnd(actor);
}
};
PointerEvent.prototype._onActionStart = function (_actor) {
// to be rewritten
};
PointerEvent.prototype._onActionEnd = function (_actor) {
// to be rewritten
};
return PointerEvent;
}(_Events__WEBPACK_IMPORTED_MODULE_0__["GameEvent"]));
var PointerEventFactory = /** @class */ (function () {
function PointerEventFactory(_pointerEventType) {
this._pointerEventType = _pointerEventType;
}
/**
* Create specific PointerEvent
*/
PointerEventFactory.prototype.create = function (coordinates, pointer, index, pointerType, button, ev) {
return new this._pointerEventType(coordinates, pointer, index, pointerType, button, ev);
};
return PointerEventFactory;
}());
var PointerDragEvent = /** @class */ (function (_super) {
__extends(PointerDragEvent, _super);
function PointerDragEvent() {
return _super !== null && _super.apply(this, arguments) || this;
}
return PointerDragEvent;
}(PointerEvent));
var PointerUpEvent = /** @class */ (function (_super) {
__extends(PointerUpEvent, _super);
function PointerUpEvent() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this._name = 'pointerup';
return _this;
}
PointerUpEvent.prototype._onActionEnd = function (actor) {
var pointer = this.pointer;
if (pointer.isDragEnd && actor.capturePointer.captureDragEvents) {
actor.eventDispatcher.emit('pointerdragend', this);
}
};
return PointerUpEvent;
}(PointerEvent));
var PointerDownEvent = /** @class */ (function (_super) {
__extends(PointerDownEvent, _super);
function PointerDownEvent() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this._name = 'pointerdown';
return _this;
}
PointerDownEvent.prototype._onActionEnd = function (actor) {
if (this.pointer.isDragStart && actor.capturePointer.captureDragEvents) {
actor.eventDispatcher.emit('pointerdragstart', this);
}
};
return PointerDownEvent;
}(PointerEvent));
var PointerMoveEvent = /** @class */ (function (_super) {
__extends(PointerMoveEvent, _super);
function PointerMoveEvent() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this._name = 'pointermove';
return _this;
// private _onActorEnter(actor: Actor) {
// const pe = createPointerEventByName('enter', this.coordinates, this.pointer, this.index, this.pointerType, this.button, this.ev);
// pe.propagate(actor);
// this.pointer.addActorUnderPointer(actor);
// if (this.pointer.isDragging) {
// this.pointer.dragTarget = actor;
// }
// }
// private _onActorLeave(actor: Actor) {
// const pe = createPointerEventByName('leave', this.coordinates, this.pointer, this.index, this.pointerType, this.button, this.ev);
// pe.propagate(actor);
// this.pointer.removeActorUnderPointer(actor);
// }
}
PointerMoveEvent.prototype.propagate = function (actor) {
// If the actor was under the pointer last frame, but not this one it left
// if (this.pointer.wasActorUnderPointer(actor) && !this.pointer.isActorUnderPointer(actor)) {
// this._onActorLeave(actor);
// return;
// }
if (this.pointer.isActorAliveUnderPointer(actor)) {
this.doAction(actor);
if (this.bubbles && actor.parent) {
this.propagate(actor.parent);
}
}
};
PointerMoveEvent.prototype._onActionStart = function (actor) {
if (!actor.capturePointer.captureMoveEvents) {
return;
}
// In the case this is new
// if (this.pointer.checkActorUnderPointer(actor) && !this.pointer.wasActorUnderPointer(actor)) {
// this._onActorEnter(actor);
// }
if (this.pointer.isDragging && actor.capturePointer.captureDragEvents) {
actor.eventDispatcher.emit('pointerdragmove', this);
}
};
return PointerMoveEvent;
}(PointerEvent));
var PointerEnterEvent = /** @class */ (function (_super) {
__extends(PointerEnterEvent, _super);
function PointerEnterEvent() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this._name = 'pointerenter';
return _this;
}
PointerEnterEvent.prototype._onActionStart = function (actor) {
if (!actor.capturePointer.captureMoveEvents) {
return;
}
};
PointerEnterEvent.prototype._onActionEnd = function (actor) {
var pointer = this.pointer;
if (pointer.isDragging && actor.capturePointer.captureDragEvents) {
actor.eventDispatcher.emit('pointerdragenter', this);
}
};
return PointerEnterEvent;
}(PointerEvent));
var PointerLeaveEvent = /** @class */ (function (_super) {
__extends(PointerLeaveEvent, _super);
function PointerLeaveEvent() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this._name = 'pointerleave';
return _this;
}
PointerLeaveEvent.prototype._onActionStart = function (actor) {
if (!actor.capturePointer.captureMoveEvents) {
return;
}
};
PointerLeaveEvent.prototype._onActionEnd = function (actor) {
var pointer = this.pointer;
if (pointer.isDragging && actor.capturePointer.captureDragEvents) {
actor.eventDispatcher.emit('pointerdragleave', this);
}
};
return PointerLeaveEvent;
}(PointerEvent));
var PointerCancelEvent = /** @class */ (function (_super) {
__extends(PointerCancelEvent, _super);
function PointerCancelEvent() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this._name = 'pointercancel';
return _this;
}
return PointerCancelEvent;
}(PointerEvent));
/**
* Wheel Events
*
* Represents a mouse wheel event. See [[Pointers]] for more information on
* handling point input.
*/
var WheelEvent = /** @class */ (function (_super) {
__extends(WheelEvent, _super);
/**
* @param x The `x` coordinate of the event (in world coordinates)
* @param y The `y` coordinate of the event (in world coordinates)
* @param pageX The `x` coordinate of the event (in document coordinates)
* @param pageY The `y` coordinate of the event (in document coordinates)
* @param screenX The `x` coordinate of the event (in screen coordinates)
* @param screenY The `y` coordinate of the event (in screen coordinates)
* @param index The index of the pointer (zero-based)
* @param deltaX The type of pointer
* @param deltaY The type of pointer
* @param deltaZ The type of pointer
* @param deltaMode The type of movement [[WheelDeltaMode]]
* @param ev The raw DOM event being handled
*/
function WheelEvent(x, y, pageX, pageY, screenX, screenY, index, deltaX, deltaY, deltaZ, deltaMode, ev) {
var _this = _super.call(this) || this;
_this.x = x;
_this.y = y;
_this.pageX = pageX;
_this.pageY = pageY;
_this.screenX = screenX;
_this.screenY = screenY;
_this.index = index;
_this.deltaX = deltaX;
_this.deltaY = deltaY;
_this.deltaZ = deltaZ;
_this.deltaMode = deltaMode;
_this.ev = ev;
return _this;
}
return WheelEvent;
}(_Events__WEBPACK_IMPORTED_MODULE_0__["GameEvent"]));
function createPointerEventByName(eventName, coordinates, pointer, index, pointerType, button, ev) {
var factory;
switch (eventName) {
case 'up':
factory = new PointerEventFactory(PointerUpEvent);
break;
case 'down':
factory = new PointerEventFactory(PointerDownEvent);
break;
case 'move':
factory = new PointerEventFactory(PointerMoveEvent);
break;
case 'cancel':
factory = new PointerEventFactory(PointerCancelEvent);
break;
case 'enter':
factory = new PointerEventFactory(PointerEnterEvent);
break;
case 'leave':
factory = new PointerEventFactory(PointerLeaveEvent);
break;
}
return factory.create(coordinates, pointer, index, pointerType, button, ev);
}
/***/ }),
/***/ "./Input/Pointers.ts":
/*!***************************!*\
!*** ./Input/Pointers.ts ***!
\***************************/
/*! exports provided: Pointers */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Pointers", function() { return Pointers; });
/* harmony import */ var _Class__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Class */ "./Class.ts");
/* harmony import */ var _Engine__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Engine */ "./Engine.ts");
/* harmony import */ var _Pointer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Pointer */ "./Input/Pointer.ts");
/* harmony import */ var _PointerEvents__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./PointerEvents */ "./Input/PointerEvents.ts");
/* harmony import */ var _Util_Util__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Util/Util */ "./Util/Util.ts");
/* harmony import */ var _Algebra__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Algebra */ "./Algebra.ts");
/* harmony import */ var _Traits_CapturePointer__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Traits/CapturePointer */ "./Traits/CapturePointer.ts");
var __extends = (undefined && undefined.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
/**
* A constant used to normalize wheel events across different browsers
*
* This normalization factor is pulled from https://developer.mozilla.org/en-US/docs/Web/Events/wheel#Listening_to_this_event_across_browser
*/
var ScrollWheelNormalizationFactor = -1 / 40;
/**
* Handles pointer events (mouse, touch, stylus, etc.) and normalizes to
* [W3C Pointer Events](http://www.w3.org/TR/pointerevents/).
*
* [[include:Pointers.md]]
*/
var Pointers = /** @class */ (function (_super) {
__extends(Pointers, _super);
function Pointers(engine) {
var _this = _super.call(this) || this;
_this._pointerDown = [];
_this._pointerUp = [];
_this._pointerMove = [];
_this._pointerCancel = [];
_this._wheel = [];
_this._pointers = [];
_this._activePointers = [];
_this._engine = engine;
_this._pointers.push(new _Pointer__WEBPACK_IMPORTED_MODULE_2__["Pointer"]());
_this._activePointers = [-1];
_this.primary = _this._pointers[0];
return _this;
}
Pointers.prototype.on = function (eventName, handler) {
_super.prototype.on.call(this, eventName, handler);
};
/**
* Initializes pointer event listeners
*/
Pointers.prototype.init = function (target) {
target = target || this._engine.canvas;
// Touch Events
target.addEventListener('touchstart', this._handleTouchEvent('down', this._pointerDown));
target.addEventListener('touchend', this._handleTouchEvent('up', this._pointerUp));
target.addEventListener('touchmove', this._handleTouchEvent('move', this._pointerMove));
target.addEventListener('touchcancel', this._handleTouchEvent('cancel', this._pointerCancel));
// W3C Pointer Events
// Current: IE11, IE10
if (window.PointerEvent) {
// IE11
this._engine.canvas.style.touchAction = 'none';
target.addEventListener('pointerdown', this._handlePointerEvent('down', this._pointerDown));
target.addEventListener('pointerup', this._handlePointerEvent('up', this._pointerUp));
target.addEventListener('pointermove', this._handlePointerEvent('move', this._pointerMove));
target.addEventListener('pointercancel', this._handlePointerEvent('cancel', this._pointerCancel));
}
else if (window.MSPointerEvent) {
// IE10
this._engine.canvas.style.msTouchAction = 'none';
target.addEventListener('MSPointerDown', this._handlePointerEvent('down', this._pointerDown));
target.addEventListener('MSPointerUp', this._handlePointerEvent('up', this._pointerUp));
target.addEventListener('MSPointerMove', this._handlePointerEvent('move', this._pointerMove));
target.addEventListener('MSPointerCancel', this._handlePointerEvent('cancel', this._pointerCancel));
}
else {
// Mouse Events
target.addEventListener('mousedown', this._handleMouseEvent('down', this._pointerDown));
target.addEventListener('mouseup', this._handleMouseEvent('up', this._pointerUp));
target.addEventListener('mousemove', this._handleMouseEvent('move', this._pointerMove));
}
// MDN MouseWheelEvent
var wheelOptions = {
passive: !(this._engine.pageScrollPreventionMode === _Engine__WEBPACK_IMPORTED_MODULE_1__["ScrollPreventionMode"].All ||
this._engine.pageScrollPreventionMode === _Engine__WEBPACK_IMPORTED_MODULE_1__["ScrollPreventionMode"].Canvas)
};
if ('onwheel' in document.createElement('div')) {
// Modern Browsers
target.addEventListener('wheel', this._handleWheelEvent('wheel', this._wheel), wheelOptions);
}
else if (document.onmousewheel !== undefined) {
// Webkit and IE
target.addEventListener('mousewheel', this._handleWheelEvent('wheel', this._wheel), wheelOptions);
}
else {
// Remaining browser and older Firefox
target.addEventListener('MozMousePixelScroll', this._handleWheelEvent('wheel', this._wheel), wheelOptions);
}
};
/**
* Synthesize a pointer event that looks like a real browser event to excalibur
* @param eventName
* @param pos
*/
Pointers.prototype.triggerEvent = function (eventName, pos, button, pointerType, pointerId) {
if (button === void 0) { button = _PointerEvents__WEBPACK_IMPORTED_MODULE_3__["NativePointerButton"].Left; }
if (pointerType === void 0) { pointerType = 'mouse'; }
if (pointerId === void 0) { pointerId = 0; }
var x = 0;
var y = 0;
var coords;
if (pos instanceof _Algebra__WEBPACK_IMPORTED_MODULE_5__["GlobalCoordinates"]) {
x = pos.pagePos.x;
y = pos.pagePos.y;
coords = pos;
}
else {
x = pos.x;
y = pos.y;
coords = new _Algebra__WEBPACK_IMPORTED_MODULE_5__["GlobalCoordinates"](pos.clone(), pos.clone(), pos.clone());
}
var eventish = {
pageX: x,
pageY: y,
pointerId: pointerId,
pointerType: pointerType,
button: button,
preventDefault: function () {
/* do nothing */
}
};
switch (eventName) {
case 'move':
this._handlePointerEvent(eventName, this._pointerMove, coords)(eventish);
break;
case 'down':
this._handlePointerEvent(eventName, this._pointerDown, coords)(eventish);
break;
case 'up':
this._handlePointerEvent(eventName, this._pointerUp, coords)(eventish);
break;
case 'cancel':
this._handlePointerEvent(eventName, this._pointerCancel, coords)(eventish);
break;
}
for (var _i = 0, _a = this._engine.currentScene.actors; _i < _a.length; _i++) {
var actor = _a[_i];
var capturePointer = actor.traits.filter(function (t) { return t instanceof _Traits_CapturePointer__WEBPACK_IMPORTED_MODULE_6__["CapturePointer"]; })[0];
if (capturePointer) {
capturePointer.update(actor, this._engine, 1);
}
}
this.dispatchPointerEvents();
this.update();
};
/**
* Update all pointer events and pointers, meant to be called at the end of frame
*/
Pointers.prototype.update = function () {
this._pointerUp.length = 0;
this._pointerDown.length = 0;
this._pointerMove.length = 0;
this._pointerCancel.length = 0;
this._wheel.length = 0;
for (var i = 0; i < this._pointers.length; i++) {
this._pointers[i].update();
}
};
/**
* Safely gets a Pointer at a specific index and initializes one if it doesn't yet exist
* @param index The pointer index to retrieve
*/
Pointers.prototype.at = function (index) {
if (index >= this._pointers.length) {
// Ensure there is a pointer to retrieve
for (var i = this._pointers.length - 1, max = index; i < max; i++) {
this._pointers.push(new _Pointer__WEBPACK_IMPORTED_MODULE_2__["Pointer"]());
this._activePointers.push(-1);
}
}
return this._pointers[index];
};
/**
* Get number of pointers being watched
*/
Pointers.prototype.count = function () {
return this._pointers.length;
};
Pointers.prototype.checkAndUpdateActorUnderPointer = function (actor) {
for (var _i = 0, _a = this._pointers; _i < _a.length; _i++) {
var pointer = _a[_i];
if (pointer.checkActorUnderPointer(actor)) {
pointer.addActorUnderPointer(actor);
}
else {
pointer.removeActorUnderPointer(actor);
}
}
};
Pointers.prototype._dispatchWithBubble = function (events) {
for (var _i = 0, events_1 = events; _i < events_1.length; _i++) {
var evt = events_1[_i];
for (var _a = 0, _b = evt.pointer.getActorsForEvents(); _a < _b.length; _a++) {
var actor = _b[_a];
evt.propagate(actor);
if (!evt.bubbles) {
// if the event stops bubbling part way stop processing
break;
}
}
}
};
Pointers.prototype._dispatchPointerLeaveEvents = function () {
var lastMoveEventPerPointerPerActor = {};
var pointerLeave = [];
for (var _i = 0, _a = this._pointerMove; _i < _a.length; _i++) {
var evt = _a[_i];
for (var _b = 0, _c = evt.pointer.getActorsForEvents(); _b < _c.length; _b++) {
var actor = _c[_b];
// If the actor was under the pointer last frame, but not this this frame, pointer left
if (!lastMoveEventPerPointerPerActor[evt.pointer.id + '+' + actor.id] &&
evt.pointer.wasActorUnderPointer(actor) &&
!evt.pointer.isActorAliveUnderPointer(actor)) {
lastMoveEventPerPointerPerActor[evt.pointer.id + '+' + actor.id] = evt;
var pe = Object(_PointerEvents__WEBPACK_IMPORTED_MODULE_3__["createPointerEventByName"])('leave', new _Algebra__WEBPACK_IMPORTED_MODULE_5__["GlobalCoordinates"](evt.worldPos, evt.pagePos, evt.screenPos), evt.pointer, evt.index, evt.pointerType, evt.button, evt.ev);
pe.propagate(actor);
pointerLeave.push(pe);
}
}
}
return pointerLeave;
};
Pointers.prototype._dispatchPointerEnterEvents = function () {
var lastMoveEventPerPointer = {};
var pointerEnter = [];
for (var _i = 0, _a = this._pointerMove; _i < _a.length; _i++) {
var evt = _a[_i];
for (var _b = 0, _c = evt.pointer.getActorsForEvents(); _b < _c.length; _b++) {
var actor = _c[_b];
// If the actor was not under the pointer last frame, but it is this frame, pointer entered
if (!lastMoveEventPerPointer[evt.pointer.id] &&
!evt.pointer.wasActorUnderPointer(actor) &&
evt.pointer.isActorAliveUnderPointer(actor)) {
lastMoveEventPerPointer[evt.pointer.id] = evt;
var pe = Object(_PointerEvents__WEBPACK_IMPORTED_MODULE_3__["createPointerEventByName"])('enter', new _Algebra__WEBPACK_IMPORTED_MODULE_5__["GlobalCoordinates"](evt.worldPos, evt.pagePos, evt.screenPos), evt.pointer, evt.index, evt.pointerType, evt.button, evt.ev);
pe.propagate(actor);
pointerEnter.push(pe);
// if pointer is dragging set the drag target
if (evt.pointer.isDragging) {
evt.pointer.dragTarget = actor;
}
}
}
}
return pointerEnter;
};
Pointers.prototype.dispatchPointerEvents = function () {
this._dispatchWithBubble(this._pointerDown);
this._dispatchWithBubble(this._pointerUp);
this._dispatchWithBubble(this._pointerMove);
this._dispatchPointerLeaveEvents();
this._dispatchPointerEnterEvents();
this._dispatchWithBubble(this._pointerCancel);
// TODO some duplication here
for (var _i = 0, _a = this._wheel; _i < _a.length; _i++) {
var evt = _a[_i];
for (var _b = 0, _c = this._pointers[evt.index].getActorsUnderPointer(); _b < _c.length; _b++) {
var actor = _c[_b];
this._propagateWheelPointerEvent(actor, evt);
if (!evt.bubbles) {
// if the event stops bubbling part way stop processing
break;
}
}
}
};
Pointers.prototype._propagateWheelPointerEvent = function (actor, wheelEvent) {
actor.emit('pointerwheel', wheelEvent);
// Recurse and propagate
if (wheelEvent.bubbles && actor.parent) {
this._propagateWheelPointerEvent(actor.parent, wheelEvent);
}
};
Pointers.prototype._handleMouseEvent = function (eventName, eventArr) {
var _this = this;
return function (e) {
e.preventDefault();
var pointer = _this.at(0);
var coordinates = _Algebra__WEBPACK_IMPORTED_MODULE_5__["GlobalCoordinates"].fromPagePosition(e.pageX, e.pageY, _this._engine);
var pe = Object(_PointerEvents__WEBPACK_IMPORTED_MODULE_3__["createPointerEventByName"])(eventName, coordinates, pointer, 0, _Pointer__WEBPACK_IMPORTED_MODULE_2__["PointerType"].Mouse, _this._nativeButtonToPointerButton(e.button), e);
eventArr.push(pe);
pointer.eventDispatcher.emit(eventName, pe);
};
};
Pointers.prototype._handleTouchEvent = function (eventName, eventArr) {
var _this = this;
return function (e) {
e.preventDefault();
for (var i = 0, len = e.changedTouches.length; i < len; i++) {
var index = _this._pointers.length > 1 ? _this._getPointerIndex(e.changedTouches[i].identifier) : 0;
if (index === -1) {
continue;
}
var pointer = _this.at(index);
var coordinates = _Algebra__WEBPACK_IMPORTED_MODULE_5__["GlobalCoordinates"].fromPagePosition(e.changedTouches[i].pageX, e.changedTouches[i].pageY, _this._engine);
var pe = Object(_PointerEvents__WEBPACK_IMPORTED_MODULE_3__["createPointerEventByName"])(eventName, coordinates, pointer, index, _Pointer__WEBPACK_IMPORTED_MODULE_2__["PointerType"].Touch, _PointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerButton"].Unknown, e);
eventArr.push(pe);
pointer.eventDispatcher.emit(eventName, pe);
// only with multi-pointer
if (_this._pointers.length > 1) {
if (eventName === 'up') {
// remove pointer ID from pool when pointer is lifted
_this._activePointers[index] = -1;
}
else if (eventName === 'down') {
// set pointer ID to given index
_this._activePointers[index] = e.changedTouches[i].identifier;
}
}
}
};
};
Pointers.prototype._handlePointerEvent = function (eventName, eventArr, coords) {
var _this = this;
return function (e) {
e.preventDefault();
// get the index for this pointer ID if multi-pointer is asked for
var index = _this._pointers.length > 1 ? _this._getPointerIndex(e.pointerId) : 0;
if (index === -1) {
return;
}
var pointer = _this.at(index);
var coordinates = coords || _Algebra__WEBPACK_IMPORTED_MODULE_5__["GlobalCoordinates"].fromPagePosition(e.pageX, e.pageY, _this._engine);
var pe = Object(_PointerEvents__WEBPACK_IMPORTED_MODULE_3__["createPointerEventByName"])(eventName, coordinates, pointer, index, _this._stringToPointerType(e.pointerType), _this._nativeButtonToPointerButton(e.button), e);
eventArr.push(pe);
pointer.eventDispatcher.emit(eventName, pe);
// only with multi-pointer
if (_this._pointers.length > 1) {
if (eventName === 'up') {
// remove pointer ID from pool when pointer is lifted
_this._activePointers[index] = -1;
}
else if (eventName === 'down') {
// set pointer ID to given index
_this._activePointers[index] = e.pointerId;
}
}
};
};
Pointers.prototype._handleWheelEvent = function (eventName, eventArr) {
var _this = this;
return function (e) {
// Should we prevent page scroll because of this event
if (_this._engine.pageScrollPreventionMode === _Engine__WEBPACK_IMPORTED_MODULE_1__["ScrollPreventionMode"].All ||
(_this._engine.pageScrollPreventionMode === _Engine__WEBPACK_IMPORTED_MODULE_1__["ScrollPreventionMode"].Canvas && e.target === _this._engine.canvas)) {
e.preventDefault();
}
var x = e.pageX - _Util_Util__WEBPACK_IMPORTED_MODULE_4__["getPosition"](_this._engine.canvas).x;
var y = e.pageY - _Util_Util__WEBPACK_IMPORTED_MODULE_4__["getPosition"](_this._engine.canvas).y;
var transformedPoint = _this._engine.screenToWorldCoordinates(new _Algebra__WEBPACK_IMPORTED_MODULE_5__["Vector"](x, y));
// deltaX, deltaY, and deltaZ are the standard modern properties
// wheelDeltaX, wheelDeltaY, are legacy properties in webkit browsers and older IE
// e.detail is only used in opera
var deltaX = e.deltaX || e.wheelDeltaX * ScrollWheelNormalizationFactor || 0;
var deltaY = e.deltaY || e.wheelDeltaY * ScrollWheelNormalizationFactor || e.wheelDelta * ScrollWheelNormalizationFactor || e.detail || 0;
var deltaZ = e.deltaZ || 0;
var deltaMode = _PointerEvents__WEBPACK_IMPORTED_MODULE_3__["WheelDeltaMode"].Pixel;
if (e.deltaMode) {
if (e.deltaMode === 1) {
deltaMode = _PointerEvents__WEBPACK_IMPORTED_MODULE_3__["WheelDeltaMode"].Line;
}
else if (e.deltaMode === 2) {
deltaMode = _PointerEvents__WEBPACK_IMPORTED_MODULE_3__["WheelDeltaMode"].Page;
}
}
var we = new _PointerEvents__WEBPACK_IMPORTED_MODULE_3__["WheelEvent"](transformedPoint.x, transformedPoint.y, e.pageX, e.pageY, x, y, 0, deltaX, deltaY, deltaZ, deltaMode, e);
eventArr.push(we);
_this.at(0).eventDispatcher.emit(eventName, we);
};
};
/**
* Gets the index of the pointer specified for the given pointer ID or finds the next empty pointer slot available.
* This is required because IE10/11 uses incrementing pointer IDs so we need to store a mapping of ID => idx
*/
Pointers.prototype._getPointerIndex = function (pointerId) {
var idx;
if ((idx = this._activePointers.indexOf(pointerId)) > -1) {
return idx;
}
for (var i = 0; i < this._activePointers.length; i++) {
if (this._activePointers[i] === -1) {
return i;
}
}
// ignore pointer because game isn't watching
return -1;
};
Pointers.prototype._nativeButtonToPointerButton = function (s) {
switch (s) {
case _PointerEvents__WEBPACK_IMPORTED_MODULE_3__["NativePointerButton"].NoButton:
return _PointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerButton"].NoButton;
case _PointerEvents__WEBPACK_IMPORTED_MODULE_3__["NativePointerButton"].Left:
return _PointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerButton"].Left;
case _PointerEvents__WEBPACK_IMPORTED_MODULE_3__["NativePointerButton"].Middle:
return _PointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerButton"].Middle;
case _PointerEvents__WEBPACK_IMPORTED_MODULE_3__["NativePointerButton"].Right:
return _PointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerButton"].Right;
case _PointerEvents__WEBPACK_IMPORTED_MODULE_3__["NativePointerButton"].Unknown:
return _PointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerButton"].Unknown;
default:
return _Util_Util__WEBPACK_IMPORTED_MODULE_4__["fail"](s);
}
};
Pointers.prototype._stringToPointerType = function (s) {
switch (s) {
case 'touch':
return _Pointer__WEBPACK_IMPORTED_MODULE_2__["PointerType"].Touch;
case 'mouse':
return _Pointer__WEBPACK_IMPORTED_MODULE_2__["PointerType"].Mouse;
case 'pen':
return _Pointer__WEBPACK_IMPORTED_MODULE_2__["PointerType"].Pen;
default:
return _Pointer__WEBPACK_IMPORTED_MODULE_2__["PointerType"].Unknown;
}
};
return Pointers;
}(_Class__WEBPACK_IMPORTED_MODULE_0__["Class"]));
/***/ }),
/***/ "./Interfaces/Audio.ts":
/*!*****************************!*\
!*** ./Interfaces/Audio.ts ***!
\*****************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/***/ }),
/***/ "./Interfaces/AudioImplementation.ts":
/*!*******************************************!*\
!*** ./Interfaces/AudioImplementation.ts ***!
\*******************************************/
/*! exports provided: ExResponse */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ExResponse", function() { return ExResponse; });
var ExResponse = /** @class */ (function () {
function ExResponse() {
}
ExResponse.type = {
any: '',
blob: 'blob',
json: 'json',
text: 'text',
document: 'document',
arraybuffer: 'arraybuffer'
};
return ExResponse;
}());
/***/ }),
/***/ "./Interfaces/Drawable.ts":
/*!********************************!*\
!*** ./Interfaces/Drawable.ts ***!
\********************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/***/ }),
/***/ "./Interfaces/Evented.ts":
/*!*******************************!*\
!*** ./Interfaces/Evented.ts ***!
\*******************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/***/ }),
/***/ "./Interfaces/Index.ts":
/*!*****************************!*\
!*** ./Interfaces/Index.ts ***!
\*****************************/
/*! exports provided: ExResponse, has_initialize, hasOnInitialize, has_preupdate, hasOnPreUpdate, has_postupdate, hasOnPostUpdate, hasPreDraw, hasPostDraw */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _Trait__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Trait */ "./Interfaces/Trait.ts");
/* empty/unused harmony star reexport *//* harmony import */ var _Audio__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Audio */ "./Interfaces/Audio.ts");
/* empty/unused harmony star reexport *//* harmony import */ var _AudioImplementation__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./AudioImplementation */ "./Interfaces/AudioImplementation.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ExResponse", function() { return _AudioImplementation__WEBPACK_IMPORTED_MODULE_2__["ExResponse"]; });
/* harmony import */ var _Drawable__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Drawable */ "./Interfaces/Drawable.ts");
/* empty/unused harmony star reexport *//* harmony import */ var _Evented__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Evented */ "./Interfaces/Evented.ts");
/* empty/unused harmony star reexport *//* harmony import */ var _Loadable__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Loadable */ "./Interfaces/Loadable.ts");
/* empty/unused harmony star reexport *//* harmony import */ var _Loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Loader */ "./Interfaces/Loader.ts");
/* empty/unused harmony star reexport *//* harmony import */ var _LifecycleEvents__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./LifecycleEvents */ "./Interfaces/LifecycleEvents.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "has_initialize", function() { return _LifecycleEvents__WEBPACK_IMPORTED_MODULE_7__["has_initialize"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "hasOnInitialize", function() { return _LifecycleEvents__WEBPACK_IMPORTED_MODULE_7__["hasOnInitialize"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "has_preupdate", function() { return _LifecycleEvents__WEBPACK_IMPORTED_MODULE_7__["has_preupdate"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "hasOnPreUpdate", function() { return _LifecycleEvents__WEBPACK_IMPORTED_MODULE_7__["hasOnPreUpdate"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "has_postupdate", function() { return _LifecycleEvents__WEBPACK_IMPORTED_MODULE_7__["has_postupdate"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "hasOnPostUpdate", function() { return _LifecycleEvents__WEBPACK_IMPORTED_MODULE_7__["hasOnPostUpdate"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "hasPreDraw", function() { return _LifecycleEvents__WEBPACK_IMPORTED_MODULE_7__["hasPreDraw"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "hasPostDraw", function() { return _LifecycleEvents__WEBPACK_IMPORTED_MODULE_7__["hasPostDraw"]; });
/* harmony import */ var _PointerEventHandlers__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./PointerEventHandlers */ "./Interfaces/PointerEventHandlers.ts");
/* empty/unused harmony star reexport */
/***/ }),
/***/ "./Interfaces/LifecycleEvents.ts":
/*!***************************************!*\
!*** ./Interfaces/LifecycleEvents.ts ***!
\***************************************/
/*! exports provided: has_initialize, hasOnInitialize, has_preupdate, hasOnPreUpdate, has_postupdate, hasOnPostUpdate, hasPreDraw, hasPostDraw */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "has_initialize", function() { return has_initialize; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasOnInitialize", function() { return hasOnInitialize; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "has_preupdate", function() { return has_preupdate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasOnPreUpdate", function() { return hasOnPreUpdate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "has_postupdate", function() { return has_postupdate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasOnPostUpdate", function() { return hasOnPostUpdate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasPreDraw", function() { return hasPreDraw; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasPostDraw", function() { return hasPostDraw; });
function has_initialize(a) {
return !!a._initialize;
}
function hasOnInitialize(a) {
return !!a.onInitialize;
}
function has_preupdate(a) {
return !!a._preupdate;
}
function hasOnPreUpdate(a) {
return !!a.onPreUpdate;
}
function has_postupdate(a) {
return !!a.onPostUpdate;
}
function hasOnPostUpdate(a) {
return !!a.onPostUpdate;
}
function hasPreDraw(a) {
return !!a.onPreDraw;
}
function hasPostDraw(a) {
return !!a.onPostDraw;
}
/***/ }),
/***/ "./Interfaces/Loadable.ts":
/*!********************************!*\
!*** ./Interfaces/Loadable.ts ***!
\********************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/***/ }),
/***/ "./Interfaces/Loader.ts":
/*!******************************!*\
!*** ./Interfaces/Loader.ts ***!
\******************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/***/ }),
/***/ "./Interfaces/PointerEventHandlers.ts":
/*!********************************************!*\
!*** ./Interfaces/PointerEventHandlers.ts ***!
\********************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/***/ }),
/***/ "./Interfaces/Trait.ts":
/*!*****************************!*\
!*** ./Interfaces/Trait.ts ***!
\*****************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/***/ }),
/***/ "./Label.ts":
/*!******************!*\
!*** ./Label.ts ***!
\******************/
/*! exports provided: FontUnit, TextAlign, BaseAlign, FontStyle, LabelImpl, Label */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FontUnit", function() { return FontUnit; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextAlign", function() { return TextAlign; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BaseAlign", function() { return BaseAlign; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FontStyle", function() { return FontStyle; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LabelImpl", function() { return LabelImpl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Label", function() { return Label; });
/* harmony import */ var _Drawing_Color__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Drawing/Color */ "./Drawing/Color.ts");
/* harmony import */ var _Actor__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Actor */ "./Actor.ts");
/* harmony import */ var _Configurable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Configurable */ "./Configurable.ts");
/* harmony import */ var _Algebra__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Algebra */ "./Algebra.ts");
/* harmony import */ var _Collision_CollisionType__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Collision/CollisionType */ "./Collision/CollisionType.ts");
var __extends = (undefined && undefined.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
/**
* Enum representing the different font size units
* https://developer.mozilla.org/en-US/docs/Web/CSS/font-size
*/
var FontUnit;
(function (FontUnit) {
/**
* Em is a scalable unit, 1 em is equal to the current font size of the current element, parent elements can effect em values
*/
FontUnit[FontUnit["Em"] = 0] = "Em";
/**
* Rem is similar to the Em, it is a scalable unit. 1 rem is equal to the font size of the root element
*/
FontUnit[FontUnit["Rem"] = 1] = "Rem";
/**
* Pixel is a unit of length in screen pixels
*/
FontUnit[FontUnit["Px"] = 2] = "Px";
/**
* Point is a physical unit length (1/72 of an inch)
*/
FontUnit[FontUnit["Pt"] = 3] = "Pt";
/**
* Percent is a scalable unit similar to Em, the only difference is the Em units scale faster when Text-Size stuff
*/
FontUnit[FontUnit["Percent"] = 4] = "Percent";
})(FontUnit || (FontUnit = {}));
/**
* Enum representing the different horizontal text alignments
*/
var TextAlign;
(function (TextAlign) {
/**
* The text is left-aligned.
*/
TextAlign[TextAlign["Left"] = 0] = "Left";
/**
* The text is right-aligned.
*/
TextAlign[TextAlign["Right"] = 1] = "Right";
/**
* The text is centered.
*/
TextAlign[TextAlign["Center"] = 2] = "Center";
/**
* The text is aligned at the normal start of the line (left-aligned for left-to-right locales,
* right-aligned for right-to-left locales).
*/
TextAlign[TextAlign["Start"] = 3] = "Start";
/**
* The text is aligned at the normal end of the line (right-aligned for left-to-right locales,
* left-aligned for right-to-left locales).
*/
TextAlign[TextAlign["End"] = 4] = "End";
})(TextAlign || (TextAlign = {}));
/**
* Enum representing the different baseline text alignments
*/
var BaseAlign;
(function (BaseAlign) {
/**
* The text baseline is the top of the em square.
*/
BaseAlign[BaseAlign["Top"] = 0] = "Top";
/**
* The text baseline is the hanging baseline. Currently unsupported; this will act like
* alphabetic.
*/
BaseAlign[BaseAlign["Hanging"] = 1] = "Hanging";
/**
* The text baseline is the middle of the em square.
*/
BaseAlign[BaseAlign["Middle"] = 2] = "Middle";
/**
* The text baseline is the normal alphabetic baseline.
*/
BaseAlign[BaseAlign["Alphabetic"] = 3] = "Alphabetic";
/**
* The text baseline is the ideographic baseline; this is the bottom of
* the body of the characters, if the main body of characters protrudes
* beneath the alphabetic baseline. Currently unsupported; this will
* act like alphabetic.
*/
BaseAlign[BaseAlign["Ideographic"] = 4] = "Ideographic";
/**
* The text baseline is the bottom of the bounding box. This differs
* from the ideographic baseline in that the ideographic baseline
* doesn't consider descenders.
*/
BaseAlign[BaseAlign["Bottom"] = 5] = "Bottom";
})(BaseAlign || (BaseAlign = {}));
/**
* Enum representing the different possible font styles
*/
var FontStyle;
(function (FontStyle) {
FontStyle[FontStyle["Normal"] = 0] = "Normal";
FontStyle[FontStyle["Italic"] = 1] = "Italic";
FontStyle[FontStyle["Oblique"] = 2] = "Oblique";
})(FontStyle || (FontStyle = {}));
/**
* @hidden
*/
var LabelImpl = /** @class */ (function (_super) {
__extends(LabelImpl, _super);
/**
* @param text The text of the label
* @param x The x position of the label
* @param y The y position of the label
* @param fontFamily Use any valid CSS font string for the label's font. Web fonts are supported. Default is `10px sans-serif`.
* @param spriteFont Use an Excalibur sprite font for the label's font, if a SpriteFont is provided it will take precedence
* over a css font.
*/
function LabelImpl(textOrConfig, x, y, fontFamily, spriteFont) {
var _this = _super.call(this, textOrConfig && typeof textOrConfig === 'object' ? textOrConfig : { pos: new _Algebra__WEBPACK_IMPORTED_MODULE_3__["Vector"](x, y) }) || this;
/**
* Sets or gets the bold property of the label's text, by default it's false
*/
_this.bold = false;
/**
* The font size in the selected units, default is 10 (default units is pixel)
*/
_this.fontSize = 10;
/**
* The font style for this label, the default is [[FontStyle.Normal]]
*/
_this.fontStyle = FontStyle.Normal;
/**
* The css units for a font size such as px, pt, em (SpriteFont only support px), by default is 'px';
*/
_this.fontUnit = FontUnit.Px;
/**
* Gets or sets the horizontal text alignment property for the label.
*/
_this.textAlign = TextAlign.Left;
/**
* Gets or sets the baseline alignment property for the label.
*/
_this.baseAlign = BaseAlign.Bottom;
/**
* Gets or sets the letter spacing on a Label. Only supported with Sprite Fonts.
*/
_this.letterSpacing = 0; //px
/**
* Whether or not the [[SpriteFont]] will be case-sensitive when matching characters.
*/
_this.caseInsensitive = true;
var text = '';
if (textOrConfig && typeof textOrConfig === 'object') {
fontFamily = textOrConfig.fontFamily;
spriteFont = textOrConfig.spriteFont;
text = textOrConfig.text;
}
else {
text = textOrConfig;
}
_this.text = text || '';
_this.color = _Drawing_Color__WEBPACK_IMPORTED_MODULE_0__["Color"].Black;
_this.spriteFont = spriteFont;
_this.body.collider.type = _Collision_CollisionType__WEBPACK_IMPORTED_MODULE_4__["CollisionType"].PreventCollision;
_this.fontFamily = fontFamily || 'sans-serif'; // coalesce to default canvas font
_this._textShadowOn = false;
_this._shadowOffsetX = 0;
_this._shadowOffsetY = 0;
if (spriteFont) {
//this._textSprites = spriteFont.getTextSprites();
}
return _this;
}
/**
* Returns the width of the text in the label (in pixels);
* @param ctx Rendering context to measure the string with
*/
LabelImpl.prototype.getTextWidth = function (ctx) {
var oldFont = ctx.font;
ctx.font = this._fontString;
var width = ctx.measureText(this.text).width;
ctx.font = oldFont;
return width;
};
// TypeScript doesn't support string enums :(
LabelImpl.prototype._lookupFontUnit = function (fontUnit) {
switch (fontUnit) {
case FontUnit.Em:
return 'em';
case FontUnit.Rem:
return 'rem';
case FontUnit.Pt:
return 'pt';
case FontUnit.Px:
return 'px';
case FontUnit.Percent:
return '%';
default:
return 'px';
}
};
LabelImpl.prototype._lookupTextAlign = function (textAlign) {
switch (textAlign) {
case TextAlign.Left:
return 'left';
case TextAlign.Right:
return 'right';
case TextAlign.Center:
return 'center';
case TextAlign.End:
return 'end';
case TextAlign.Start:
return 'start';
default:
return 'start';
}
};
LabelImpl.prototype._lookupBaseAlign = function (baseAlign) {
switch (baseAlign) {
case BaseAlign.Alphabetic:
return 'alphabetic';
case BaseAlign.Bottom:
return 'bottom';
case BaseAlign.Hanging:
return 'hanging';
case BaseAlign.Ideographic:
return 'ideographic';
case BaseAlign.Middle:
return 'middle';
case BaseAlign.Top:
return 'top';
default:
return 'alphabetic';
}
};
LabelImpl.prototype._lookupFontStyle = function (fontStyle) {
var boldstring = this.bold ? ' bold' : '';
switch (fontStyle) {
case FontStyle.Italic:
return 'italic' + boldstring;
case FontStyle.Normal:
return 'normal' + boldstring;
case FontStyle.Oblique:
return 'oblique' + boldstring;
default:
return 'normal' + boldstring;
}
};
/**
* Sets the text shadow for sprite fonts
* @param offsetX The x offset in pixels to place the shadow
* @param offsetY The y offset in pixels to place the shadow
* @param shadowColor The color of the text shadow
*/
LabelImpl.prototype.setTextShadow = function (offsetX, offsetY, shadowColor) {
this.spriteFont.setTextShadow(offsetX, offsetY, shadowColor);
};
/**
* Toggles text shadows on or off, only applies when using sprite fonts
*/
LabelImpl.prototype.useTextShadow = function (on) {
this.spriteFont.useTextShadow(on);
};
/**
* Clears the current text shadow
*/
LabelImpl.prototype.clearTextShadow = function () {
this._textShadowOn = false;
this._shadowOffsetX = 0;
this._shadowOffsetY = 0;
};
LabelImpl.prototype.update = function (engine, delta) {
_super.prototype.update.call(this, engine, delta);
};
LabelImpl.prototype.draw = function (ctx, delta) {
ctx.save();
ctx.translate(this.pos.x, this.pos.y);
ctx.scale(this.scale.x, this.scale.y);
ctx.rotate(this.rotation);
if (this._textShadowOn) {
ctx.save();
ctx.translate(this._shadowOffsetX, this._shadowOffsetY);
this._fontDraw(ctx);
ctx.restore();
}
this._fontDraw(ctx);
_super.prototype.draw.call(this, ctx, delta);
ctx.restore();
};
LabelImpl.prototype._fontDraw = function (ctx) {
if (this.spriteFont) {
this.spriteFont.draw(ctx, this.text, 0, 0, {
color: this.color.clone(),
baseAlign: this.baseAlign,
textAlign: this.textAlign,
fontSize: this.fontSize,
letterSpacing: this.letterSpacing,
opacity: this.opacity
});
}
else {
var oldAlign = ctx.textAlign;
var oldTextBaseline = ctx.textBaseline;
ctx.textAlign = this._lookupTextAlign(this.textAlign);
ctx.textBaseline = this._lookupBaseAlign(this.baseAlign);
if (this.color) {
this.color.a = this.opacity;
}
ctx.fillStyle = this.color.toString();
ctx.font = this._fontString;
if (this.maxWidth) {
ctx.fillText(this.text, 0, 0, this.maxWidth);
}
else {
ctx.fillText(this.text, 0, 0);
}
ctx.textAlign = oldAlign;
ctx.textBaseline = oldTextBaseline;
}
};
Object.defineProperty(LabelImpl.prototype, "_fontString", {
get: function () {
return this._lookupFontStyle(this.fontStyle) + " " + this.fontSize + this._lookupFontUnit(this.fontUnit) + " " + this.fontFamily;
},
enumerable: false,
configurable: true
});
LabelImpl.prototype.debugDraw = function (ctx) {
_super.prototype.debugDraw.call(this, ctx);
};
return LabelImpl;
}(_Actor__WEBPACK_IMPORTED_MODULE_1__["Actor"]));
/**
* Labels are the way to draw small amounts of text to the screen. They are
* actors and inherit all of the benefits and capabilities.
*
* [[include:Labels.md]]
*/
var Label = /** @class */ (function (_super) {
__extends(Label, _super);
function Label(textOrConfig, x, y, fontFamily, spriteFont) {
return _super.call(this, textOrConfig, x, y, fontFamily, spriteFont) || this;
}
return Label;
}(Object(_Configurable__WEBPACK_IMPORTED_MODULE_2__["Configurable"])(LabelImpl)));
/***/ }),
/***/ "./Loader.css":
/*!********************!*\
!*** ./Loader.css ***!
\********************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../node_modules/css-loader/dist/runtime/api.js */ "../../node_modules/css-loader/dist/runtime/api.js");
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_0__);
// Imports
var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_0___default()(false);
// Module
___CSS_LOADER_EXPORT___.push([module.i, "/* Buttons styles start */\n\nbutton#excalibur-play {\n display: inline-block;\n position: relative;\n z-index: 999;\n border-radius: 6px;\n border: none;\n /*border: 3px solid;\n border-color: white;\n box-shadow: 0 0 10px #ccc;*/\n padding: 1rem 1.5rem 1rem 4rem;\n margin: 0;\n text-decoration: none;\n background: #00b233;\n color: #ffffff;\n font-family: sans-serif;\n font-size: 2rem;\n line-height: 1;\n cursor: pointer;\n text-align: center;\n transition: background 250ms ease-in-out, transform 150ms ease;\n -webkit-appearance: none;\n -moz-appearance: none;\n\n -webkit-animation: excalibur-button-fadein 200ms; /* Safari, Chrome and Opera > 12.1 */\n -moz-animation: excalibur-button-fadein 200ms; /* Firefox < 16 */\n -ms-animation: excalibur-button-fadein 200ms; /* Internet Explorer */\n -o-animation: excalibur-button-fadein 200ms; /* Opera < 12.1 */\n animation: excalibur-button-fadein 200ms;\n}\n\n/*\nbutton#excalibur-play {\n display: none;\n}*/\n\nbutton#excalibur-play:after {\n position: absolute;\n content: '';\n border: 8px solid;\n border-color: transparent transparent transparent white;\n left: 35px;\n top: 24px;\n width: 0;\n height: 0;\n}\n\nbutton#excalibur-play:before {\n position: absolute;\n content: '';\n border: 3px solid;\n left: 19px;\n top: 14px;\n border-radius: 20px;\n width: 30px;\n height: 30px;\n}\n\nbutton#excalibur-play:hover,\nbutton#excalibur-play:focus {\n background: #00982c;\n}\n\nbutton#excalibur-play:focus {\n outline: 1px solid #fff;\n outline-offset: -4px;\n}\n\nbutton#excalibur-play:active {\n transform: scale(0.99);\n}\n\n@keyframes excalibur-button-fadein {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n\n/* Firefox < 16 */\n@-moz-keyframes excalibur-button-fadein {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n\n/* Safari, Chrome and Opera > 12.1 */\n@-webkit-keyframes excalibur-button-fadein {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n\n/* Internet Explorer */\n@-ms-keyframes excalibur-button-fadein {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n\n/* Opera < 12.1 */\n@-o-keyframes excalibur-button-fadein {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n", ""]);
// Exports
/* harmony default export */ __webpack_exports__["default"] = (___CSS_LOADER_EXPORT___);
/***/ }),
/***/ "./Loader.logo.png":
/*!*************************!*\
!*** ./Loader.logo.png ***!
\*************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony default export */ __webpack_exports__["default"] = ("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAdQAAAB2CAYAAABxhGI9AAAACXBIWXMAAAsSAAALEgHS3X78AAAKnUlEQVR42u3dP2wjSx0H8N8hJIonIRmJjsq0SBR+BQ1dcqKhe0lD77SvSwpKkJKGPulpktfRIMUdEqKIqV57rpAokM4dbSiyq7ONPTP7x39ifz7SFbnEnp3xer47O7uzH15fXwMA6OYHmgAABCoACFQAEKgAgEAFAIEKAAIVAAQqACBQAUCgAoBABQCBCgAIVAAQqAAgUAFAoAIAAhUABCoACFQAEKgAgECFLbmOiNeFf2PbAyz68Pr6qhUgbRwR92v+/zwiJrYHMEKFMmcN///UtgcQqFBk1PD/97U9Qx8VCFSgu4EmAIEKAAIVAAQqACBQ4Z25jojP8eX+0WtNAgIVaOY+Im5j+eKh24h41jQgUIEyZ7F5NaPU7wCBCiwYd/w9cOB+qAlgJ3KLLow0EV198803RWvJfvfddx+0lhEqHKu5JgAjVCBvlhmFzjQRXUekHz9+TP79y8uLRjNChXfvoePvAYEKxNtj1e42/O5JoIJABcrdRMRVLM+X3kTEpaaB988cKuzWg9EobTWdMx0Oly8uN4dqhAoARqgnaN3arHfqu7OyH8ItKLVB/P+CEfMTHyGPY3npx1m8zWGDEeoBfUk/xdti57dr/r1Wv2+6EPow3tZ5rRdS72s1neuF97xvWd+XTH0/V+UMttDWqbI/r2nrxfp+jv2uSjSO7S+OXy/A/3lN+9xX5T5HxEUPZZ0tfB71+w57eJ/HFu+z+jkv1u92YX9fbI/HhX3JA9rp5MPr66tWaG9UfUGbrHIzi7cLUyYFf/tpTady03EEeL8mUJ6i7MKYNvWNqr4Pe2jradXO60LrvPAz2PQ5RPX684ah8dxD+2zantnCgVipSVV+m/tgB9W2DDq2Sx/vM95wcHhZhWVJm8yrv58cSgfTdc70+++/X/r522+/tUKSEepBqo+om4ZLPerMjUwuNnQCtx1GWJtee1FwdD5uWd86xLs8UaVt2aNEO1/saZ/Z5rYMW4zq6v34rGV9Bg3q2eZ9SkeNm9qwyUh30OPIHYFKx5FG03C7znSOqYBq+qW/zpQ3anH037TNHluG6f0WPsPhHvab4QFty7ogOeuxDYcNy2/zu2214WNYWxmBurNO8bGn97pNBOO8xy/9uCorZZ4I2r4C7aJgO7ZV9iE49Dm6NvOWx+pWE9CUq3zbdTp9doz38TbXtzqH9RT5CyWe422OaZoZGeZCabrhPQY9HjwsjpTvCg4YtlE2+Ta/j2bzn8fqrDqgm+6yUHOmAvWUjAtGhbNYvsBknDnqH1Qhc7VmxHgeb/NbudA5j/UXlYwif2p6luhAc9teu1npiHKnDs8if6tCm7JLX3NKpgttXe9ruc9mHMd7a83iwdxF5vt8tutARaCeklRnNK9C8WnNF7geJQ4T4XG3JhSnVdilQrG+yOnrlVHfsEGYzhNBn7Lu6tS7+HJafJQ4EMiNlNqWXZ9WPvVgnVYHG5M1ByDXkT6leX2EgTqJtyt45yv7S2qO3sEZjZhDLXeR+YKdJ0Zdk8QocvH9N732KrNtq+FZ/zzIHABcJrYpd+Xv14lOd5ap76SgrduW/VTQ1qcQpqnbgu4ifZvUMNpd9XuoZmvCtPaQ2Y/BCHVLgbrJTeRPDdVf6pfMKDU2fOkHmVFFfXr3MsouLsnNvV5kRoe5+s431PeuoKPqWnaurY/ZPBEeqwceN4l96iwO6H7Mjq4y7VGPVNe10VaZMzVCPVWpI/Z6FZbcv5fMqGCU+dLfFGzj58jP8+bCdJCo7yzKTwdOF0bu9Ug7V4c+yz7FJfYeGoysUss0HssIdVZwYLDujMqlESoCdTtGsZtbHnJBeNdDSJSs0jTKdMJN1HNX54Wv7bvsU9NkVJVa13dX+/wuArV0X/l5RHyo/lnfF4G6p6DrS0kHdtXhy35TGErDPYZUn2WfWqDOo/lVqdMD2O/hKJhD7S/odukymq9s02QN4EEPR/zbaOumZc+r15zK1Zqznl9jsfiemTM1QmV3HUuTkedlg9HIQzRbUD93dfC+2tpj2fIHEH2+RqCCQH13gZq7hWXTNpVu19OB1fc9nQ0AKOKUb5lU0P1kDyOneoWk0lOZ9cIP0x7qu8+2BhCoR2wYu1+e7DmaXzBSsu5vaX1ne2zrpmUPTmxf7PM1Dm4y/vC7ny7Nif7+z/9ZmtM0Z3panPLtPmra9f16bcK0Dpbnwk43Vd/RHtu6zfNQTy1QBy3aqG2g9nVmxml+BOoJyT3NpWmn9xhfFnu4bvDa+44BXhqqfdf3uUF9+yz77AT31Yue2mjecYQ62NLfgkA9ghHqLNEhNem4H1c6vdyDxhf/bpz5m4coW/c39wi6VH2bPtHlcaV9cvXts+zxCe6rTeqc2ndL7uGd93QwM9bFcAzMoZZ7SgTBbWx+asui61h/iq1+RmjqdbnQXQ3T1DNQ63V/U9ucqm/pMzPb1rePsk/1iTOjgvatR4W3Lc8ULB78pELyrnAfeTcj1NU509/86mfJ33/8+Mf00a05UyPUEw7UVCeWG/WNEiExyHRMt5ltW30izUPk18ytt7lNfc8i//DvtvXto+ySA5BjljsLUF8lPkqMPEtW1JomDsiGBZ9Byb4NAvUITSN9GuwsIj6t6UTOqk7jJREkmzqli8xIs96udSO20sX0H1vW92IL9e1a9rgqVyf91gbPsTy9UD9n9lOkT8k+RfkFR5PMNqxOcdSf32PBvg3vilO+zdxE+okx9Wm0ph36XYsRZCpMF993GOk5qvqB3Dct6jvssb67KvuUNJ3frw92bhr8/STSF0JdRPMLpUCgnsgo9S76PZ246ZFk1wWvK5m3vVoYvW1Sz7nN91jfXbQ1ZQc7TW6HeaoOalypG/8/p/rP1aNAc6ZHzSnfdqPUPhdy2PQw6Nz9gSVhuhiqueUHR3uu7y7K3rdDX4u46ZrPbUa0IFBZ0seKQ3XQTRt2vm3W/a2DbNKys++rvm3ep6+y1x2UdP3bWU9lzra47U1GmlctX/sQ23t+aOlByLTh/4NAPaCRxtcdO5HLSJ/6vNtCwGx67VPmPbvWd1q9frKHtp4kAqRJ2HR9j762JfX3bZ//elPtj13PPDx1+D5tqk/Xi6NO8SHz7MmH19dXrdBNfVFP6T2PT1UHNit87/t4m5+aRH+nQBdvqyhZDKJLfZs8h7XPsqdV2ZOV+tanKB8aln0dyxdAXbV4j4gvt4oMOrbP6vbU73NW7TMlbdTnPrWpfqXfh9HKZ9vke7KuTeZRNtXRSe6+1FV//ce/ln5eXfsXgcqXzr6+9261M3moOoa7E6nvTZTfy7iNsmfb7kjfgXGsvxe0vihsEts9HTquPpt1q1vtahu2TqAiUAEEKj0zhwoARqgAu/OnX/442WH+9xc/Wvr58re/Tr7f41/+ZsRqhAoACFQAEKgAcHjMoQJskJsz/eqrr5Z+vvr7v5fmQFevAl5lztQIFQAQqAAgUAHgIJlDBdhgdQ41N2eKESoAIFABQKACwFEwhwoARqgAIFABQKACAAIVAAQqAAhUABCoAIBABQCBCgACFQAEKgAgUAFAoAKAQAUAgQoACFQAEKgAIFABQKACAAIVAAQqAAhUABCoAIBABQCBCgACFQAQqAAgUAFAoAKAQAUAlvwPcFDns1DsH4sAAAAASUVORK5CYII=");
/***/ }),
/***/ "./Loader.ts":
/*!*******************!*\
!*** ./Loader.ts ***!
\*******************/
/*! exports provided: Loader */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Loader", function() { return Loader; });
/* harmony import */ var _Drawing_Color__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Drawing/Color */ "./Drawing/Color.ts");
/* harmony import */ var _Util_WebAudio__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Util/WebAudio */ "./Util/WebAudio.ts");
/* harmony import */ var _Util_Log__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Util/Log */ "./Util/Log.ts");
/* harmony import */ var _Promises__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Promises */ "./Promises.ts");
/* harmony import */ var _Class__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Class */ "./Class.ts");
/* harmony import */ var _Util_DrawUtil__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Util/DrawUtil */ "./Util/DrawUtil.ts");
/* harmony import */ var _Loader_logo_png__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Loader.logo.png */ "./Loader.logo.png");
/* harmony import */ var _Loader_css__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Loader.css */ "./Loader.css");
var __extends = (undefined && undefined.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
/**
* Pre-loading assets
*
* The loader provides a mechanism to preload multiple resources at
* one time. The loader must be passed to the engine in order to
* trigger the loading progress bar.
*
* The [[Loader]] itself implements [[Loadable]] so you can load loaders.
*
* ## Example: Pre-loading resources for a game
*
* ```js
* // create a loader
* var loader = new ex.Loader();
*
* // create a resource dictionary (best practice is to keep a separate file)
* var resources = {
* TextureGround: new ex.Texture("/images/textures/ground.png"),
* SoundDeath: new ex.Sound("/sound/death.wav", "/sound/death.mp3")
* };
*
* // loop through dictionary and add to loader
* for (var loadable in resources) {
* if (resources.hasOwnProperty(loadable)) {
* loader.addResource(resources[loadable]);
* }
* }
*
* // start game
* game.start(loader).then(function () {
* console.log("Game started!");
* });
* ```
*
* ## Customize the Loader
*
* The loader can be customized to show different, text, logo, background color, and button.
*
* ```typescript
* const loader = new ex.Loader([playerTexture]);
*
* // The loaders button text can simply modified using this
* loader.playButtonText = 'Start the best game ever';
*
* // The logo can be changed by inserting a base64 image string here
*
* loader.logo = 'data:image/png;base64,iVBORw...';
* loader.logoWidth = 15;
* loader.logoHeight = 14;
*
* // The background color can be changed like so by supplying a valid CSS color string
*
* loader.backgroundColor = 'red'
* loader.backgroundColor = '#176BAA'
*
* // To build a completely new button
* loader.startButtonFactory = () => {
* let myButton = document.createElement('button');
* myButton.textContent = 'The best button';
* return myButton;
* };
*
* engine.start(loader).then(() => {});
* ```
*/
var Loader = /** @class */ (function (_super) {
__extends(Loader, _super);
/**
* @param loadables Optionally provide the list of resources you want to load at constructor time
*/
function Loader(loadables) {
var _this = _super.call(this) || this;
_this._resourceList = [];
_this._index = 0;
_this._playButtonShown = false;
_this._resourceCount = 0;
_this._numLoaded = 0;
_this._progressCounts = {};
_this._totalCounts = {};
// logo drawing stuff
// base64 string encoding of the excalibur logo (logo-white.png)
_this.logo = _Loader_logo_png__WEBPACK_IMPORTED_MODULE_6__["default"];
_this.logoWidth = 468;
_this.logoHeight = 118;
/**
* Gets or sets the color of the loading bar, default is [[Color.White]]
*/
_this.loadingBarColor = _Drawing_Color__WEBPACK_IMPORTED_MODULE_0__["Color"].White;
/**
* Gets or sets the background color of the loader as a hex string
*/
_this.backgroundColor = '#176BAA';
_this.suppressPlayButton = false;
/** Loads the css from Loader.css */
_this._playButtonStyles = _Loader_css__WEBPACK_IMPORTED_MODULE_7__["default"].toString();
/**
* Get/set play button text
*/
_this.playButtonText = 'Play game';
/**
* Return a html button element for excalibur to use as a play button
*/
_this.startButtonFactory = function () {
var buttonElement = document.createElement('button');
buttonElement.id = 'excalibur-play';
buttonElement.textContent = _this.playButtonText;
buttonElement.style.display = 'none';
return buttonElement;
};
_this.getData = function () {
return;
};
_this.setData = function () {
return;
};
_this.processData = function () {
return;
};
_this.onprogress = function (e) {
_Util_Log__WEBPACK_IMPORTED_MODULE_2__["Logger"].getInstance().debug('[ex.Loader] Loading ' + ((100 * e.loaded) / e.total).toFixed(0));
return;
};
_this.oncomplete = function () {
return;
};
_this.onerror = function () {
return;
};
if (loadables) {
_this.addResources(loadables);
}
return _this;
}
Object.defineProperty(Loader.prototype, "_image", {
get: function () {
if (!this._imageElement) {
this._imageElement = new Image();
this._imageElement.src = this.logo;
}
return this._imageElement;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Loader.prototype, "playButtonRootElement", {
get: function () {
return this._playButtonRootElement;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Loader.prototype, "playButtonElement", {
get: function () {
return this._playButtonElement;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Loader.prototype, "_playButton", {
get: function () {
if (!this._playButtonRootElement) {
this._playButtonRootElement = document.createElement('div');
this._playButtonRootElement.id = 'excalibur-play-root';
this._playButtonRootElement.style.position = 'absolute';
document.body.appendChild(this._playButtonRootElement);
}
if (!this._styleBlock) {
this._styleBlock = document.createElement('style');
this._styleBlock.textContent = this._playButtonStyles;
document.head.appendChild(this._styleBlock);
}
if (!this._playButtonElement) {
this._playButtonElement = this.startButtonFactory();
this._playButtonRootElement.appendChild(this._playButtonElement);
}
return this._playButtonElement;
},
enumerable: false,
configurable: true
});
Loader.prototype.wireEngine = function (engine) {
this._engine = engine;
};
/**
* Add a resource to the loader to load
* @param loadable Resource to add
*/
Loader.prototype.addResource = function (loadable) {
var key = this._index++;
this._resourceList.push(loadable);
this._progressCounts[key] = 0;
this._totalCounts[key] = 1;
this._resourceCount++;
};
/**
* Add a list of resources to the loader to load
* @param loadables The list of resources to load
*/
Loader.prototype.addResources = function (loadables) {
var i = 0;
var len = loadables.length;
for (i; i < len; i++) {
this.addResource(loadables[i]);
}
};
/**
* Returns true if the loader has completely loaded all resources
*/
Loader.prototype.isLoaded = function () {
return this._numLoaded === this._resourceCount;
};
/**
* Shows the play button and returns a promise that resolves when clicked
*/
Loader.prototype.showPlayButton = function () {
if (this.suppressPlayButton) {
return _Promises__WEBPACK_IMPORTED_MODULE_3__["Promise"].resolve();
}
else {
this._playButtonShown = true;
this._playButton.style.display = 'block';
var promise_1 = new _Promises__WEBPACK_IMPORTED_MODULE_3__["Promise"]();
this._playButton.addEventListener('click', function () { return (promise_1.state() === _Promises__WEBPACK_IMPORTED_MODULE_3__["PromiseState"].Pending ? promise_1.resolve() : promise_1); });
this._playButton.addEventListener('touchend', function () { return (promise_1.state() === _Promises__WEBPACK_IMPORTED_MODULE_3__["PromiseState"].Pending ? promise_1.resolve() : promise_1); });
this._playButton.addEventListener('pointerup', function () { return (promise_1.state() === _Promises__WEBPACK_IMPORTED_MODULE_3__["PromiseState"].Pending ? promise_1.resolve() : promise_1); });
return promise_1;
}
};
Loader.prototype.hidePlayButton = function () {
this._playButtonShown = false;
this._playButton.style.display = 'none';
};
/**
* Clean up generated elements for the loader
*/
Loader.prototype.dispose = function () {
if (this._playButtonRootElement.parentElement) {
this._playButtonRootElement.removeChild(this._playButtonElement);
document.body.removeChild(this._playButtonRootElement);
document.head.removeChild(this._styleBlock);
this._playButtonRootElement = null;
this._playButtonElement = null;
this._styleBlock = null;
}
};
/**
* Begin loading all of the supplied resources, returning a promise
* that resolves when loading of all is complete
*/
Loader.prototype.load = function () {
var _this = this;
var complete = new _Promises__WEBPACK_IMPORTED_MODULE_3__["Promise"]();
if (this._resourceList.length === 0) {
this.showPlayButton().then(function () {
// Unlock audio context in chrome after user gesture
// https://github.com/excaliburjs/Excalibur/issues/262
// https://github.com/excaliburjs/Excalibur/issues/1031
_Util_WebAudio__WEBPACK_IMPORTED_MODULE_1__["WebAudio"].unlock().then(function () {
_this.hidePlayButton();
_this.oncomplete.call(_this);
complete.resolve();
_this.dispose();
});
});
return complete;
}
this._resourceList.forEach(function (resource) {
if (_this._engine) {
resource.wireEngine(_this._engine);
}
resource.onprogress = function (e) {
_this.updateResourceProgress(e.loaded, e.total);
};
resource.oncomplete = resource.onerror = function () {
_this.markResourceComplete();
if (_this.isLoaded()) {
setTimeout(function () {
_this.showPlayButton().then(function () {
// Unlock audio context in chrome after user gesture
// https://github.com/excaliburjs/Excalibur/issues/262
// https://github.com/excaliburjs/Excalibur/issues/1031
_Util_WebAudio__WEBPACK_IMPORTED_MODULE_1__["WebAudio"].unlock().then(function () {
_this.hidePlayButton();
_this.oncomplete.call(_this);
complete.resolve();
_this.dispose();
});
});
}, 200); // short delay in showing the button for aesthetics
}
};
});
function loadNext(list, index) {
if (!list[index]) {
return;
}
list[index].load().then(function () {
loadNext(list, index + 1);
});
}
loadNext(this._resourceList, 0);
return complete;
};
Loader.prototype.updateResourceProgress = function (loadedBytes, totalBytes) {
var chunkSize = 100 / this._resourceCount;
var resourceProgress = loadedBytes / totalBytes;
// This only works if we load 1 resource at a time
var totalProgress = resourceProgress * chunkSize + this.progress * 100;
this.onprogress({ loaded: totalProgress, total: 100 });
};
Loader.prototype.markResourceComplete = function () {
this._numLoaded++;
};
Object.defineProperty(Loader.prototype, "progress", {
/**
* Returns the progess of the loader as a number between [0, 1] inclusive.
*/
get: function () {
return this._resourceCount > 0 ? this._numLoaded / this._resourceCount : 1;
},
enumerable: false,
configurable: true
});
/**
* Loader draw function. Draws the default Excalibur loading screen.
* Override `logo`, `logoWidth`, `logoHeight` and `backgroundColor` properties
* to customize the drawing, or just override entire method.
*/
Loader.prototype.draw = function (ctx) {
var canvasHeight = this._engine.canvasHeight / this._engine.pixelRatio;
var canvasWidth = this._engine.canvasWidth / this._engine.pixelRatio;
if (this._playButtonRootElement) {
var left = ctx.canvas.offsetLeft;
var top_1 = ctx.canvas.offsetTop;
var buttonWidth = this._playButton.clientWidth;
var buttonHeight = this._playButton.clientHeight;
if (this.playButtonPosition) {
this._playButtonRootElement.style.left = this.playButtonPosition.x + "px";
this._playButtonRootElement.style.top = this.playButtonPosition.y + "px";
}
else {
this._playButtonRootElement.style.left = left + canvasWidth / 2 - buttonWidth / 2 + "px";
this._playButtonRootElement.style.top = top_1 + canvasHeight / 2 - buttonHeight / 2 + 100 + "px";
}
}
ctx.fillStyle = this.backgroundColor;
ctx.fillRect(0, 0, canvasWidth, canvasHeight);
var logoY = canvasHeight / 2;
var width = Math.min(this.logoWidth, canvasWidth * 0.75);
var logoX = canvasWidth / 2 - width / 2;
if (this.logoPosition) {
logoX = this.logoPosition.x;
logoY = this.logoPosition.y;
}
var imageHeight = Math.floor(width * (this.logoHeight / this.logoWidth)); // OG height/width factor
var oldAntialias = this._engine.getAntialiasing();
this._engine.setAntialiasing(true);
if (!this.logoPosition) {
ctx.drawImage(this._image, 0, 0, this.logoWidth, this.logoHeight, logoX, logoY - imageHeight - 20, width, imageHeight);
}
else {
ctx.drawImage(this._image, 0, 0, this.logoWidth, this.logoHeight, logoX, logoY, width, imageHeight);
}
// loading box
if (!this.suppressPlayButton && this._playButtonShown) {
this._engine.setAntialiasing(oldAntialias);
return;
}
var loadingX = logoX;
var loadingY = logoY;
if (this.loadingBarPosition) {
loadingX = this.loadingBarPosition.x;
loadingY = this.loadingBarPosition.y;
}
ctx.lineWidth = 2;
_Util_DrawUtil__WEBPACK_IMPORTED_MODULE_5__["roundRect"](ctx, loadingX, loadingY, width, 20, 10, this.loadingBarColor);
var progress = width * this.progress;
var margin = 5;
var progressWidth = progress - margin * 2;
var height = 20 - margin * 2;
_Util_DrawUtil__WEBPACK_IMPORTED_MODULE_5__["roundRect"](ctx, loadingX + margin, loadingY + margin, progressWidth > 10 ? progressWidth : 10, height, 5, null, this.loadingBarColor);
this._engine.setAntialiasing(oldAntialias);
};
/**
* Perform any calculations or logic in the `update` method. The default `Loader` does not
* do anything in this method so it is safe to override.
*/
Loader.prototype.update = function (_engine, _delta) {
// overridable update
};
return Loader;
}(_Class__WEBPACK_IMPORTED_MODULE_4__["Class"]));
/***/ }),
/***/ "./Math/Index.ts":
/*!***********************!*\
!*** ./Math/Index.ts ***!
\***********************/
/*! exports provided: PerlinGenerator, PerlinDrawer2D, Random */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _PerlinNoise__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./PerlinNoise */ "./Math/PerlinNoise.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PerlinGenerator", function() { return _PerlinNoise__WEBPACK_IMPORTED_MODULE_0__["PerlinGenerator"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PerlinDrawer2D", function() { return _PerlinNoise__WEBPACK_IMPORTED_MODULE_0__["PerlinDrawer2D"]; });
/* harmony import */ var _Random__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Random */ "./Math/Random.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Random", function() { return _Random__WEBPACK_IMPORTED_MODULE_1__["Random"]; });
/***/ }),
/***/ "./Math/PerlinNoise.ts":
/*!*****************************!*\
!*** ./Math/PerlinNoise.ts ***!
\*****************************/
/*! exports provided: PerlinGenerator, PerlinDrawer2D */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PerlinGenerator", function() { return PerlinGenerator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PerlinDrawer2D", function() { return PerlinDrawer2D; });
/* harmony import */ var _Random__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Random */ "./Math/Random.ts");
/* harmony import */ var _Drawing_Color__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Drawing/Color */ "./Drawing/Color.ts");
/* harmony import */ var _Util_Util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Util/Util */ "./Util/Util.ts");
function _lerp(time, a, b) {
return a + time * (b - a);
}
function _fade(t) {
return t * t * t * (t * (t * 6 - 15) + 10);
}
/**
* Generates perlin noise based on the 2002 Siggraph paper http://mrl.nyu.edu/~perlin/noise/
* Also https://flafla2.github.io/2014/08/09/perlinnoise.html
*/
var PerlinGenerator = /** @class */ (function () {
function PerlinGenerator(options) {
this._perm = [
151,
160,
137,
91,
90,
15,
131,
13,
201,
95,
96,
53,
194,
233,
7,
225,
140,
36,
103,
30,
69,
142,
8,
99,
37,
240,
21,
10,
23,
190,
6,
148,
247,
120,
234,
75,
0,
26,
197,
62,
94,
252,
219,
203,
117,
35,
11,
32,
57,
177,
33,
88,
237,
149,
56,
87,
174,
20,
125,
136,
171,
168,
68,
175,
74,
165,
71,
134,
139,
48,
27,
166,
77,
146,
158,
231,
83,
111,
229,
122,
60,
211,
133,
230,
220,
105,
92,
41,
55,
46,
245,
40,
244,
102,
143,
54,
65,
25,
63,
161,
1,
216,
80,
73,
209,
76,
132,
187,
208,
89,
18,
169,
200,
196,
135,
130,
116,
188,
159,
86,
164,
100,
109,
198,
173,
186,
3,
64,
52,
217,
226,
250,
124,
123,
5,
202,
38,
147,
118,
126,
255,
82,
85,
212,
207,
206,
59,
227,
47,
16,
58,
17,
182,
189,
28,
42,
223,
183,
170,
213,
119,
248,
152,
2,
44,
154,
163,
70,
221,
153,
101,
155,
167,
43,
172,
9,
129,
22,
39,
253,
19,
98,
108,
110,
79,
113,
224,
232,
178,
185,
112,
104,
218,
246,
97,
228,
251,
34,
242,
193,
238,
210,
144,
12,
191,
179,
162,
241,
81,
51,
145,
235,
249,
14,
239,
107,
49,
192,
214,
31,
181,
199,
106,
157,
184,
84,
204,
176,
115,
121,
50,
45,
127,
4,
150,
254,
138,
236,
205,
93,
222,
114,
67,
29,
24,
72,
243,
141,
128,
195,
78,
66,
215,
61,
156,
180
];
this._p = new Uint8Array(512);
this._defaultPerlinOptions = {
octaves: 1,
frequency: 1,
amplitude: 1,
persistance: 0.5
};
options = _Util_Util__WEBPACK_IMPORTED_MODULE_2__["extend"]({}, this._defaultPerlinOptions, options);
this.persistance = options.persistance;
this.amplitude = options.amplitude;
this.frequency = options.frequency;
this.octaves = options.octaves;
if (options.seed) {
this._random = new _Random__WEBPACK_IMPORTED_MODULE_0__["Random"](options.seed);
}
else {
this._random = new _Random__WEBPACK_IMPORTED_MODULE_0__["Random"]();
}
this._perm = this._random.shuffle(this._perm);
for (var i = 0; i < 512; i++) {
this._p[i] = this._perm[i % 256] & 0xff;
}
}
PerlinGenerator.prototype.noise = function () {
var amp = this.amplitude;
var freq = this.frequency;
var total = 0;
var maxValue = 0;
for (var i = 0; i < this.octaves; i++) {
switch (arguments.length) {
case 1:
total += this._noise1d(arguments[0] * freq) * amp;
break;
case 2:
total += this._noise2d(arguments[0] * freq, arguments[1] * freq) * amp;
break;
case 3:
total += this._noise3d(arguments[0] * freq, arguments[1] * freq, arguments[2] * freq) * amp;
break;
/* istanbul ignore next */
default:
throw new Error('Invalid arguments for perlin noise');
}
maxValue += amp;
amp *= this.persistance;
freq *= 2;
}
return total / maxValue;
};
/**
* Generates a list starting at 0 and ending at 1 of continuous perlin noise, by default the step is 1/length;
*
*/
PerlinGenerator.prototype.sequence = function (length, step) {
if (!step) {
step = 1 / length;
}
var array = new Array(length);
for (var i = 0; i < length; i++) {
array[i] = this.noise(i * step);
}
return array;
};
/**
* Generates a 2D grid of perlin noise given a step value packed into a 1D array i = (x + y*width),
* by default the step will 1/(min(dimension))
*/
PerlinGenerator.prototype.grid = function (width, height, step) {
if (!step) {
step = 1 / Math.min(width, height);
}
var array = new Array(width * height);
for (var y = 0; y < height; y++) {
for (var x = 0; x < width; x++) {
array[x + y * width] = this.noise(x * step, y * step);
}
}
return array;
};
PerlinGenerator.prototype._gradient3d = function (hash, x, y, z) {
var h = hash & 0xf;
var u = h < 8 ? x : y;
var v = h < 4 ? y : h === 12 || h === 14 ? x : z;
return ((h & 1) === 0 ? u : -u) + ((h & 2) === 0 ? v : -v);
};
PerlinGenerator.prototype._gradient2d = function (hash, x, y) {
var value = (hash & 1) === 0 ? x : y;
return (hash & 2) === 0 ? -value : value;
};
PerlinGenerator.prototype._gradient1d = function (hash, x) {
return (hash & 1) === 0 ? -x : x;
};
PerlinGenerator.prototype._noise1d = function (x) {
var intX = Math.floor(x) & 0xff; // force 0-255 integers to lookup in permutation
x -= Math.floor(x);
var fadeX = _fade(x);
return (_lerp(fadeX, this._gradient1d(this._p[intX], x), this._gradient1d(this._p[intX + 1], x - 1)) + 1) / 2;
};
PerlinGenerator.prototype._noise2d = function (x, y) {
var intX = Math.floor(x) & 0xff;
var intY = Math.floor(y) & 0xff;
x -= Math.floor(x);
y -= Math.floor(y);
var fadeX = _fade(x);
var fadeY = _fade(y);
var a = this._p[intX] + intY;
var b = this._p[intX + 1] + intY;
return ((_lerp(fadeY, _lerp(fadeX, this._gradient2d(this._p[a], x, y), this._gradient2d(this._p[b], x - 1, y)), _lerp(fadeX, this._gradient2d(this._p[a + 1], x, y - 1), this._gradient2d(this._p[b + 1], x - 1, y - 1))) +
1) /
2);
};
PerlinGenerator.prototype._noise3d = function (x, y, z) {
var intX = Math.floor(x) & 0xff;
var intY = Math.floor(y) & 0xff;
var intZ = Math.floor(z) & 0xff;
x -= Math.floor(x);
y -= Math.floor(y);
z -= Math.floor(z);
var fadeX = _fade(x);
var fadeY = _fade(y);
var fadeZ = _fade(z);
var a = this._p[intX] + intY;
var b = this._p[intX + 1] + intY;
var aa = this._p[a] + intZ;
var ba = this._p[b] + intZ;
var ab = this._p[a + 1] + intZ;
var bb = this._p[b + 1] + intZ;
return ((_lerp(fadeZ, _lerp(fadeY, _lerp(fadeX, this._gradient3d(this._p[aa], x, y, z), this._gradient3d(this._p[ba], x - 1, y, z)), _lerp(fadeX, this._gradient3d(this._p[ab], x, y - 1, z), this._gradient3d(this._p[bb], x - 1, y - 1, z))), _lerp(fadeY, _lerp(fadeX, this._gradient3d(this._p[aa + 1], x, y, z - 1), this._gradient3d(this._p[ba + 1], x - 1, y, z - 1)), _lerp(fadeX, this._gradient3d(this._p[ab + 1], x, y - 1, z - 1), this._gradient3d(this._p[bb + 1], x - 1, y - 1, z - 1)))) +
1) /
2);
};
return PerlinGenerator;
}());
/**
* A helper to draw 2D perlin maps given a perlin generator and a function
*/
var PerlinDrawer2D = /** @class */ (function () {
/**
* @param generator - An existing perlin generator
* @param colorFcn - A color function that takes a value between [0, 255] derived from the perlin generator, and returns a color
*/
function PerlinDrawer2D(generator, colorFcn) {
this.generator = generator;
this.colorFcn = colorFcn;
if (!colorFcn) {
this.colorFcn = function (val) {
return val < 125 ? _Drawing_Color__WEBPACK_IMPORTED_MODULE_1__["Color"].Black : _Drawing_Color__WEBPACK_IMPORTED_MODULE_1__["Color"].White;
};
}
}
/**
* Returns an image of 2D perlin noise
*/
PerlinDrawer2D.prototype.image = function (width, height) {
var image = document.createElement('img');
var canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext('2d');
this.draw(ctx, 0, 0, width, height);
image.src = canvas.toDataURL();
return image;
};
/**
* This draws a 2D perlin grid on a canvas context, not recommended to be called every frame due to performance
*/
PerlinDrawer2D.prototype.draw = function (ctx, x, y, width, height) {
var grid = this.generator.grid(width, height);
var imageData = ctx.getImageData(x, y, width, height);
for (var j = 0; j < height; j++) {
for (var i = 0; i < width; i++) {
var val = grid[i + width * j];
var c = Math.floor(val * 255) & 0xff;
var pixel = (i + j * imageData.width) * 4;
var color = this.colorFcn(c);
imageData.data[pixel] = color.r;
imageData.data[pixel + 1] = color.g;
imageData.data[pixel + 2] = color.b;
imageData.data[pixel + 3] = Math.floor(color.a * 255);
}
}
ctx.putImageData(imageData, x, y);
};
return PerlinDrawer2D;
}());
/***/ }),
/***/ "./Math/Random.ts":
/*!************************!*\
!*** ./Math/Random.ts ***!
\************************/
/*! exports provided: Random */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Random", function() { return Random; });
/**
* Pseudo-Random Utility
*
* A pseudo-random utility to add seeded random support for help in
* generating things like terrain or reproducible randomness. Uses the
* [Mersenne Twister](https://en.wikipedia.org/wiki/Mersenne_Twister) algorithm.
*
* [[include:Random.md]]
*/
/**
* 32-bit mask
*/
var BITMASK32 = 0xffffffff;
/**
* Pseudo-random number generator following the Mersenne_Twister algorithm. Given a seed this generator will produce the same sequence
* of numbers each time it is called.
* See https://en.wikipedia.org/wiki/Mersenne_Twister for more details.
* Uses the MT19937-32 (2002) implementation documented here http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/emt19937ar.html
*
* Api inspired by http://chancejs.com/# https://github.com/chancejs/chancejs
*/
var Random = /** @class */ (function () {
/**
* If no seed is specified, the Date.now() is used
*/
function Random(seed) {
this.seed = seed;
// Separation point of one one word, the number of bits in the lower bitmask 0 <= r <= w-1
this._lowerMask = 0x7fffffff; // 31 bits same as _r
this._upperMask = 0x80000000; // 34 high bits
// Word size, 64 bits
this._w = 32;
// Degree of recurrence
this._n = 624;
// Middle word, an offset used in the recurrence defining the series x, 1<=m<n
this._m = 397;
// coefficients of teh rational normal form twist matrix
this._a = 0x9908b0df;
// tempering bit shifts and masks
this._u = 11;
this._s = 7;
this._b = 0x9d2c5680;
this._t = 15;
this._c = 0xefc60000;
this._l = 18;
this._f = 1812433253;
this._mt = new Array(this._n);
// need to mask to support higher bit machines
this._mt[0] = (seed || Date.now()) >>> 0;
for (var i = 1; i < this._n; i++) {
var s = this._mt[i - 1] ^ (this._mt[i - 1] >>> (this._w - 2));
// numbers are bigger than the JS max safe int, add in 16-bit chunks to prevent IEEE rounding errors on high bits
this._mt[i] = (((this._f * ((s & 0xffff0000) >>> 16)) << 16) + this._f * (s & 0xffff) + i) >>> 0;
}
this._index = this._n;
}
/**
* Apply the twist
*/
Random.prototype._twist = function () {
var mag01 = [0x0, this._a];
var y = 0, i = 0;
for (; i < this._n - this._m; i++) {
y = (this._mt[i] & this._upperMask) | (this._mt[i + 1] & this._lowerMask);
this._mt[i] = this._mt[i + this._m] ^ (y >>> 1) ^ (mag01[y & 0x1] & BITMASK32);
}
for (; i < this._n - 1; i++) {
y = (this._mt[i] & this._upperMask) | (this._mt[i + 1] & this._lowerMask);
this._mt[i] = this._mt[i + (this._m - this._n)] ^ (y >>> 1) ^ (mag01[y & 0x1] & BITMASK32);
}
y = (this._mt[this._n - 1] & this._upperMask) | (this._mt[0] & this._lowerMask);
this._mt[this._n - 1] = this._mt[this._m - 1] ^ (y >>> 1) ^ (mag01[y & 0x1] & BITMASK32);
this._index = 0;
};
/**
* Return next 32 bit integer number in sequence
*/
Random.prototype.nextInt = function () {
if (this._index >= this._n) {
this._twist();
}
var y = this._mt[this._index++];
y ^= y >>> this._u;
y ^= (y << this._s) & this._b;
y ^= (y << this._t) & this._c;
y ^= y >>> this._l;
return y >>> 0;
};
/**
* Return a random floating point number between [0, 1)
*/
Random.prototype.next = function () {
return this.nextInt() * (1.0 / 4294967296.0); // divided by 2^32
};
/**
* Return a random floating point in range [min, max) min is included, max is not included
*/
Random.prototype.floating = function (min, max) {
return (max - min) * this.next() + min;
};
/**
* Return a random integer in range [min, max] min is included, max is included.
* Implemented with rejection sampling, see https://medium.com/@betable/tifu-by-using-math-random-f1c308c4fd9d#.i13tdiu5a
*/
Random.prototype.integer = function (min, max) {
return Math.floor((max - min + 1) * this.next() + min);
};
/**
* Returns true or false randomly with 50/50 odds by default.
* By default the likelihood of returning a true is .5 (50%).
* @param likelihood takes values between [0, 1]
*/
Random.prototype.bool = function (likelihood) {
if (likelihood === void 0) { likelihood = 0.5; }
return this.next() <= likelihood;
};
/**
* Returns one element from an array at random
*/
Random.prototype.pickOne = function (array) {
return array[this.integer(0, array.length - 1)];
};
/**
* Returns a new array random picking elements from the original
* @param array Original array to pick from
* @param numPicks can be any positive number
* @param allowDuplicates indicates whether the returned set is allowed duplicates (it does not mean there will always be duplicates
* just that it is possible)
*/
Random.prototype.pickSet = function (array, numPicks, allowDuplicates) {
if (allowDuplicates === void 0) { allowDuplicates = false; }
if (allowDuplicates) {
return this._pickSetWithDuplicates(array, numPicks);
}
else {
return this._pickSetWithoutDuplicates(array, numPicks);
}
};
/**
* Returns a new array randomly picking elements in the original (not reused)
* @param numPicks must be less than or equal to the number of elements in the array.
*/
Random.prototype._pickSetWithoutDuplicates = function (array, numPicks) {
if (numPicks > array.length || numPicks < 0) {
throw new Error('Invalid number of elements to pick, must pick a value 0 < n <= length');
}
if (numPicks === array.length) {
return array;
}
var result = new Array(numPicks);
var currentPick = 0;
var tempArray = array.slice(0);
while (currentPick < numPicks) {
var index = this.integer(0, tempArray.length - 1);
result[currentPick++] = tempArray[index];
tempArray.splice(index, 1);
}
return result;
};
/**
* Returns a new array random picking elements from the original allowing duplicates
* @param numPicks can be any positive number
*/
Random.prototype._pickSetWithDuplicates = function (array, numPicks) {
// Typescript numbers are all floating point, so do we add check for int? (or floor the input?)
if (numPicks < 0) {
throw new Error('Invalid number of elements to pick, must pick a value 0 <= n < MAX_INT');
}
var result = new Array(numPicks);
for (var i = 0; i < numPicks; i++) {
result[i] = this.pickOne(array);
}
return result;
};
/**
* Returns a new array that has its elements shuffled. Using the Fisher/Yates method
* https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
*/
Random.prototype.shuffle = function (array) {
var tempArray = array.slice(0);
var swap = null;
for (var i = 0; i < tempArray.length - 2; i++) {
var randomIndex = this.integer(i, tempArray.length - 1);
swap = tempArray[i];
tempArray[i] = tempArray[randomIndex];
tempArray[randomIndex] = swap;
}
return tempArray;
};
/**
* Generate a list of random integer numbers
* @param length the length of the final array
* @param min the minimum integer number to generate inclusive
* @param max the maximum integer number to generate inclusive
*/
Random.prototype.range = function (length, min, max) {
var result = new Array(length);
for (var i = 0; i < length; i++) {
result[i] = this.integer(min, max);
}
return result;
};
/**
* Returns the result of a d4 dice roll
*/
Random.prototype.d4 = function () {
return this.integer(1, 4);
};
/**
* Returns the result of a d6 dice roll
*/
Random.prototype.d6 = function () {
return this.integer(1, 6);
};
/**
* Returns the result of a d8 dice roll
*/
Random.prototype.d8 = function () {
return this.integer(1, 8);
};
/**
* Returns the result of a d10 dice roll
*/
Random.prototype.d10 = function () {
return this.integer(1, 10);
};
/**
* Returns the result of a d12 dice roll
*/
Random.prototype.d12 = function () {
return this.integer(1, 12);
};
/**
* Returns the result of a d20 dice roll
*/
Random.prototype.d20 = function () {
return this.integer(1, 20);
};
return Random;
}());
/***/ }),
/***/ "./Particles.ts":
/*!**********************!*\
!*** ./Particles.ts ***!
\**********************/
/*! exports provided: EmitterType, ParticleImpl, Particle, ParticleEmitterImpl, ParticleEmitter */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EmitterType", function() { return EmitterType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ParticleImpl", function() { return ParticleImpl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Particle", function() { return Particle; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ParticleEmitterImpl", function() { return ParticleEmitterImpl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ParticleEmitter", function() { return ParticleEmitter; });
/* harmony import */ var _Actor__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Actor */ "./Actor.ts");
/* harmony import */ var _Drawing_Color__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Drawing/Color */ "./Drawing/Color.ts");
/* harmony import */ var _Algebra__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Algebra */ "./Algebra.ts");
/* harmony import */ var _Util_Util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Util/Util */ "./Util/Util.ts");
/* harmony import */ var _Util_DrawUtil__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Util/DrawUtil */ "./Util/DrawUtil.ts");
/* harmony import */ var _Traits_Index__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Traits/Index */ "./Traits/Index.ts");
/* harmony import */ var _Configurable__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Configurable */ "./Configurable.ts");
/* harmony import */ var _Math_Random__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Math/Random */ "./Math/Random.ts");
/* harmony import */ var _Collision_CollisionType__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Collision/CollisionType */ "./Collision/CollisionType.ts");
var __extends = (undefined && undefined.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
/**
* An enum that represents the types of emitter nozzles
*/
var EmitterType;
(function (EmitterType) {
/**
* Constant for the circular emitter type
*/
EmitterType[EmitterType["Circle"] = 0] = "Circle";
/**
* Constant for the rectangular emitter type
*/
EmitterType[EmitterType["Rectangle"] = 1] = "Rectangle";
})(EmitterType || (EmitterType = {}));
/**
* @hidden
*/
var ParticleImpl = /** @class */ (function () {
function ParticleImpl(emitterOrConfig, life, opacity, beginColor, endColor, position, velocity, acceleration, startSize, endSize) {
this.position = new _Algebra__WEBPACK_IMPORTED_MODULE_2__["Vector"](0, 0);
this.velocity = new _Algebra__WEBPACK_IMPORTED_MODULE_2__["Vector"](0, 0);
this.acceleration = new _Algebra__WEBPACK_IMPORTED_MODULE_2__["Vector"](0, 0);
this.particleRotationalVelocity = 0;
this.currentRotation = 0;
this.focus = null;
this.focusAccel = 0;
this.opacity = 1;
this.beginColor = _Drawing_Color__WEBPACK_IMPORTED_MODULE_1__["Color"].White;
this.endColor = _Drawing_Color__WEBPACK_IMPORTED_MODULE_1__["Color"].White;
// Life is counted in ms
this.life = 300;
this.fadeFlag = false;
// Color transitions
this._rRate = 1;
this._gRate = 1;
this._bRate = 1;
this._aRate = 0;
this._currentColor = _Drawing_Color__WEBPACK_IMPORTED_MODULE_1__["Color"].White;
this.emitter = null;
this.particleSize = 5;
this.particleSprite = null;
this.sizeRate = 0;
this.elapsedMultiplier = 0;
var emitter = emitterOrConfig;
if (emitter && !(emitterOrConfig instanceof ParticleEmitter)) {
var config = emitterOrConfig;
emitter = config.emitter;
life = config.life;
opacity = config.opacity;
endColor = config.endColor;
beginColor = config.beginColor;
position = config.position;
velocity = config.velocity;
acceleration = config.acceleration;
startSize = config.startSize;
endSize = config.endSize;
}
this.emitter = emitter;
this.life = life || this.life;
this.opacity = opacity || this.opacity;
this.endColor = endColor || this.endColor.clone();
this.beginColor = beginColor || this.beginColor.clone();
this._currentColor = this.beginColor.clone();
this.position = position || this.position;
this.velocity = velocity || this.velocity;
this.acceleration = acceleration || this.acceleration;
this._rRate = (this.endColor.r - this.beginColor.r) / this.life;
this._gRate = (this.endColor.g - this.beginColor.g) / this.life;
this._bRate = (this.endColor.b - this.beginColor.b) / this.life;
this._aRate = this.opacity / this.life;
this.startSize = startSize || 0;
this.endSize = endSize || 0;
if (this.endSize > 0 && this.startSize > 0) {
this.sizeRate = (this.endSize - this.startSize) / this.life;
this.particleSize = this.startSize;
}
}
ParticleImpl.prototype.kill = function () {
this.emitter.removeParticle(this);
};
ParticleImpl.prototype.update = function (delta) {
this.life = this.life - delta;
this.elapsedMultiplier = this.elapsedMultiplier + delta;
if (this.life < 0) {
this.kill();
}
if (this.fadeFlag) {
this.opacity = _Util_Util__WEBPACK_IMPORTED_MODULE_3__["clamp"](this._aRate * this.life, 0.0001, 1);
}
if (this.startSize > 0 && this.endSize > 0) {
this.particleSize = _Util_Util__WEBPACK_IMPORTED_MODULE_3__["clamp"](this.sizeRate * delta + this.particleSize, Math.min(this.startSize, this.endSize), Math.max(this.startSize, this.endSize));
}
this._currentColor.r = _Util_Util__WEBPACK_IMPORTED_MODULE_3__["clamp"](this._currentColor.r + this._rRate * delta, 0, 255);
this._currentColor.g = _Util_Util__WEBPACK_IMPORTED_MODULE_3__["clamp"](this._currentColor.g + this._gRate * delta, 0, 255);
this._currentColor.b = _Util_Util__WEBPACK_IMPORTED_MODULE_3__["clamp"](this._currentColor.b + this._bRate * delta, 0, 255);
this._currentColor.a = _Util_Util__WEBPACK_IMPORTED_MODULE_3__["clamp"](this.opacity, 0.0001, 1);
if (this.focus) {
var accel = this.focus
.sub(this.position)
.normalize()
.scale(this.focusAccel)
.scale(delta / 1000);
this.velocity = this.velocity.add(accel);
}
else {
this.velocity = this.velocity.add(this.acceleration.scale(delta / 1000));
}
this.position = this.position.add(this.velocity.scale(delta / 1000));
if (this.particleRotationalVelocity) {
this.currentRotation = (this.currentRotation + (this.particleRotationalVelocity * delta) / 1000) % (2 * Math.PI);
}
};
ParticleImpl.prototype.draw = function (ctx) {
if (this.particleSprite) {
this.particleSprite.rotation = this.currentRotation;
this.particleSprite.scale.setTo(this.particleSize, this.particleSize);
this.particleSprite.draw(ctx, this.position.x, this.position.y);
return;
}
this._currentColor.a = _Util_Util__WEBPACK_IMPORTED_MODULE_3__["clamp"](this.opacity, 0.0001, 1);
ctx.fillStyle = this._currentColor.toString();
ctx.beginPath();
ctx.arc(this.position.x, this.position.y, this.particleSize, 0, Math.PI * 2);
ctx.fill();
ctx.closePath();
};
return ParticleImpl;
}());
/**
* Particle is used in a [[ParticleEmitter]]
*/
var Particle = /** @class */ (function (_super) {
__extends(Particle, _super);
function Particle(emitterOrConfig, life, opacity, beginColor, endColor, position, velocity, acceleration, startSize, endSize) {
return _super.call(this, emitterOrConfig, life, opacity, beginColor, endColor, position, velocity, acceleration, startSize, endSize) || this;
}
return Particle;
}(Object(_Configurable__WEBPACK_IMPORTED_MODULE_6__["Configurable"])(ParticleImpl)));
/**
* @hidden
*/
var ParticleEmitterImpl = /** @class */ (function (_super) {
__extends(ParticleEmitterImpl, _super);
/**
* @param x The x position of the emitter
* @param y The y position of the emitter
* @param width The width of the emitter
* @param height The height of the emitter
*/
function ParticleEmitterImpl(xOrConfig, y, width, height) {
var _this = _super.call(this, typeof xOrConfig === 'number' ? { pos: new _Algebra__WEBPACK_IMPORTED_MODULE_2__["Vector"](xOrConfig, y), width: width, height: height } : xOrConfig) || this;
_this.numParticles = 0;
/**
* Gets or sets the isEmitting flag
*/
_this.isEmitting = true;
/**
* Gets or sets the backing particle collection
*/
_this.particles = null;
/**
* Gets or sets the backing deadParticle collection
*/
_this.deadParticles = null;
/**
* Gets or sets the minimum particle velocity
*/
_this.minVel = 0;
/**
* Gets or sets the maximum particle velocity
*/
_this.maxVel = 0;
/**
* Gets or sets the acceleration vector for all particles
*/
_this.acceleration = new _Algebra__WEBPACK_IMPORTED_MODULE_2__["Vector"](0, 0);
/**
* Gets or sets the minimum angle in radians
*/
_this.minAngle = 0;
/**
* Gets or sets the maximum angle in radians
*/
_this.maxAngle = 0;
/**
* Gets or sets the emission rate for particles (particles/sec)
*/
_this.emitRate = 1; //particles/sec
/**
* Gets or sets the life of each particle in milliseconds
*/
_this.particleLife = 2000;
/**
* Gets or sets the opacity of each particle from 0 to 1.0
*/
_this.opacity = 1;
/**
* Gets or sets the fade flag which causes particles to gradually fade out over the course of their life.
*/
_this.fadeFlag = false;
/**
* Gets or sets the optional focus where all particles should accelerate towards
*/
_this.focus = null;
/**
* Gets or sets the acceleration for focusing particles if a focus has been specified
*/
_this.focusAccel = 1;
/*
* Gets or sets the optional starting size for the particles
*/
_this.startSize = null;
/*
* Gets or sets the optional ending size for the particles
*/
_this.endSize = null;
/**
* Gets or sets the minimum size of all particles
*/
_this.minSize = 5;
/**
* Gets or sets the maximum size of all particles
*/
_this.maxSize = 5;
/**
* Gets or sets the beginning color of all particles
*/
_this.beginColor = _Drawing_Color__WEBPACK_IMPORTED_MODULE_1__["Color"].White;
/**
* Gets or sets the ending color of all particles
*/
_this.endColor = _Drawing_Color__WEBPACK_IMPORTED_MODULE_1__["Color"].White;
/**
* Gets or sets the sprite that a particle should use
* @warning Performance intensive
*/
_this.particleSprite = null;
/**
* Gets or sets the emitter type for the particle emitter
*/
_this.emitterType = EmitterType.Rectangle;
/**
* Gets or sets the emitter radius, only takes effect when the [[emitterType]] is [[EmitterType.Circle]]
*/
_this.radius = 0;
/**
* Gets or sets the particle rotational speed velocity
*/
_this.particleRotationalVelocity = 0;
/**
* Indicates whether particles should start with a random rotation
*/
_this.randomRotation = false;
_this._particlesToEmit = 0;
_this.body.collider.type = _Collision_CollisionType__WEBPACK_IMPORTED_MODULE_8__["CollisionType"].PreventCollision;
_this.particles = new _Util_Util__WEBPACK_IMPORTED_MODULE_3__["Collection"]();
_this.deadParticles = new _Util_Util__WEBPACK_IMPORTED_MODULE_3__["Collection"]();
_this.random = new _Math_Random__WEBPACK_IMPORTED_MODULE_7__["Random"]();
// Remove offscreen culling from particle emitters
for (var i = 0; i < _this.traits.length; i++) {
if (_this.traits[i] instanceof _Traits_Index__WEBPACK_IMPORTED_MODULE_5__["OffscreenCulling"]) {
_this.traits.splice(i, 1);
}
}
return _this;
}
ParticleEmitterImpl.prototype.removeParticle = function (particle) {
this.deadParticles.push(particle);
};
/**
* Causes the emitter to emit particles
* @param particleCount Number of particles to emit right now
*/
ParticleEmitterImpl.prototype.emitParticles = function (particleCount) {
for (var i = 0; i < particleCount; i++) {
this.particles.push(this._createParticle());
}
};
ParticleEmitterImpl.prototype.clearParticles = function () {
this.particles.clear();
};
// Creates a new particle given the constraints of the emitter
ParticleEmitterImpl.prototype._createParticle = function () {
// todo implement emitter constraints;
var ranX = 0;
var ranY = 0;
var angle = _Util_Util__WEBPACK_IMPORTED_MODULE_3__["randomInRange"](this.minAngle, this.maxAngle, this.random);
var vel = _Util_Util__WEBPACK_IMPORTED_MODULE_3__["randomInRange"](this.minVel, this.maxVel, this.random);
var size = this.startSize || _Util_Util__WEBPACK_IMPORTED_MODULE_3__["randomInRange"](this.minSize, this.maxSize, this.random);
var dx = vel * Math.cos(angle);
var dy = vel * Math.sin(angle);
if (this.emitterType === EmitterType.Rectangle) {
ranX = _Util_Util__WEBPACK_IMPORTED_MODULE_3__["randomInRange"](this.pos.x, this.pos.x + this.width, this.random);
ranY = _Util_Util__WEBPACK_IMPORTED_MODULE_3__["randomInRange"](this.pos.y, this.pos.y + this.height, this.random);
}
else if (this.emitterType === EmitterType.Circle) {
var radius = _Util_Util__WEBPACK_IMPORTED_MODULE_3__["randomInRange"](0, this.radius, this.random);
ranX = radius * Math.cos(angle) + this.pos.x;
ranY = radius * Math.sin(angle) + this.pos.y;
}
var p = new Particle(this, this.particleLife, this.opacity, this.beginColor, this.endColor, new _Algebra__WEBPACK_IMPORTED_MODULE_2__["Vector"](ranX, ranY), new _Algebra__WEBPACK_IMPORTED_MODULE_2__["Vector"](dx, dy), this.acceleration, this.startSize, this.endSize);
p.fadeFlag = this.fadeFlag;
p.particleSize = size;
if (this.particleSprite) {
p.particleSprite = this.particleSprite;
}
p.particleRotationalVelocity = this.particleRotationalVelocity;
if (this.randomRotation) {
p.currentRotation = _Util_Util__WEBPACK_IMPORTED_MODULE_3__["randomInRange"](0, Math.PI * 2, this.random);
}
if (this.focus) {
p.focus = this.focus.add(new _Algebra__WEBPACK_IMPORTED_MODULE_2__["Vector"](this.pos.x, this.pos.y));
p.focusAccel = this.focusAccel;
}
return p;
};
ParticleEmitterImpl.prototype.update = function (engine, delta) {
var _this = this;
_super.prototype.update.call(this, engine, delta);
if (this.isEmitting) {
this._particlesToEmit += this.emitRate * (delta / 1000);
//var numParticles = Math.ceil(this.emitRate * delta / 1000);
if (this._particlesToEmit > 1.0) {
this.emitParticles(Math.floor(this._particlesToEmit));
this._particlesToEmit = this._particlesToEmit - Math.floor(this._particlesToEmit);
}
}
this.particles.forEach(function (p) { return p.update(delta); });
this.deadParticles.forEach(function (p) { return _this.particles.removeElement(p); });
this.deadParticles.clear();
};
ParticleEmitterImpl.prototype.draw = function (ctx) {
// todo is there a more efficient to draw
// possibly use a webgl offscreen canvas and shaders to do particles?
this.particles.forEach(function (p) { return p.draw(ctx); });
};
ParticleEmitterImpl.prototype.debugDraw = function (ctx) {
_super.prototype.debugDraw.call(this, ctx);
ctx.fillStyle = _Drawing_Color__WEBPACK_IMPORTED_MODULE_1__["Color"].Black.toString();
ctx.fillText('Particles: ' + this.particles.count(), this.pos.x, this.pos.y + 20);
if (this.focus) {
ctx.fillRect(this.focus.x + this.pos.x, this.focus.y + this.pos.y, 3, 3);
_Util_DrawUtil__WEBPACK_IMPORTED_MODULE_4__["line"](ctx, _Drawing_Color__WEBPACK_IMPORTED_MODULE_1__["Color"].Yellow, this.focus.x + this.pos.x, this.focus.y + this.pos.y, this.center.x, this.center.y);
ctx.fillText('Focus', this.focus.x + this.pos.x, this.focus.y + this.pos.y);
}
};
return ParticleEmitterImpl;
}(_Actor__WEBPACK_IMPORTED_MODULE_0__["Actor"]));
/**
* Using a particle emitter is a great way to create interesting effects
* in your game, like smoke, fire, water, explosions, etc. `ParticleEmitter`
* extend [[Actor]] allowing you to use all of the features that come with.
*
* [[include:Particles.md]]
*/
var ParticleEmitter = /** @class */ (function (_super) {
__extends(ParticleEmitter, _super);
function ParticleEmitter(xOrConfig, y, width, height) {
return _super.call(this, xOrConfig, y, width, height) || this;
}
return ParticleEmitter;
}(Object(_Configurable__WEBPACK_IMPORTED_MODULE_6__["Configurable"])(ParticleEmitterImpl)));
/***/ }),
/***/ "./Physics.ts":
/*!********************!*\
!*** ./Physics.ts ***!
\********************/
/*! exports provided: CollisionResolutionStrategy, BroadphaseStrategy, Integrator, Physics */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CollisionResolutionStrategy", function() { return CollisionResolutionStrategy; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BroadphaseStrategy", function() { return BroadphaseStrategy; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Integrator", function() { return Integrator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Physics", function() { return Physics; });
/* harmony import */ var _Algebra__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Algebra */ "./Algebra.ts");
/* harmony import */ var _Util_Decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Util/Decorators */ "./Util/Decorators.ts");
var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
/**
* Possible collision resolution strategies
*
* The default is [[CollisionResolutionStrategy.Box]] which performs simple axis aligned arcade style physics.
*
* More advanced rigid body physics are enabled by setting [[CollisionResolutionStrategy.RigidBody]] which allows for complicated
* simulated physical interactions.
*/
var CollisionResolutionStrategy;
(function (CollisionResolutionStrategy) {
CollisionResolutionStrategy[CollisionResolutionStrategy["Box"] = 0] = "Box";
CollisionResolutionStrategy[CollisionResolutionStrategy["RigidBody"] = 1] = "RigidBody";
})(CollisionResolutionStrategy || (CollisionResolutionStrategy = {}));
/**
* Possible broadphase collision pair identification strategies
*
* The default strategy is [[BroadphaseStrategy.DynamicAABBTree]] which uses a binary tree of axis-aligned bounding boxes to identify
* potential collision pairs which is O(nlog(n)) faster. The other possible strategy is the [[BroadphaseStrategy.Naive]] strategy
* which loops over every object for every object in the scene to identify collision pairs which is O(n^2) slower.
*/
var BroadphaseStrategy;
(function (BroadphaseStrategy) {
BroadphaseStrategy[BroadphaseStrategy["Naive"] = 0] = "Naive";
BroadphaseStrategy[BroadphaseStrategy["DynamicAABBTree"] = 1] = "DynamicAABBTree";
})(BroadphaseStrategy || (BroadphaseStrategy = {}));
/**
* Possible numerical integrators for position and velocity
*/
var Integrator;
(function (Integrator) {
Integrator[Integrator["Euler"] = 0] = "Euler";
})(Integrator || (Integrator = {}));
/**
* The [[Physics]] object is the global configuration object for all Excalibur physics.
*
* [[include:Physics.md]]
*/
/* istanbul ignore next */
var Physics = /** @class */ (function () {
function Physics() {
}
/**
* Configures Excalibur to use box physics. Box physics which performs simple axis aligned arcade style physics.
*/
Physics.useBoxPhysics = function () {
Physics.collisionResolutionStrategy = CollisionResolutionStrategy.Box;
};
/**
* Configures Excalibur to use rigid body physics. Rigid body physics allows for complicated
* simulated physical interactions.
*/
Physics.useRigidBodyPhysics = function () {
Physics.collisionResolutionStrategy = CollisionResolutionStrategy.RigidBody;
};
Object.defineProperty(Physics, "dynamicTreeVelocityMultiplyer", {
get: function () {
return Physics.dynamicTreeVelocityMultiplier;
},
set: function (value) {
Physics.dynamicTreeVelocityMultiplier = value;
},
enumerable: false,
configurable: true
});
/**
* Global acceleration that is applied to all vanilla actors that have a [[CollisionType.Active|active]] collision type.
* Global acceleration won't effect [[Label|labels]], [[ScreenElement|ui actors]], or [[Trigger|triggers]] in Excalibur.
*
* This is a great way to globally simulate effects like gravity.
*/
Physics.acc = new _Algebra__WEBPACK_IMPORTED_MODULE_0__["Vector"](0, 0);
/**
* Globally switches all Excalibur physics behavior on or off.
*/
Physics.enabled = true;
/**
* Gets or sets the number of collision passes for Excalibur to perform on physics bodies.
*
* Reducing collision passes may cause things not to collide as expected in your game, but may increase performance.
*
* More passes can improve the visual quality of collisions when many objects are on the screen. This can reduce jitter, improve the
* collision resolution of fast move objects, or the stability of large numbers of objects stacked together.
*
* Fewer passes will improve the performance of the game at the cost of collision quality, more passes will improve quality at the
* cost of performance.
*
* The default is set to 5 passes which is a good start.
*/
Physics.collisionPasses = 5;
/**
* Gets or sets the broadphase pair identification strategy.
*
* The default strategy is [[BroadphaseStrategy.DynamicAABBTree]] which uses a binary tree of axis-aligned bounding boxes to identify
* potential collision pairs which is O(nlog(n)) faster. The other possible strategy is the [[BroadphaseStrategy.Naive]] strategy
* which loops over every object for every object in the scene to identify collision pairs which is O(n^2) slower.
*/
Physics.broadphaseStrategy = BroadphaseStrategy.DynamicAABBTree;
/**
* Globally switches the debug information for the broadphase strategy
*/
Physics.broadphaseDebug = false;
/**
* Show the normals as a result of collision on the screen.
*/
Physics.showCollisionNormals = false;
/**
* Show the position, velocity, and acceleration as graphical vectors.
*/
Physics.showMotionVectors = false;
/**
* Show the axis-aligned bounding boxes of the collision bodies on the screen.
*/
Physics.showBounds = false;
/**
* Show the bounding collision area shapes
*/
Physics.showArea = false;
/**
* Show points of collision interpreted by excalibur as a result of collision.
*/
Physics.showContacts = false;
/**
* Show the surface normals of the collision areas.
*/
Physics.showNormals = false;
/**
* Gets or sets the global collision resolution strategy (narrowphase).
*
* The default is [[CollisionResolutionStrategy.Box]] which performs simple axis aligned arcade style physics.
*
* More advanced rigid body physics are enabled by setting [[CollisionResolutionStrategy.RigidBody]] which allows for complicated
* simulated physical interactions.
*/
Physics.collisionResolutionStrategy = CollisionResolutionStrategy.Box;
/**
* The default mass to use if none is specified
*/
Physics.defaultMass = 10;
/**
* Gets or sets the position and velocity positional integrator, currently only Euler is supported.
*/
Physics.integrator = Integrator.Euler;
/**
* Number of steps to use in integration. A higher number improves the positional accuracy over time. This can be useful to increase
* if you have fast moving objects in your simulation or you have a large number of objects and need to increase stability.
*/
Physics.integrationSteps = 1;
/**
* Gets or sets whether rotation is allowed in a RigidBody collision resolution
*/
Physics.allowRigidBodyRotation = true;
/**
* Small value to help collision passes settle themselves after the narrowphase.
*/
Physics.collisionShift = 0.001;
/**
* Factor to add to the RigidBody BoundingBox, bounding box (dimensions += vel * dynamicTreeVelocityMultiplier);
*/
Physics.dynamicTreeVelocityMultiplier = 2;
/**
* Pad RigidBody BoundingBox by a constant amount
*/
Physics.boundsPadding = 5;
/**
* Surface epsilon is used to help deal with surface penetration
*/
Physics.surfaceEpsilon = 0.1;
/**
* Enable fast moving body checking, this enables checking for collision pairs via raycast for fast moving objects to prevent
* bodies from tunneling through one another.
*/
Physics.checkForFastBodies = true;
/**
* Disable minimum fast moving body raycast, by default if ex.Physics.checkForFastBodies = true Excalibur will only check if the
* body is moving at least half of its minimum dimension in an update. If ex.Physics.disableMinimumSpeedForFastBody is set to true,
* Excalibur will always perform the fast body raycast regardless of speed.
*/
Physics.disableMinimumSpeedForFastBody = false;
__decorate([
Object(_Util_Decorators__WEBPACK_IMPORTED_MODULE_1__["obsolete"])({
message: 'Alias for incorrect spelling used in older versions, will be removed in v0.25.0',
alternateMethod: 'dynamicTreeVelocityMultiplier'
})
], Physics, "dynamicTreeVelocityMultiplyer", null);
return Physics;
}());
/***/ }),
/***/ "./Polyfill.ts":
/*!*********************!*\
!*** ./Polyfill.ts ***!
\*********************/
/*! exports provided: polyfill */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "polyfill", function() { return polyfill; });
/* harmony import */ var core_js_es_array__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! core-js/es/array */ "../../node_modules/core-js/es/array/index.js");
/* harmony import */ var core_js_es_array__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(core_js_es_array__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var core_js_es_function__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! core-js/es/function */ "../../node_modules/core-js/es/function/index.js");
/* harmony import */ var core_js_es_function__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(core_js_es_function__WEBPACK_IMPORTED_MODULE_1__);
function polyfill() {
/* istanbul ignore next */
if (typeof window === 'undefined') {
window = {
audioContext: function () {
return;
}
};
}
/* istanbul ignore next */
if (typeof window !== 'undefined' && !window.requestAnimationFrame) {
window.requestAnimationFrame =
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function (callback) {
window.setInterval(callback, 1000 / 60);
};
}
/* istanbul ignore next */
if (typeof window !== 'undefined' && !window.cancelAnimationFrame) {
window.cancelAnimationFrame =
window.webkitCancelAnimationFrame ||
window.mozCancelAnimationFrame ||
function () {
return;
};
}
/* istanbul ignore next */
if (typeof window !== 'undefined' && !window.AudioContext) {
window.AudioContext =
window.AudioContext ||
window.webkitAudioContext ||
window.mozAudioContext ||
window.msAudioContext ||
window.oAudioContext;
}
/* istanbul ignore next */
if (typeof window !== 'undefined' && !window.devicePixelRatio) {
window.devicePixelRatio = window.devicePixelRatio || 1;
}
}
/***/ }),
/***/ "./PostProcessing/ColorBlindCorrector.ts":
/*!***********************************************!*\
!*** ./PostProcessing/ColorBlindCorrector.ts ***!
\***********************************************/
/*! exports provided: ColorBlindness, ColorBlindCorrector */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorBlindness", function() { return ColorBlindness; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorBlindCorrector", function() { return ColorBlindCorrector; });
/* harmony import */ var _Util_Log__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./../Util/Log */ "./Util/Log.ts");
var ColorBlindness;
(function (ColorBlindness) {
ColorBlindness[ColorBlindness["Protanope"] = 0] = "Protanope";
ColorBlindness[ColorBlindness["Deuteranope"] = 1] = "Deuteranope";
ColorBlindness[ColorBlindness["Tritanope"] = 2] = "Tritanope";
})(ColorBlindness || (ColorBlindness = {}));
/**
* This post processor can correct colors and simulate color blindness.
* It is possible to use this on every game, but the game's performance
* will suffer measurably. It's better to use it as a helpful tool while developing your game.
* Remember, the best practice is to design with color blindness in mind.
*
* [[include:ColorBlind.md]]
*/
var ColorBlindCorrector = /** @class */ (function () {
function ColorBlindCorrector(engine, simulate, colorMode) {
if (simulate === void 0) { simulate = false; }
if (colorMode === void 0) { colorMode = ColorBlindness.Protanope; }
this.engine = engine;
this.simulate = simulate;
this.colorMode = colorMode;
/*eslint-disable */
this._vertexShader = '' +
'attribute vec2 a_position;' +
'attribute vec2 a_texCoord;' +
'uniform vec2 u_resolution;' +
'varying vec2 v_texCoord;' +
'void main() {' +
// convert the rectangle from pixels to 0.0 to 1.0
'vec2 zeroToOne = a_position / u_resolution;' +
// convert from 0->1 to 0->2
'vec2 zeroToTwo = zeroToOne * 2.0;' +
// convert from 0->2 to -1->+1 (clipspace)
'vec2 clipSpace = zeroToTwo - 1.0;' +
'gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);' +
// pass the texCoord to the fragment shader
// The GPU will interpolate this value between points.
'v_texCoord = a_texCoord;' +
'}';
this._fragmentShader = 'precision mediump float;' +
// our texture
'uniform sampler2D u_image;' +
// the texCoords passed in from the vertex shader.
'varying vec2 v_texCoord;' +
// Color blind conversions
/*'mat3 m[9] =' +
'{' +
'mat3(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0 ),' + // normal
'mat3(0.567, 0.433, 0.0, 0.558, 0.442, 0.0, 0.0, 0.242, 0.758),' + // protanopia
'mat3(0.817, 0.183, 0.0, 0.333, 0.667, 0.0, 0.0, 0.125,0.875),' + // protanomaly
'mat3(0.625, 0.375, 0.0, 0.7, 0.3, 0.0, 0.0, 0.3,0.7 ),' + // deuteranopia
'mat3(0.8, 0.2, 0.0, 0.258, 0.742, 0.0, 0.0, 0.142,0.858),' + // deuteranomaly
'mat3(0.95, 0.05, 0.0, 0.0, 0.433, 0.567, 0.0, 0.475,0.525),' + // tritanopia
'mat3(0.967, 0.033, 0.0, 0.0, 0.733, 0.267, 0.0, 0.183,0.817),' + // tritanomaly
'mat3(0.299, 0.587, 0.114, 0.299, 0.587, 0.114, 0.299, 0.587,0.114),' + // achromatopsia
'mat3(0.618, 0.320, 0.062, 0.163, 0.775, 0.062, 0.163, 0.320,0.516)' + // achromatomaly
'};' +*/
'void main() {' +
'vec4 o = texture2D(u_image, v_texCoord);' +
// RGB to LMS matrix conversion
'float L = (17.8824 * o.r) + (43.5161 * o.g) + (4.11935 * o.b);' +
'float M = (3.45565 * o.r) + (27.1554 * o.g) + (3.86714 * o.b);' +
'float S = (0.0299566 * o.r) + (0.184309 * o.g) + (1.46709 * o.b);' +
// Simulate color blindness
'//MODE CODE//' +
/* Deuteranope for testing
'float l = 1.0 * L + 0.0 * M + 0.0 * S;' +
'float m = 0.494207 * L + 0.0 * M + 1.24827 * S;' +
'float s = 0.0 * L + 0.0 * M + 1.0 * S;' +*/
// LMS to RGB matrix conversion
'vec4 error;' +
'error.r = (0.0809444479 * l) + (-0.130504409 * m) + (0.116721066 * s);' +
'error.g = (-0.0102485335 * l) + (0.0540193266 * m) + (-0.113614708 * s);' +
'error.b = (-0.000365296938 * l) + (-0.00412161469 * m) + (0.693511405 * s);' +
'error.a = 1.0;' +
'vec4 diff = o - error;' +
'vec4 correction;' +
'correction.r = 0.0;' +
'correction.g = (diff.r * 0.7) + (diff.g * 1.0);' +
'correction.b = (diff.r * 0.7) + (diff.b * 1.0);' +
'correction = o + correction;' +
'correction.a = o.a;' +
'//SIMULATE//' +
'}';
this._internalCanvas = document.createElement('canvas');
this._internalCanvas.width = engine.drawWidth;
this._internalCanvas.height = engine.drawHeight;
// eslint-disable-next-line
this._gl = this._internalCanvas.getContext('webgl', { preserveDrawingBuffer: true });
this._program = this._gl.createProgram();
var fragmentShader = this._getShader('Fragment', this._getFragmentShaderByMode(colorMode));
var vertextShader = this._getShader('Vertex', this._vertexShader);
this._gl.attachShader(this._program, vertextShader);
this._gl.attachShader(this._program, fragmentShader);
this._gl.linkProgram(this._program);
if (!this._gl.getProgramParameter(this._program, this._gl.LINK_STATUS)) {
_Util_Log__WEBPACK_IMPORTED_MODULE_0__["Logger"].getInstance().error('Unable to link shader program!');
}
this._gl.useProgram(this._program);
}
ColorBlindCorrector.prototype._getFragmentShaderByMode = function (colorMode) {
var code = '';
if (colorMode === ColorBlindness.Protanope) {
code =
'float l = 0.0 * L + 2.02344 * M + -2.52581 * S;' +
'float m = 0.0 * L + 1.0 * M + 0.0 * S;' +
'float s = 0.0 * L + 0.0 * M + 1.0 * S;';
}
else if (colorMode === ColorBlindness.Deuteranope) {
code =
'float l = 1.0 * L + 0.0 * M + 0.0 * S;' +
'float m = 0.494207 * L + 0.0 * M + 1.24827 * S;' +
'float s = 0.0 * L + 0.0 * M + 1.0 * S;';
}
else if (colorMode === ColorBlindness.Tritanope) {
code =
'float l = 1.0 * L + 0.0 * M + 0.0 * S;' +
'float m = 0.0 * L + 1.0 * M + 0.0 * S;' +
'float s = -0.395913 * L + 0.801109 * M + 0.0 * S;';
}
if (this.simulate) {
this._fragmentShader = this._fragmentShader.replace('//SIMULATE//', 'gl_FragColor = error.rgba;');
}
else {
this._fragmentShader = this._fragmentShader.replace('//SIMULATE//', 'gl_FragColor = correction.rgba;');
}
return this._fragmentShader.replace('//MODE CODE//', code);
};
ColorBlindCorrector.prototype._setRectangle = function (x, y, width, height) {
var x1 = x;
var x2 = x + width;
var y1 = y;
var y2 = y + height;
this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array([x1, y1, x2, y1, x1, y2, x1, y2, x2, y1, x2, y2]), this._gl.STATIC_DRAW);
};
ColorBlindCorrector.prototype._getShader = function (type, program) {
var shader;
if (type === 'Fragment') {
shader = this._gl.createShader(this._gl.FRAGMENT_SHADER);
}
else if (type === 'Vertex') {
shader = this._gl.createShader(this._gl.VERTEX_SHADER);
}
else {
_Util_Log__WEBPACK_IMPORTED_MODULE_0__["Logger"].getInstance().error('Error unknown shader type', type);
}
this._gl.shaderSource(shader, program);
this._gl.compileShader(shader);
if (!this._gl.getShaderParameter(shader, this._gl.COMPILE_STATUS)) {
_Util_Log__WEBPACK_IMPORTED_MODULE_0__["Logger"].getInstance().error('Unable to compile shader!', this._gl.getShaderInfoLog(shader));
return null;
}
return shader;
};
ColorBlindCorrector.prototype.process = function (image, out) {
// look up where the vertex data needs to go.
var positionLocation = this._gl.getAttribLocation(this._program, 'a_position');
var texCoordLocation = this._gl.getAttribLocation(this._program, 'a_texCoord');
var texCoordBuffer = this._gl.createBuffer();
this._gl.bindBuffer(this._gl.ARRAY_BUFFER, texCoordBuffer);
this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array([0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0]), this._gl.STATIC_DRAW);
this._gl.enableVertexAttribArray(texCoordLocation);
this._gl.vertexAttribPointer(texCoordLocation, 2, this._gl.FLOAT, false, 0, 0);
// Create a texture.
var texture = this._gl.createTexture();
this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
// Set the parameters so we can render any size image.
this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, this._gl.NEAREST);
this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, this._gl.NEAREST);
// Flip the texture when unpacking into the gl context, gl reads textures in the opposite order as everything else :/
this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, 1);
// Upload the image into the texture.
this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, image);
// lookup uniforms
var resolutionLocation = this._gl.getUniformLocation(this._program, 'u_resolution');
// set the resolution
this._gl.uniform2f(resolutionLocation, this._internalCanvas.width, this._internalCanvas.height);
// Create a buffer for the position of the rectangle corners.
var positionBuffer = this._gl.createBuffer();
this._gl.bindBuffer(this._gl.ARRAY_BUFFER, positionBuffer);
this._gl.enableVertexAttribArray(positionLocation);
this._gl.vertexAttribPointer(positionLocation, 2, this._gl.FLOAT, false, 0, 0);
// Set a rectangle the same size as the image.
this._setRectangle(0, 0, image.width, image.height);
// Draw the rectangle.
this._gl.drawArrays(this._gl.TRIANGLES, 0, 6);
// Grab transformed image from internal canvas
var pixelData = new Uint8Array(image.width * image.height * 4);
this._gl.readPixels(0, 0, image.width, image.height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, pixelData);
image.data.set(pixelData);
out.putImageData(image, 0, 0);
};
return ColorBlindCorrector;
}());
/***/ }),
/***/ "./PostProcessing/Index.ts":
/*!*********************************!*\
!*** ./PostProcessing/Index.ts ***!
\*********************************/
/*! exports provided: ColorBlindness, ColorBlindCorrector */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _ColorBlindCorrector__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ColorBlindCorrector */ "./PostProcessing/ColorBlindCorrector.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorBlindness", function() { return _ColorBlindCorrector__WEBPACK_IMPORTED_MODULE_0__["ColorBlindness"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorBlindCorrector", function() { return _ColorBlindCorrector__WEBPACK_IMPORTED_MODULE_0__["ColorBlindCorrector"]; });
/* harmony import */ var _PostProcessor__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./PostProcessor */ "./PostProcessing/PostProcessor.ts");
/* empty/unused harmony star reexport */
/***/ }),
/***/ "./PostProcessing/PostProcessor.ts":
/*!*****************************************!*\
!*** ./PostProcessing/PostProcessor.ts ***!
\*****************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/***/ }),
/***/ "./Promises.ts":
/*!*********************!*\
!*** ./Promises.ts ***!
\*********************/
/*! exports provided: PromiseState, Promise */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PromiseState", function() { return PromiseState; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Promise", function() { return Promise; });
// Promises/A+ Spec http://promises-aplus.github.io/promises-spec/
/**
* Valid states for a promise to be in
*/
var PromiseState;
(function (PromiseState) {
PromiseState[PromiseState["Resolved"] = 0] = "Resolved";
PromiseState[PromiseState["Rejected"] = 1] = "Rejected";
PromiseState[PromiseState["Pending"] = 2] = "Pending";
})(PromiseState || (PromiseState = {}));
/**
* Promises are used to do asynchronous work and they are useful for
* creating a chain of actions. In Excalibur they are used for loading,
* sounds, animation, actions, and more.
*
* [[include:Promises.md]]
*/
var Promise = /** @class */ (function () {
function Promise() {
this._state = PromiseState.Pending;
this._successCallbacks = [];
this._rejectCallback = function () {
return;
};
}
/**
* Create and resolve a Promise with an optional value
* @param value An optional value to wrap in a resolved promise
*/
Promise.resolve = function (value) {
var promise = new Promise().resolve(value);
return promise;
};
/**
* Create and reject a Promise with an optional value
* @param value An optional value to wrap in a rejected promise
*/
Promise.reject = function (value) {
var promise = new Promise().reject(value);
return promise;
};
Promise.join = function () {
var promises = [];
if (arguments.length > 0 && !Array.isArray(arguments[0])) {
for (var _i = 0; _i < arguments.length; _i++) {
promises[_i - 0] = arguments[_i];
}
}
else if (arguments.length === 1 && Array.isArray(arguments[0])) {
promises = arguments[0];
}
var joinedPromise = new Promise();
if (!promises || !promises.length) {
return joinedPromise.resolve();
}
var total = promises.length;
var successes = 0;
var rejects = 0;
var errors = [];
promises.forEach(function (p) {
p.then(function () {
successes += 1;
if (successes === total) {
joinedPromise.resolve();
}
else if (successes + rejects + errors.length === total) {
joinedPromise.reject(errors);
}
}, function () {
rejects += 1;
if (successes + rejects + errors.length === total) {
joinedPromise.reject(errors);
}
}).error(function (e) {
errors.push(e);
if (errors.length + successes + rejects === total) {
joinedPromise.reject(errors);
}
});
});
return joinedPromise;
};
/**
* Chain success and reject callbacks after the promise is resolved
* @param successCallback Call on resolution of promise
* @param rejectCallback Call on rejection of promise
*/
Promise.prototype.then = function (successCallback, rejectCallback) {
if (successCallback) {
this._successCallbacks.push(successCallback);
// If the promise is already resolved call immediately
if (this.state() === PromiseState.Resolved) {
try {
successCallback.call(this, this._value);
}
catch (e) {
this._handleError(e);
}
}
}
if (rejectCallback) {
this._rejectCallback = rejectCallback;
// If the promise is already rejected call immediately
if (this.state() === PromiseState.Rejected) {
try {
rejectCallback.call(this, this._value);
}
catch (e) {
this._handleError(e);
}
}
}
return this;
};
/**
* Add an error callback to the promise
* @param errorCallback Call if there was an error in a callback
*/
Promise.prototype.error = function (errorCallback) {
if (errorCallback) {
this._errorCallback = errorCallback;
}
return this;
};
/**
* Resolve the promise and pass an option value to the success callbacks
* @param value Value to pass to the success callbacks
*/
Promise.prototype.resolve = function (value) {
var _this = this;
if (this._state === PromiseState.Pending) {
this._value = value;
try {
this._state = PromiseState.Resolved;
this._successCallbacks.forEach(function (cb) {
cb.call(_this, _this._value);
});
}
catch (e) {
this._handleError(e);
}
}
else {
throw new Error('Cannot resolve a promise that is not in a pending state!');
}
return this;
};
/**
* Reject the promise and pass an option value to the reject callbacks
* @param value Value to pass to the reject callbacks
*/
Promise.prototype.reject = function (value) {
if (this._state === PromiseState.Pending) {
this._value = value;
try {
this._state = PromiseState.Rejected;
this._rejectCallback.call(this, this._value);
}
catch (e) {
this._handleError(e);
}
}
else {
throw new Error('Cannot reject a promise that is not in a pending state!');
}
return this;
};
/**
* Inspect the current state of a promise
*/
Promise.prototype.state = function () {
return this._state;
};
Promise.prototype._handleError = function (e) {
if (this._errorCallback) {
this._errorCallback.call(this, e);
}
else {
// rethrow error
throw e;
}
};
return Promise;
}());
/***/ }),
/***/ "./Resources/Gif.ts":
/*!**************************!*\
!*** ./Resources/Gif.ts ***!
\**************************/
/*! exports provided: Gif, Stream, ParseGif */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Gif", function() { return Gif; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Stream", function() { return Stream; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ParseGif", function() { return ParseGif; });
/* harmony import */ var _Resource__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Resource */ "./Resources/Resource.ts");
/* harmony import */ var _Promises__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Promises */ "./Promises.ts");
/* harmony import */ var _Texture__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Texture */ "./Resources/Texture.ts");
/* harmony import */ var _Drawing_Color__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Drawing/Color */ "./Drawing/Color.ts");
/* harmony import */ var _Drawing_SpriteSheet__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Drawing/SpriteSheet */ "./Drawing/SpriteSheet.ts");
var __extends = (undefined && undefined.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
/**
* The [[Texture]] object allows games built in Excalibur to load image resources.
* [[Texture]] is an [[Loadable]] which means it can be passed to a [[Loader]]
* to pre-load before starting a level or game.
*
* [[include:Textures.md]]
*/
var Gif = /** @class */ (function (_super) {
__extends(Gif, _super);
/**
* @param path Path to the image resource
* @param color Optionally set the color to treat as transparent the gif, by default [[Color.Magenta]]
* @param bustCache Optionally load texture with cache busting
*/
function Gif(path, color, bustCache) {
if (color === void 0) { color = _Drawing_Color__WEBPACK_IMPORTED_MODULE_3__["Color"].Magenta; }
if (bustCache === void 0) { bustCache = true; }
var _this = _super.call(this, path, 'arraybuffer', bustCache) || this;
_this.path = path;
_this.color = color;
_this.bustCache = bustCache;
/**
* A [[Promise]] that resolves when the Texture is loaded.
*/
_this.loaded = new _Promises__WEBPACK_IMPORTED_MODULE_1__["Promise"]();
_this._isLoaded = false;
_this._stream = null;
_this._gif = null;
_this._texture = [];
_this._animation = null;
_this._transparentColor = null;
_this._transparentColor = color;
return _this;
}
/**
* Returns true if the Texture is completely loaded and is ready
* to be drawn.
*/
Gif.prototype.isLoaded = function () {
return this._isLoaded;
};
/**
* Begins loading the texture and returns a promise to be resolved on completion
*/
Gif.prototype.load = function () {
var _this = this;
var complete = new _Promises__WEBPACK_IMPORTED_MODULE_1__["Promise"]();
var loaded = _super.prototype.load.call(this);
loaded.then(function () {
_this._stream = new Stream(_this.getData());
_this._gif = new ParseGif(_this._stream, _this._transparentColor);
var promises = [];
for (var imageIndex = 0; imageIndex < _this._gif.images.length; imageIndex++) {
var texture = new _Texture__WEBPACK_IMPORTED_MODULE_2__["Texture"](_this._gif.images[imageIndex].src, false);
_this._texture.push(texture);
promises.push(texture.load());
}
_Promises__WEBPACK_IMPORTED_MODULE_1__["Promise"].join(promises).then(function () {
_this._isLoaded = true;
complete.resolve(_this._texture);
});
}, function () {
complete.reject('Error loading texture.');
});
return complete;
};
Gif.prototype.asSprite = function (id) {
if (id === void 0) { id = 0; }
var sprite = this._texture[id].asSprite();
return sprite;
};
Gif.prototype.asSpriteSheet = function () {
var spriteArray = this._texture.map(function (texture) {
return texture.asSprite();
});
return new _Drawing_SpriteSheet__WEBPACK_IMPORTED_MODULE_4__["SpriteSheet"](spriteArray);
};
Gif.prototype.asAnimation = function (engine, speed) {
var spriteSheet = this.asSpriteSheet();
this._animation = spriteSheet.getAnimationForAll(engine, speed);
return this._animation;
};
Object.defineProperty(Gif.prototype, "readCheckBytes", {
get: function () {
return this._gif.checkBytes;
},
enumerable: false,
configurable: true
});
return Gif;
}(_Resource__WEBPACK_IMPORTED_MODULE_0__["Resource"]));
var bitsToNum = function (ba) {
return ba.reduce(function (s, n) {
return s * 2 + n;
}, 0);
};
var byteToBitArr = function (bite) {
var a = [];
for (var i = 7; i >= 0; i--) {
a.push(!!(bite & (1 << i)));
}
return a;
};
var Stream = /** @class */ (function () {
function Stream(dataArray) {
var _this = this;
this.data = null;
this.len = 0;
this.position = 0;
this.readByte = function () {
if (_this.position >= _this.data.byteLength) {
throw new Error('Attempted to read past end of stream.');
}
return _this.data[_this.position++];
};
this.readBytes = function (n) {
var bytes = [];
for (var i = 0; i < n; i++) {
bytes.push(_this.readByte());
}
return bytes;
};
this.read = function (n) {
var s = '';
for (var i = 0; i < n; i++) {
s += String.fromCharCode(_this.readByte());
}
return s;
};
this.readUnsigned = function () {
// Little-endian.
var a = _this.readBytes(2);
return (a[1] << 8) + a[0];
};
this.data = new Uint8Array(dataArray);
this.len = this.data.byteLength;
if (this.len === 0) {
throw new Error('No data loaded from file');
}
}
return Stream;
}());
var lzwDecode = function (minCodeSize, data) {
// TODO: Now that the GIF parser is a bit different, maybe this should get an array of bytes instead of a String?
var pos = 0; // Maybe this streaming thing should be merged with the Stream?
var readCode = function (size) {
var code = 0;
for (var i = 0; i < size; i++) {
if (data.charCodeAt(pos >> 3) & (1 << (pos & 7))) {
code |= 1 << i;
}
pos++;
}
return code;
};
var output = [];
var clearCode = 1 << minCodeSize;
var eoiCode = clearCode + 1;
var codeSize = minCodeSize + 1;
var dict = [];
var clear = function () {
dict = [];
codeSize = minCodeSize + 1;
for (var i = 0; i < clearCode; i++) {
dict[i] = [i];
}
dict[clearCode] = [];
dict[eoiCode] = null;
};
var code;
var last;
while (true) {
last = code;
code = readCode(codeSize);
if (code === clearCode) {
clear();
continue;
}
if (code === eoiCode) {
break;
}
if (code < dict.length) {
if (last !== clearCode) {
dict.push(dict[last].concat(dict[code][0]));
}
}
else {
if (code !== dict.length) {
throw new Error('Invalid LZW code.');
}
dict.push(dict[last].concat(dict[last][0]));
}
output.push.apply(output, dict[code]);
if (dict.length === 1 << codeSize && codeSize < 12) {
// If we're at the last code and codeSize is 12, the next code will be a clearCode, and it'll be 12 bits long.
codeSize++;
}
}
// I don't know if this is technically an error, but some GIFs do it.
//if (Math.ceil(pos / 8) !== data.length) throw new Error('Extraneous LZW bytes.');
return output;
};
// The actual parsing; returns an object with properties.
var ParseGif = /** @class */ (function () {
function ParseGif(stream, color) {
var _this = this;
if (color === void 0) { color = _Drawing_Color__WEBPACK_IMPORTED_MODULE_3__["Color"].Magenta; }
this._st = null;
this._handler = {};
this._transparentColor = null;
this.frames = [];
this.images = [];
this.globalColorTable = [];
this.checkBytes = [];
// LZW (GIF-specific)
this.parseColorTable = function (entries) {
// Each entry is 3 bytes, for RGB.
var ct = [];
for (var i = 0; i < entries; i++) {
var rgb = _this._st.readBytes(3);
var rgba = '#' +
rgb
.map(function (x) {
var hex = x.toString(16);
return hex.length === 1 ? '0' + hex : hex;
})
.join('');
ct.push(rgba);
}
return ct;
};
this.readSubBlocks = function () {
var size, data;
data = '';
do {
size = _this._st.readByte();
data += _this._st.read(size);
} while (size !== 0);
return data;
};
this.parseHeader = function () {
var hdr = {
sig: null,
ver: null,
width: null,
height: null,
colorRes: null,
globalColorTableSize: null,
gctFlag: null,
sorted: null,
globalColorTable: [],
bgColor: null,
pixelAspectRatio: null // if not 0, aspectRatio = (pixelAspectRatio + 15) / 64
};
hdr.sig = _this._st.read(3);
hdr.ver = _this._st.read(3);
if (hdr.sig !== 'GIF') {
throw new Error('Not a GIF file.'); // XXX: This should probably be handled more nicely.
}
hdr.width = _this._st.readUnsigned();
hdr.height = _this._st.readUnsigned();
var bits = byteToBitArr(_this._st.readByte());
hdr.gctFlag = bits.shift();
hdr.colorRes = bitsToNum(bits.splice(0, 3));
hdr.sorted = bits.shift();
hdr.globalColorTableSize = bitsToNum(bits.splice(0, 3));
hdr.bgColor = _this._st.readByte();
hdr.pixelAspectRatio = _this._st.readByte(); // if not 0, aspectRatio = (pixelAspectRatio + 15) / 64
if (hdr.gctFlag) {
hdr.globalColorTable = _this.parseColorTable(1 << (hdr.globalColorTableSize + 1));
_this.globalColorTable = hdr.globalColorTable;
}
if (_this._handler.hdr && _this._handler.hdr(hdr)) {
_this.checkBytes.push(_this._handler.hdr);
}
};
this.parseExt = function (block) {
var parseGCExt = function (block) {
_this.checkBytes.push(_this._st.readByte()); // Always 4
var bits = byteToBitArr(_this._st.readByte());
block.reserved = bits.splice(0, 3); // Reserved; should be 000.
block.disposalMethod = bitsToNum(bits.splice(0, 3));
block.userInput = bits.shift();
block.transparencyGiven = bits.shift();
block.delayTime = _this._st.readUnsigned();
block.transparencyIndex = _this._st.readByte();
block.terminator = _this._st.readByte();
if (_this._handler.gce && _this._handler.gce(block)) {
_this.checkBytes.push(_this._handler.gce);
}
};
var parseComExt = function (block) {
block.comment = _this.readSubBlocks();
if (_this._handler.com && _this._handler.com(block)) {
_this.checkBytes.push(_this._handler.com);
}
};
var parsePTExt = function (block) {
_this.checkBytes.push(_this._st.readByte()); // Always 12
block.ptHeader = _this._st.readBytes(12);
block.ptData = _this.readSubBlocks();
if (_this._handler.pte && _this._handler.pte(block)) {
_this.checkBytes.push(_this._handler.pte);
}
};
var parseAppExt = function (block) {
var parseNetscapeExt = function (block) {
_this.checkBytes.push(_this._st.readByte()); // Always 3
block.unknown = _this._st.readByte(); // ??? Always 1? What is this?
block.iterations = _this._st.readUnsigned();
block.terminator = _this._st.readByte();
if (_this._handler.app && _this._handler.app.NETSCAPE && _this._handler.app.NETSCAPE(block)) {
_this.checkBytes.push(_this._handler.app);
}
};
var parseUnknownAppExt = function (block) {
block.appData = _this.readSubBlocks();
// FIXME: This won't work if a handler wants to match on any identifier.
if (_this._handler.app && _this._handler.app[block.identifier] && _this._handler.app[block.identifier](block)) {
_this.checkBytes.push(_this._handler.app[block.identifier]);
}
};
_this.checkBytes.push(_this._st.readByte()); // Always 11
block.identifier = _this._st.read(8);
block.authCode = _this._st.read(3);
switch (block.identifier) {
case 'NETSCAPE':
parseNetscapeExt(block);
break;
default:
parseUnknownAppExt(block);
break;
}
};
var parseUnknownExt = function (block) {
block.data = _this.readSubBlocks();
if (_this._handler.unknown && _this._handler.unknown(block)) {
_this.checkBytes.push(_this._handler.unknown);
}
};
block.label = _this._st.readByte();
switch (block.label) {
case 0xf9:
block.extType = 'gce';
parseGCExt(block);
break;
case 0xfe:
block.extType = 'com';
parseComExt(block);
break;
case 0x01:
block.extType = 'pte';
parsePTExt(block);
break;
case 0xff:
block.extType = 'app';
parseAppExt(block);
break;
default:
block.extType = 'unknown';
parseUnknownExt(block);
break;
}
};
this.parseImg = function (img) {
var deinterlace = function (pixels, width) {
// Of course this defeats the purpose of interlacing. And it's *probably*
// the least efficient way it's ever been implemented. But nevertheless...
var newPixels = new Array(pixels.length);
var rows = pixels.length / width;
var cpRow = function (toRow, fromRow) {
var fromPixels = pixels.slice(fromRow * width, (fromRow + 1) * width);
newPixels.splice.apply(newPixels, [toRow * width, width].concat(fromPixels));
};
var offsets = [0, 4, 2, 1];
var steps = [8, 8, 4, 2];
var fromRow = 0;
for (var pass = 0; pass < 4; pass++) {
for (var toRow = offsets[pass]; toRow < rows; toRow += steps[pass]) {
cpRow(toRow, fromRow);
fromRow++;
}
}
return newPixels;
};
img.leftPos = _this._st.readUnsigned();
img.topPos = _this._st.readUnsigned();
img.width = _this._st.readUnsigned();
img.height = _this._st.readUnsigned();
var bits = byteToBitArr(_this._st.readByte());
img.lctFlag = bits.shift();
img.interlaced = bits.shift();
img.sorted = bits.shift();
img.reserved = bits.splice(0, 2);
img.lctSize = bitsToNum(bits.splice(0, 3));
if (img.lctFlag) {
img.lct = _this.parseColorTable(1 << (img.lctSize + 1));
}
img.lzwMinCodeSize = _this._st.readByte();
var lzwData = _this.readSubBlocks();
img.pixels = lzwDecode(img.lzwMinCodeSize, lzwData);
if (img.interlaced) {
// Move
img.pixels = deinterlace(img.pixels, img.width);
}
_this.frames.push(img);
_this.arrayToImage(img);
if (_this._handler.img && _this._handler.img(img)) {
_this.checkBytes.push(_this._handler);
}
};
this.parseBlock = function () {
var block = {
sentinel: _this._st.readByte(),
type: ''
};
var blockChar = String.fromCharCode(block.sentinel);
switch (blockChar) {
case '!':
block.type = 'ext';
_this.parseExt(block);
break;
case ',':
block.type = 'img';
_this.parseImg(block);
break;
case ';':
block.type = 'eof';
if (_this._handler.eof && _this._handler.eof(block)) {
_this.checkBytes.push(_this._handler.eof);
}
break;
default:
throw new Error('Unknown block: 0x' + block.sentinel.toString(16));
}
if (block.type !== 'eof') {
_this.parseBlock();
}
};
this.arrayToImage = function (frame) {
var count = 0;
var c = document.createElement('canvas');
c.id = count.toString();
c.width = frame.width;
c.height = frame.height;
count++;
var context = c.getContext('2d');
var pixSize = 1;
var y = 0;
var x = 0;
for (var i = 0; i < frame.pixels.length; i++) {
if (x % frame.width === 0) {
y++;
x = 0;
}
if (_this.globalColorTable[frame.pixels[i]] === _this._transparentColor.toHex()) {
context.fillStyle = "rgba(0, 0, 0, 0)";
}
else {
context.fillStyle = _this.globalColorTable[frame.pixels[i]];
}
context.fillRect(x, y, pixSize, pixSize);
x++;
}
var img = new Image();
img.src = c.toDataURL();
_this.images.push(img);
};
this._st = stream;
this._handler = {};
this._transparentColor = color;
this.parseHeader();
this.parseBlock();
}
return ParseGif;
}());
/***/ }),
/***/ "./Resources/Index.ts":
/*!****************************!*\
!*** ./Resources/Index.ts ***!
\****************************/
/*! exports provided: Resource, Sound, AudioContextFactory, AudioInstanceFactory, AudioInstance, WebAudioInstance, Texture, Gif, Stream, ParseGif */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _Resource__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Resource */ "./Resources/Resource.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Resource", function() { return _Resource__WEBPACK_IMPORTED_MODULE_0__["Resource"]; });
/* harmony import */ var _Sound_Index__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Sound/Index */ "./Resources/Sound/Index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Sound", function() { return _Sound_Index__WEBPACK_IMPORTED_MODULE_1__["Sound"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AudioContextFactory", function() { return _Sound_Index__WEBPACK_IMPORTED_MODULE_1__["AudioContextFactory"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AudioInstanceFactory", function() { return _Sound_Index__WEBPACK_IMPORTED_MODULE_1__["AudioInstanceFactory"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AudioInstanc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment